Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Set-up · 25 minutes

Set up your lab for Securing AI infrastructure

After this lesson you can
  • Create the lab folder and a virtual environment with pinned libraries
  • Train the first model and save it as a plain JSON file
  • Prove with a check script that the lab is ready
Lab files of this lesson (4)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. Type the code yourself first: you learn more.

What you need

  • The courses "Python for security work" (lessons 1 to 9: functions, files, command-line tools, logging, HTTP, tests and subprocess), "Linux" Part 1 (the terminal, files, permissions) and "Networking hands-on" (ports, HTTP). Part 2 of the Linux course (users, permissions, services) is recommended: lesson 5 uses it.
  • A Linux computer. The course runs on Linux, and some commands (ulimit, /proc) are Linux only. You need no administrator rights, no GPU, no Docker and no cloud account.
  • Python 3.12 or newer. The pinned libraries need it. The programs of the lessons use the standard library and run on Python 3.10 or later, but you install the libraries once, in one environment.
  • About 500 MB of free disk space for the install. After that every lesson runs offline.
  • Ports 8420 to 8439 on 127.0.0.1 (your own computer) free. The lessons start small servers there. Nothing listens on another address, and nothing leaves your computer.

Where a real platform has an equivalent (a container, a managed gateway, a secrets manager, a CI service), the lesson names it in one or two sentences. The course cannot test those, so it says so.

Set it up

1. Make the lab folder

mkdir -p (make directory, with its parents) creates the folder. cd (change directory) moves you into it.

mkdir -p ~/krlab/ai-infrastructure
cd ~/krlab/ai-infrastructure
pwd
/home/you/krlab/ai-infrastructure

2. Make a virtual environment

A virtual environment is a private folder of Python packages. python3 -m venv .venv creates it. source .venv/bin/activate switches it on, and your prompt starts with (.venv). Run the source line at the start of every lesson.

python3 -m venv .venv
source .venv/bin/activate
python --version
Python 3.14.4

3. Pin the versions and install

A pinned version is an exact one, written with ==. The course "How AI works" explains why: the same versions give the same numbers. Save this file. pip install -r installs every package that a file lists.

requirements.txt

scikit-learn==1.9.1
numpy==2.5.5
scipy==1.18.1
joblib==1.6.0
pip install -r requirements.txt
Successfully installed cloudpickle-3.1.3 joblib-1.6.0 narwhals-2.29.0 numpy-2.5.5 scikit-learn-1.9.1 scipy-1.18.1 threadpoolctl-3.8.0

4. Save the data and the training program

The course gives you two files. data.py makes fixed fake login events: how many failed logins an account had, whether the device is new, and how far (in km) the login is from the usual place. random.Random(seed) gives the same numbers for the same seed on every machine. The label suspicious comes from a rule with a little noise.

data.py

"""data.py: fixed fake login events. The same seed gives the same events on every machine."""
import random

FEATURES = ["failed", "new_device", "km"]


def make_events(seed, n, shift=0):
    """Return n events as dicts. `shift` adds to the failed logins, to imitate a change in the world."""
    rng = random.Random(seed)
    events = []
    for _ in range(n):
        failed = int(rng.random() ** 2 * 12)
        new_device = 1 if rng.random() < 0.2 else 0
        km = int(rng.random() ** 2 * 400)
        risk = 0.5 * failed + 1.5 * new_device + km / 150 + (rng.random() - 0.5) * 1.5
        events.append({"failed": failed + shift, "new_device": new_device, "km": km, "suspicious": 1 if risk > 4 else 0})
    return events

