TECHNOLOGY 

Published on

Training on GCP

Google has made the deep learning training and deployment process streamlined by allowing us to train models, store them, and deploy them with minimal code. Before training in the cloud, we should first train the model locally to confirm everything works as intended.

To begin, we must set some environment variables and organize our project files into the correct structure required by Cloud ML. Inside the training folder in this chapter’s GitHub repository, you will find the correct file layout. The __init__.py file simply tells GCP that our folder contains an executable Python package.

Next, define the job directory and training data path:

JOB_DIR="model_folder"
TRAIN_DATA="/path/to/data"
  

Now train the model locally using Cloud ML’s local runner:

gcloud ml-engine local train \
    --job-dir $JOB_DIR \
    --module-name trainer.task \
    --package-path trainer/ \
    -- --train-file $TRAIN_DATA
  

If your model trains successfully locally, you are ready for cloud training.

Cloud Training Setup

Training on Cloud ML is submitted as a job. The platform automatically sets up the environment, runs the training, and cleans up afterward.

Each training job must have a unique name. We will call our job classifier_model.

Instead of a local job directory, we now point Cloud ML to a folder inside our Google Cloud Storage bucket.

Choose the closest region to your location in the United States:

  • us-west1
  • us-central1
  • us-east1
JOB_NAME="classifier_model"
JOB_DIR="gs://classifier_bucket123/$JOB_NAME"
PACKAGE_STAGING_PATH="gs://classifier_bucket123"
MAIN_TRAINER_MODULE="trainer.simple_classifier"
REGION="us-east1"
TRAIN_DATA="gs://classifier_bucket123/creditcard.csv"
  

Submit the Cloud Training Job

Send the job to Cloud ML with:

gcloud ml-engine jobs submit training $JOB_NAME \
    --staging-bucket $PACKAGE_STAGING_PATH \
    --job-dir $JOB_DIR \
    --package-path /trainer \
    --module-name $MAIN_TRAINER_MODULE \
    --runtime-version 1.8 \
    --region $REGION \
    -- --train-file $TRAIN_DATA
  

The --runtime-version must match your installed version of TensorFlow. You can check your version by running:

python -c "import tensorflow as tf; print(tf.__version__)"
  

Monitor Training Progress

After submitting the job, Cloud ML will confirm that training has started. You can log in to the GCP console and use the Jobs section to check:

  • Training metrics
  • Error messages
  • Output logs
  • Resource usage

This information provides the same visibility you'd normally see when training locally.

When training is complete, the script will output the SavedModel binaries to your Google Cloud Storage bucket. If you have reached this stage successfully, you are ready to deploy the model as an API.

For a 10-Year-Old: Simple Explanation

Imagine you are teaching a robot how to understand information. First you teach it at home (your computer), then you send it to Google’s huge computer school so it can learn even better.

  • You set up the robot’s school folder.
  • You teach it at home to make sure it works.
  • You send it to Google’s supercomputers to train faster.
  • Google shows you its progress online.

When Google finishes training your robot, it becomes smart enough to help real people!

Picture
Published on

Artificial Intelligence – Deploying for Online Learning on GCP

Deploying a TensorFlow SavedModel to Google Cloud Platform (GCP) lets us run predictions online, at scale, without managing servers directly.

Your TensorFlow model must be stored in a Google Cloud Storage bucket. This includes the saved_model.pb file.

Step 1: Create a Deployed Model Object

First, create the model container on GCP:

gcloud ml-engine models create "deployed_classifier"
  

This prepares a container where future versions will live.

Step 2: Tell GCP Where the SavedModel Files Are

Set the environment variable that points to the model binaries:

DEPLOYMENT_SOURCE="gs://classifier_bucket123/classifier_model/binaries"
  

Step 3: Deploy the Model Version

Deploy a version of your model to Google Cloud ML Engine:

gcloud ml-engine versions create "version1" \
    --model "deployed_classifier" \
    --origin $DEPLOYMENT_SOURCE \
    --runtime-version 1.9
  

The deployment process may take a few minutes.

Step 4: Prepare Data for Prediction

Define the variables used for prediction:

MODEL_NAME="deployed_classifier"
INPUT_DATA_FILE="test.json"
VERSION_NAME="version1"
  

The test.json file contains a sample JSON input.

Step 5: Request a Prediction

Send a prediction request to your deployed model:

gcloud ml-engine predict \
    --model $MODEL_NAME \
    --version $VERSION_NAME \
    --json-instances $INPUT_DATA_FILE
  

You’ll receive JSON output containing the prediction probabilities.

Success! Your Model Is Live □

Your deployed model can now be called from apps, websites, backend services, or automated systems.

For a 10-Year-Old: Super Simple Explanation

You built a smart robot and now you're putting it on the internet.

Here’s what happened:

  • You put the robot’s brain online (Google Cloud Storage).
  • You told Google your robot exists.
  • You told Google where the robot’s brain file is.
  • You turned the robot on (created a version).
  • You asked the robot a question (prediction command).

The robot replies:

  • “This looks like fraud (90% sure)”
  • “This does NOT look like fraud (10% sure)”

Your robot now lives in the cloud and people can ask it questions anytime!

Picture
Published on

Using an API to Get Predictions

After you deploy a machine learning model on Google Cloud, you can call it from your own application through an API. Below is a simple walkthrough showing how to:


  • Set up Google Cloud service account credentials
  • Write a Python script to send data to the model
  • Create a simple Flask API to return predictions

1. Create a Google Cloud Service Account

First, you need a service account key so your app can access the model.


  1. Go to APIs & Services → Credentials
  2. Create a service account key
  3. Download it as a JSON file

Set this environment variable:

export GOOGLE_APPLICATION_CREDENTIALS="my-service-key.json"

2. Python Client for Sending Data (gcp_client.py)

This script sends data to your deployed model and returns a prediction.

import google.auth
from googleapiclient.discovery import build

credentials, project_id = google.auth.default()
ml = build("ml", "v1", credentials=credentials)

def call_model(features):
    model = "deployed_classifier"
    version = "v1"

    endpoint = f"projects/{project_id}/models/{model}/versions/{version}"
    body = {"instances": [{"x": features}]}

    resp = ml.projects().predict(name=endpoint, body=body).execute()
    return resp.get("predictions", [])

3. Flask App (app.py)

This Flask app exposes a /predict endpoint.

from flask import Flask, request, jsonify
from flask_cors import CORS
from gcp_client import call_model

app = Flask(__name__)
CORS(app)

@app.route("/predict", methods=["POST"])
def predict():
    data = request.get_json(force=True)
    features = data.get("features")

    if features is None:
        return jsonify({"error": "Missing features"}), 400

    preds = call_model(features)
    return jsonify({"prediction": preds[0] if preds else None})

if __name__ == "__main__":
    app.run(debug=True)

4. Run the App

Run this:

export FLASK_APP=app.py
flask run


Test with:

curl -X POST http://127.0.0.1:5000/predict \
  -H "Content-Type: application/json" \
  -d '{"features":[1,2,3,4]}'

Explain Like I'm 10

Imagine a super-smart robot in Google’s cloud. If you send it numbers, it sends back answers.


The service key is your pass that lets your app talk to the robot.

gcp_client.py is like a phone that calls the robot.

app.py is like a receptionist that takes questions and returns answers.

Image description
Published on
Artificial Intelligence – Scaling Your Applications

Scalability describes how well a system can handle increasing workloads without slowing down or failing. When we build software—especially machine learning or AI applications—we want them to remain fast, reliable, and stable even as more users or larger datasets place greater demands on the system.


There are two main strategies for scaling an application: scaling up and scaling out.

1. Scaling Up (Vertical Scaling)

Scaling up means improving the hardware of a single machine so it can handle more work.

Examples include:

  • Upgrading from a CPU-based machine to one with powerful GPUs
  • Adding more memory (RAM)
  • Switching to a larger cloud instance with more processing capability

This approach is often simple—you just move your existing program to a stronger machine. But it has limits, because there’s only so much hardware you can add to one system.


2. Scaling Out (Horizontal Scaling)


Scaling out means spreading the workload across multiple workers or machines.


Instead of one machine doing all the work, several machines share the tasks.
This method is more flexible and can grow almost indefinitely.


A common tool for scaling out big workloads is Apache Spark, which helps distribute large computations across an entire cluster of machines.

Scaling Out TensorFlow


While scaling up can be achieved with a single hardware change, scaling out TensorFlow requires distributing the training process across multiple devices. This allows:


  • Faster training
  • The ability to process much larger datasets
  • More resilient and powerful system design

In this section, we focus specifically on how to scale out TensorFlow, using distributed training techniques that allow many machines to work together during model training.


Simple Explanation

Imagine you have a giant pile of homework. You can handle it two different ways:


Scaling Up = Getting Stronger Yourself

This is like sharpening your pencil, getting a bigger desk, and maybe drinking hot chocolate so you can work faster.


It’s still just you, but now you can work a bit quicker because you have better tools.


Scaling Out = Getting More Friends to Help

Instead of doing the homework alone, you ask your friends to help.
Everyone takes a piece of the work, and you finish much faster.


This is what computers do when they “scale out”—lots of machines help with the same problem.


TensorFlow Example


If your homework is too big for just you, you either:


  • Work on a bigger desk (scaling up), or
  • Get a whole team to help you (scaling out)


TensorFlow scaling out is like forming a homework team where each person solves a small part, and together you finish the assignment super fast.