train.py trains a model with scikit-learn and saves it as plain numbers in model.json, with a manifest.json that holds the SHA-256 hash (a fingerprint of the file's bytes) of the model. Lesson 2 explains why the model is a JSON file and not a pickle.

train.py

"""train.py: train a small model and save it as plain JSON numbers, not as a pickle.

    python3 train.py v1 [seed] [broken]      writes models/v1/model.json and models/v1/manifest.json
"""
import hashlib
import json
import sys
from pathlib import Path

from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

from data import FEATURES, make_events


def train(version, seed=1, broken=None, root="."):
    events = make_events(seed, 1000)
    labels = [e["suspicious"] for e in events]
    X = [[0 if f == broken else e[f] for f in FEATURES] for e in events]   # `broken` imitates a feature column that was lost
    scaler = StandardScaler().fit(X)
    model = LogisticRegression().fit(scaler.transform(X), labels)
    model_json = {"features": FEATURES, "mean": [round(v, 6) for v in scaler.mean_],
                  "scale": [round(v, 6) for v in scaler.scale_],
                  "weights": [round(v, 6) for v in model.coef_[0]], "bias": round(float(model.intercept_[0]), 6)}
    folder = Path(root, "models", version)
    folder.mkdir(parents=True, exist_ok=True)
    text = "{\n" + ",\n".join(f' "{k}": {json.dumps(v)}' for k, v in model_json.items()) + "\n}\n"
    (folder / "model.json").write_text(text)
    manifest = {"version": version, "sha256": hashlib.sha256(text.encode()).hexdigest()}
    (folder / "manifest.json").write_text(json.dumps(manifest) + "\n")
    for name in ("model.json", "manifest.json"):
        (folder / name).chmod(0o644)   # the same on every machine, whatever the umask
    return manifest


if __name__ == "__main__":
    version = sys.argv[1]
    seed = int(sys.argv[2]) if len(sys.argv) > 2 else 1
    print(train(version, seed, sys.argv[3] if len(sys.argv) > 3 else None))

5. Train version 1

python train.py v1
cat models/v1/model.json
{'version': 'v1', 'sha256': '85eec023d661f4f82a784b933885c6a17069ac8bad159c4223c72a1c708b9219'}
{
 "features": ["failed", "new_device", "km"],
 "mean": [3.546, 0.196, 138.071],
 "scale": [3.530423, 0.396969, 122.398644],
 "weights": [5.317512, 1.558588, 2.343423],
 "bias": -3.256751
}

Check your lab

labcheck.py checks the Python version, the environment, the three libraries, the data, the model file, and that ports 8420 to 8439 are free. socket is the standard library module for network connections. connect_ex tries to connect and returns 0 when something answers, so a free port gives a non-zero number.

labcheck.py

"""labcheck.py: prove that the lab of "Securing AI infrastructure" works."""
import hashlib
import json
import socket
import sys
from pathlib import Path

PINNED = {"sklearn": "1.9", "numpy": "2.5", "scipy": "1.18"}
results = []


def check(name, ok, detail):
    results.append(ok)
    print(("ok   " if ok else "FAIL ") + name.ljust(9) + detail)


v = sys.version_info
check("python", v >= (3, 12), f"{v.major}.{v.minor}.{v.micro}")
check("venv", sys.prefix != sys.base_prefix, sys.prefix)
for module, want in PINNED.items():
    try:
        lib = __import__(module)
        check(module, ".".join(lib.__version__.split(".")[:2]) == want, f"{lib.__version__} (the lessons use {want}.x)")
    except ImportError:
        check(module, False, "not installed")

try:
    from data import make_events
    count = sum(e["suspicious"] for e in make_events(1, 1000))
    check("data", count == 289, f"{count} suspicious events of 1000 (must be 289)")
except ImportError:
    check("data", False, "data.py is missing")

try:
    folder = Path("models/v1")
    sha = json.loads((folder / "manifest.json").read_text())["sha256"]
    check("model", hashlib.sha256((folder / "model.json").read_bytes()).hexdigest() == sha, "models/v1 matches its manifest")
except OSError:
    check("model", False, "models/v1 is missing: run python train.py v1")

busy = []
for port in range(8420, 8440):
    with socket.socket() as s:
        if s.connect_ex(("127.0.0.1", port)) == 0:
            busy.append(port)
check("ports", not busy, "8420 to 8439 are free" if not busy else f"in use: {busy}")

print(f"lab ready: {sum(results)} of {len(results)}")
sys.exit(0 if all(results) else 1)
python labcheck.py
ok   python   3.14.4
ok   venv     /home/you/krlab/ai-infrastructure/.venv
ok   sklearn  1.9.1 (the lessons use 1.9.x)
ok   numpy    2.5.5 (the lessons use 2.5.x)
ok   scipy    1.18.1 (the lessons use 1.18.x)
ok   data     289 suspicious events of 1000 (must be 289)
ok   model    models/v1 matches its manifest
ok   ports    8420 to 8439 are free
lab ready: 8 of 8

Your Python version and your folder can differ. The last line must be the same. Type the last line of your own output.

The course page offers a zip of the lab files and a script, kr-lab.sh. If you start at a later lesson with sh kr-lab.sh LESSON FOLDER, the folder holds only the files that the lessons print. It does not hold what the lessons make with a command: the model, the keys, the gateway token, the samples and the registry. Switch on the environment, then run the lines for the lessons before the one you start at (the comment names the lesson that makes the file):

python train.py v1                                      # lesson 0: models/v1
mkdir -p models/current && cp models/v1/* models/current/   # lesson 2: the folder that the service reads
python keystore.py add alpha predict                    # lesson 3: keys.json and secrets/alpha.key
python keystore.py add beta read                        # lesson 3: secrets/beta.key
( umask 077; python -c "import secrets; print(secrets.token_hex(16))" > secrets/gateway.token )   # lesson 3: the token that the gateway and the service share
python release.py v1                                    # lesson 6: models/registry.json
python make_samples.py                                  # lesson 7: the folder samples/

The lessons that are named explain each command.

If it fails

Read the first line that starts with FAIL. Fix that one, then run python labcheck.py again.

The script saysWhat it meansWhat to do
FAIL pythonPython is older than 3.12.Install a newer Python, then repeat steps 2 and 3 with it.
FAIL venvThe environment is not switched on.Run source .venv/bin/activate. The prompt must start with (.venv).
FAIL sklearn not installedThe install ran outside the environment.Switch it on, then run pip install -r requirements.txt again.
FAIL datadata.py differs from the lesson.Save the file again, exactly as printed.
FAIL modelThere is no models/v1, or the file changed after training.Run python train.py v1 again.
FAIL portsA program on your computer uses a port in 8420 to 8439.Find it with ss -ltnp, stop it, or finish your other lab first.

If pip cannot find the pinned versions on your system, the course "How AI works" describes what to do: the numbers can then differ in the last digit, and the page checks only counts and rounded values.