Picture
Published on
Artificial Intelligence – Scaling Out with Distributed TensorFlow

As machine learning models grow larger and require more computation, a single machine—or even a single GPU—may not be powerful enough to train them efficiently. To overcome this limitation, TensorFlow provides mechanisms to distribute training across multiple machines or devices, allowing us to scale out our compute resources.

Although several distributed frameworks exist—native Distributed TensorFlow, TensorFlowOnSpark, and Horovod—this section focuses exclusively on native Distributed TensorFlow, which is built directly into TensorFlow’s core design.

Approaches to Distributed Training

In distributed systems, there are two main strategies for dividing the workload: model parallelism and data parallelism.

Picture
Model parallelism splits different parts of the model across multiple devices.

  • Device A handles one portion of the model
  • Device B handles another portion
  • Together they complete forward and backward passes

This method is most useful when the model is too large to fit onto a single GPU, or when you have a large number of compute nodes that you want to utilize simultaneously.


Picture
Data parallelism replicates the entire model on each device.
Each device receives a different piece of the training data, computes gradients, and then sends them to be combined.
  • Works best when you have fewer nodes
  • More common than model parallelism
  • Easy to scale and widely supported in TensorFlow
After devices complete their work, a central entity aggregates the results.


Picture
When performing data parallelism in TensorFlow, training relies on a key component known as the parameter server (PS).

Parameter Server Responsibilities

  • Stores the master copy of model weights and variables
  • Aggregates gradients sent from workers
  • Applies updates and broadcasts updated parameters back
Parameter servers typically run on CPUs.

Worker Nodes (TensorFlow Servers)

  • Typically run on GPUs
  • Perform forward/backward computations
  • Send gradients to the parameter server
Among these workers, one is designated as the chief worker, which is responsible for:

  • Initializing variables
  • Coordinating training steps
  • Saving checkpoints
  • Managing the training session

Together, the parameter servers and workers form a TensorFlow cluster.


Picture


Synchronous vs. Asynchronous Updates

Distributed training can share gradients and update the model in two different ways: synchronously or asynchronously.

Synchronous Distribution

All workers operate in lockstep.


  • Every worker receives its data at the same time
  • Every worker computes gradients
  • Workers wait at a barrier until all results are ready
  • Only then is the model updated

Pros:
  • More stable updates (similar to large-batch SGD)

Cons:
  • Slowest worker (straggler) delays everyone
  • Can significantly reduce throughput

Asynchronous Distribution

Workers operate independently, without waiting.


  • Each worker trains at its own speed
  • Gradients are sent to the parameter server immediately
  • The PS updates the model as soon as gradients arrive

Pros:

  • Fast and efficient
  • No worker-to-worker waiting

Cons:

  • Workers may use older parameter versions
  • Updates are noisier

SGD Behavior in Distributed Training


Stochastic Gradient Descent (SGD) normally works in a loop:


  1. Compute gradients
  2. Update model weights
  3. Repeat

In distributed training:


  • Synchronous SGD = all gradients collected → update once per iteration
  • Asynchronous SGD = each gradient applied immediately, leading to many small updates

This changes training dynamics and may affect convergence stability, depending on the method used.

Preparing Code for Distributed TensorFlow

Building a distributed TensorFlow program involves three main steps:

1. Define the Cluster


Use tf.train.ClusterSpec and tf.train.Server to describe:

  • Parameter servers
  • Worker servers
  • Network addresses
  • Roles of each machine

2. Assign Devices with tf.device()

Explicitly place:


  • Variables on parameter servers
  • Computation operations on worker GPUs

This ensures TensorFlow knows exactly where to run each operation.


3. Use MonitoredTrainingSession

Replace a standard session with:


  • tf.train.MonitoredTrainingSession()

This automatically handles:


  • Initialization
  • Recovery from failures
  • Checkpointing
  • Synchronization between chief and workers

This makes distributed training more robust and easier to manage.


Summary

Why do we “scale out”?


Imagine you have a huge pile of homework and only one pencil—you’ll finish very slowly.
But if ten friends help you, you’ll finish much faster.
Distributed TensorFlow is like that: many computers helping train one big model.

Two Ways to Share the Work

Model Parallelism

Everyone works on different parts of the project.

Data Parallelism

Everyone works on the same project, but with different pages of homework (different data).

What’s the Parameter Server?

It’s like the team leader:


  • Collects everyone’s answers
  • Decides the final version
  • Sends the new version to the whole team
Synchronous vs. Asynchronous


🟦 Synchronous = “Wait for everyone!”

Nobody moves forward until everyone finishes a task.


🟩 Asynchronous = “Go at your own speed!”

You send your work when you’re done, without waiting.





Published on
Artificial Intelligence – Testing and Maintaining Your Applications

Building AI systems—whether they learn continuously from new data (online learning) or are trained once and used afterward (offline learning)—requires more than just creating a model. It also requires ongoing testing and maintenance to make sure everything keeps working the way it should. No matter how the model learns, we must establish reliable monitoring systems and safety checks that alert us whenever the model’s predictions or its essential infrastructure start acting unexpectedly.

Expanded Explanation

In traditional software development, testing is relatively straightforward: for each specific input, we know exactly what the output should be. This makes it easy to write tests that verify whether the system behaves correctly.

Machine learning, however, doesn’t follow that neat pattern. A model may produce different outputs for inputs that look similar, and those outputs depend on many factors—training data, randomness, environment, even hardware differences. This makes classic, rule-based testing harder to apply.

Despite these challenges, testing remains crucial. In machine learning projects, “testing” involves carefully verifying the following:
  • Inputs: Are we providing the model with data in the right format and within expected ranges?
  • Outputs: Are the predictions reasonable, consistent, and within acceptable boundaries?
  • Errors: Are we handling failures, missing data, or unexpected behaviors safely?

In this chapter, we will explore practical methods for testing machine learning code, including strategies tailored for systems that behave unpredictably. We’ll also go through best practices that help ensure reliability even when perfect reproducibility isn’t possible.

Keeping AI Applications Healthy After Deployment

Once an AI model is released into the real world, the job isn’t over. Models may degrade over time as the world changes—a phenomenon known as model drift. To keep the system stable, AI applications must be continuously monitored and maintained.

DevOps tools, such as Jenkins, play an important role here. They can automatically run a set of tests every time a new version of a model or application component is created. Only if all tests pass will the updated version be allowed to move into production. This reduces the risk of shipping broken or unsafe updates.

While we do not expect machine learning engineers to design full development or deployment pipelines on their own, it is important to understand the key principles behind them. These concepts help you collaborate effectively with DevOps teams and ensure that your models are safely and efficiently deployed.



What This All Means?

Imagine you built a robot that gives you advice—maybe it helps with homework or tells you what game to play. To make sure your robot stays helpful and doesn’t start acting weird, you need to check on it regularly.

Testing

Testing is like asking the robot:
  • “Are you listening correctly?”
  • “Are you answering in a way that makes sense?”
  • “Are you freezing or making mistakes?”

In regular computer programs, the answer is the same every time, so it’s easy to test. But with AI robots, they might give different answers because they learn from data. That makes testing trickier!

Maintaining

After your robot is built, you still need to watch it. Maybe it starts learning things that are wrong or confuses new information. So you check it from time to time and fix things if needed.

Tools like Jenkins are like helpers that test the robot every time you teach it something new. If the robot starts making mistakes, the helper won’t let those mistakes go into the real world.

So basically:
  • Testing: making sure your AI works properly.
  • Maintaining: keeping it working even as things change.
Picture
Published on

KembaraXtra–Computer Terms – 386SX

386SX refers to a cost-reduced version of the Intel 80386 microprocessor. While it retains a 32-bit internal architecture and instruction set, it uses a 16-bit external data bus and often a narrower address bus. This made it cheaper to integrate into computer systems, as it could be paired with less expensive support chips and memory subsystems. As a result, 386SX-based systems offered many of the programming advantages of 32-bit processors at a lower overall cost, although with somewhat reduced performance compared to 386DX systems.


Picture
Published on

KembaraXtra–Computer Terms – 386SL

386SL is the name used for a variant of the Intel 80386 processor designed for portable and low-power computing environments, such as early laptop computers. This chip integrates power-management features and other functionality that reduces energy consumption, extending battery life while still maintaining compatibility with 80386 instruction sets. It allowed laptop manufacturers to deliver mobile systems with PC performance levels that were similar to desktop machines of the time.


Picture
Published on

KembaraXtra–Computer Terms – 386DX

The term 386DX refers to the full-featured Intel 80386DX microprocessor, a 32-bit CPU with a 32-bit data bus and 32-bit registers. It supports advanced operating modes, including protected mode, and can address large amounts of memory. Systems built around the 386DX were capable of running sophisticated multitasking operating systems and applications that significantly outperformed earlier 16-bit platforms.


Picture
Published on

KembaraXtra–Computer Terms – 386BSD
386BSD is a version of the BSD UNIX operating system created for systems based on the Intel 80386 processor. It is distinct from BSD386, which was produced by Berkeley Software Design, Inc. Released in 1992 as a freely distributable system, 386BSD played a key role in the history of open-source UNIX-like operating systems. Over time, it gave rise to two significant descendants, NetBSD and FreeBSD, each of which evolved into separate, widely used projects. These later systems continued and expanded the design goals of 386BSD, focusing on portability, robustness, and performance across a wide range of hardware platforms.


Picture