Contents
Train CNN and CRNN from scratch is for people who write Python and want to build reading of handwritten digits in a form cell themselves. A terminal, a virtual environment, and a .py file are enough. Convolution formulas and assembling a line from columns show up in the lesson that cannot take the next step without them. The work runs on a CPU: a GPU speeds up later runs, and the series does not stop without one.
By the end of the series the code does two things and puts them in order. First, do not lose a filled cell: on a scan some fields are empty and some hold a value such as 7,3 or 12/14, and an empty field must not be confused with a written one. Second, read that string without marking by hand where each digit sits. The first model looks at whether there is anything to read. The second reads the symbols. That link is called a cascade.
Networks of this size answer a narrow question about an image that is already cropped. A form cell with a measurement such as 7,3, a diameter 12/14, a thickness 1,5-2, a tick on a questionnaire: the alphabet is short, the grid of cells is known in advance, and the look is at one square.
The benefit of that size is concrete. Training is fast: the input is one cell crop, the stack is shallow, and the course runs are meant for a CPU. The answer for a cell is computed on the same low-power machine that holds the scans, and a stack of forms goes through cell by cell. The guard drops empty fields at once, and the line reader runs only where there is ink. If the form or the handwriting changes and the cells still contain digits, the old network is fine-tuned on the new crops.
The cascade is still several steps away. First comes the map of the course and a way to repeat yesterday's run with the same result. Then a picture becomes a table of numbers, a list of symbols we can read appears, and so do the training examples. After that, a tiny network that tells an empty cell from a filled one, a boundary after which a cell counts as filled, line reading, and joining the two models. Today we take only the start: where we are going, and the bench on which later experiments can be compared.
Yesterday the loss was better. Today, with the same code, it is worse. Often the algorithm is not to blame. What moved is randomness that was not fixed: the weights started elsewhere, the data was shuffled differently, and a comparison of augmentations turned into a lottery. This lesson does not train a model. It answers two questions: what CNN and CRNN mean in this series, and how to set the bench so tomorrow's run can be compared honestly with yesterday's.

Seed — why it matters now
A computer does not roll dice out of thin air. It has a pseudorandom generator: a long sequence that is fully determined. A seed is the starting point in that sequence. The same seed means the same "random" numbers, the same initial network weights, and the same order of examples when the data is shuffled. Another seed means another trajectory. Without a fixed seed, two runs of one script cannot be compared: you are comparing different draws from the generator, not the code or the architecture.
Later in the text, "seed" is that starting point. In code the parameter is almost always named seed.
By the end of the lesson you will have a clear picture of why there are two different networks, a virtual environment, a script that prints versions and the device, and a check that one seed produces bitwise-identical weights.
What CNN and CRNN are
The course task is plain. A scanned form has cells. Some are empty, some hold a handwritten value such as 7,3 or 12/14. You need to not lose the filled ones and read the string without marking by hand where each digit sits on the crop.
One "universal" network is usually not enough for both. We build a cascade of two roles.
A CNN (convolutional neural network) looks at a picture as a grid of pixels. A small-window filter slides across the plane and looks for local features: a stroke, a corner, a blot of ink, an empty field. The same filter weights work everywhere in the frame, so the network does not learn "a seven on the left" separately from "a seven on the right." Several layers stack simple features into more complex ones. In this series the first real CNN is a tiny empty-cell detector: a crop in, "empty / not empty" out (lessons 7–9). That is not text reading. It is a guard: "should we call the reader here at all?"
A CRNN (convolutional recurrent neural network) is for when the answer is a sequence of variable length, not one class. The convolutional part again pulls features from the picture, but the result is cut into columns along the line (time steps). A recurrent block, or a modern stand-in, then looks at those columns in order, left to right, the way an eye moves along digits. Each step yields a distribution over the alphabet plus a blank symbol. How to assemble a string from that without a label "this column is a seven" is CTC (connectionist temporal classification) (lesson 10); the CRNN itself comes a little later. In short: the CNN answers "is there anything to read," the CRNN answers "what was written."
Why not hand everything to one network on day one? An empty cell and a filled cell are different error modes. Treating a value as empty means losing data. Reading an extra empty field is almost free: reading or the format will drop it later. So we first train the guard with a hard limit on not missing values, and only then the line reader. The cascade makes the price of each error explicit.

A rough map of the course (names are a compass, not today's schedule):
| Stage | What appears | Role |
|---|---|---|
| Lessons 1–3 | lab, tensor, alphabet | the bench and the label contract |
| Lessons 4–6 | synthetic data, split, dataset | data without leakage |
| Lessons 7–9 | Tiny CNN, threshold, recipe | the detector (CNN) |
| Lessons 10+ | CTC, then CRNN | the line reader |
| Near the end | the two models joined | the cascade "guard → reader" |
Today we take only the first row of that table: the lab, a working environment, and reproducibility. There will be no networks, data, or thresholds yet. There will be an answer to whether tomorrow's run can be trusted at all.
Later in the course we will compare variants: different augmentations, different thresholds, with and without class balance, Tiny CNN against simple rules. If the seed is different every time, or someone "forgot" it, the "best" configuration may just be a lucky start of the generator. Then you take noise for a benefit of the convolutional network, or you throw away a working trick because one run "did not take off." Fixing the environment and the seed does not teach the model to read digits. It makes the later comparisons honest.
Files in this lesson
They are not on your disk yet. Today you type them. The figure has four pillars. The beam on top is the promise of the lesson: the same run tomorrow gives the same result. Each pillar answers its own question; remove one and the beam does not hold.

device.py— where we compute. An NVIDIA GPU, a Mac accelerator, or the CPU. Without this, "it is slow on my machine" and "I get different numbers" have nothing to attach to.seed.py— how we pin down the chaos. It sets one seed in Python, NumPy, and PyTorch at once, so weights and shuffling do not wander on their own.check_environment.py— the smoke test. It prints versions and the device and does one calculation. If it is silent or crashes, there is nothing to learn next.check_determinism.py— the proof. Two runs with one seed give one weight fingerprint. This is not "it feels stable." It is a check.
The fifth file is not a pillar. It is the floor: requirements.txt with the dependency list (torch, numpy, Pillow, matplotlib, pyyaml, pytest). Without it there is nothing to build the pillars from.
If a file will not start, the reference is the tag lesson-01. Do not clone it.
Predict

"Predict" is not a test and not a grade. Before the command you write down what you expect: which device you will see, whether the weight fingerprints will match, and what happens if the seed is set once and never refreshed. After the run you compare the forecast with the terminal. A match means a belief became a fact. A mismatch is the lesson: you see where your picture of the hardware or of randomness was wrong, instead of scrolling past the output.
Before you run anything, write the answers down (on paper or in notes):
- Which device will
check_environment.pyprint on your computer:cpu,cuda, ormps? - We will train the same tiny model twice with the same seed. Will the weight "fingerprints" match?
- What if we call
set_seedonce and do not reset the seed between the two trainings?
Setup
You write the course code yourself and keep it in your repository. Do not clone someone else's repository of finished files. Open the reference lesson-01 in the browser only after you have typed a file and something does not match. Typos and red imports are part of the lesson.
Create a folder and a repository, then a separate environment:
mkdir cnn-crnn-from-scratch
cd cnn-crnn-from-scratch
git init
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
Type requirements.txt:
torch>=2.2
numpy>=1.26
Pillow>=10.0
matplotlib>=3.8
pyyaml>=6.0
pytest>=8.0
And .gitignore, so the environment and generated data do not land in a commit:
.venv/
__pycache__/
.pytest_cache/
data/
Then install the dependencies:
pip install -r requirements.txt
If you need a PyTorch build, take it from the PyTorch install page. The course is designed so a CPU is enough.
Check that python points at the project (the terminal prompt usually shows (.venv)):
which python
python -c "import torch; print(torch.__version__)"
Example on macOS:
/Users/you/cnn-crnn-from-scratch/.venv/bin/python
2.14.1
On Windows, use where python instead of which python. The path should contain the project's .venv folder. If the path is the system one, the environment is not active and the packages will land somewhere else.
Code: type it yourself
Below is the text of the files to type into your repository. Write it yourself. If a file does not work, compare it with the tag lesson-01 in the browser.
Comments inside the files stay in Russian, the same wording as that tag, so a line-by-line comparison does not drift because of language. The notes under each file say what the lines do.

1. Choosing the device
In PyTorch, tensors and computation live on a device: the CPU or an accelerator. The same formula on different devices has the same meaning, a different speed, and sometimes a different "noise" (on a GPU some operations can be non-deterministic). So in the lab we ask explicitly where we are computing, and we print the answer in the smoke test. Otherwise "it is slow on my machine" and "I get different numbers" have nothing to attach to.
Three options this course knows:
| Name in code | What it is | When it appears |
|---|---|---|
cuda |
an NVIDIA GPU through CUDA (Compute Unified Device Architecture) | An NVIDIA card, a driver, and a PyTorch build with CUDA |
mps |
an Apple accelerator through MPS (Metal Performance Shaders) | A Mac on Apple Silicon and PyTorch with Metal support |
cpu |
an ordinary processor | Always available; the fallback and the main path of the course |
The order in the function is not "better → worse." It is "ask about the usual accelerator first, otherwise take what is certainly there." On the figure: NVIDIA first, then Apple, otherwise the CPU.
File: src/device.py

"""Выбор устройства для вычислений: cuda → mps → cpu."""
import torch
def pick_device() -> torch.device:
if torch.cuda.is_available():
return torch.device("cuda") # NVIDIA + работающий драйвер
mps = getattr(torch.backends, "mps", None) # Apple Silicon, если модуль есть
if mps is not None and mps.is_available():
return torch.device("mps") # ускорение Metal на Mac
return torch.device("cpu") # запасной путь: весь курс рассчитан на CPU
Line by line:
torch.cuda.is_available()is not "is there an NVIDIA chip in the case." It is "can PyTorch compute on it right now." A card without a driver, or a CPU build of the package, returnsFalse.getattr(torch.backends, "mps", None)— older PyTorch builds may have nompsmodule. Withoutgetattrthe code would raiseAttributeErroron a machine without Metal; with it we simply move on.mps.is_available()— a Mac with Apple Silicon and a working Metal backend.cpu— the default path. The whole course is designed so a CPU is enough: the lab, Tiny CNN, and CTC in NumPy do not require buying a GPU. An accelerator helps later on heavy runs, and the absence ofcudaormpsis not a blocker.
When tensors are created on one device and an operation is called on another, PyTorch usually complains. So pick_device() is called once at the start of a script and the result is passed on (or the model is placed on that device). In lesson 1 we only choose and print; moving networks appears together with training.
2. Fix the seed in every library
We already covered the idea of a seed: it is the starting point of a pseudorandom generator. In practice one training script has several such generators. Each lives in its own library and remembers its own state. If you seed only PyTorch and leave NumPy alone, the data can shuffle differently at the same torch.manual_seed(42). The figure has four gears: pin one and the others still carry noise.
If randomness is not fixed, two runs of the same file are two different experiments. The code, the data, and the settings are the same, and the result is not:
- different initial weights → the network takes another trajectory → after the same epochs the loss and the accuracy differ;
- examples land in batches in another order → the training steps differ;
- later, random distortions of the picture and randomly turning off some features change the frame and the features differently every time.
On screen that looks like "yesterday it was 0.99, today it is 0.96" with not a single edit in the code. A comparison of "with augmentation and without," "threshold 0.5 and a chosen one," "class balance and none" becomes a lottery: the winner can be a lucky start of the generator, not a good decision. The check at the end of the lesson shows exactly that. Forget to call set_seed before the second run, and the weight fingerprint is already different.
Why training needs randomness at all:
- Initial network weights. Each filter and each layer has numbers that pixels and features are multiplied by. Before the first training step the network has seen nothing, so the right numbers cannot be taken from the task. Zeros are not used either: every window would be identical, and a stroke and an empty field would not differ at the start. So the numbers are small and random. That set decides the trajectory: the same examples and the same step count, a different seed — different first numbers and a different training path.
- Shuffling examples. Training goes in batches: several crops at a time. The order of batches is often random, so the model does not memorize the order of the file.
- Augmentations (later, lesson 6) are random safe distortions of the picture: a small shift, a little noise. The generator drives those too.
- Randomly turning features off (later, lesson 9) means that during training the network turns off part of the features each time. That is randomness too.
One call to torch.manual_seed(42) is not enough. It touches the PyTorch generator, not the random module from the Python standard library and not numpy.random (NumPy is the library for numeric arrays; data and part of the distortions are often built on it). On a GPU, PyTorch also has a separate generator for each CUDA device. torch.cuda.manual_seed_all fixes that one.
File: src/seed.py

"""Воспроизводимость: фиксируем все источники случайности."""
import os
import random
import numpy as np
import torch
def set_seed(seed: int = 42, deterministic: bool = False) -> None:
"""Фиксирует seed в Python, NumPy и PyTorch (CPU и CUDA).
deterministic=True просит PyTorch использовать только детерминированные
алгоритмы. На GPU это может замедлить обучение или бросить ошибку для
операций без детерминированной версии.
"""
random.seed(seed) # стандартная библиотека (аугментации позже)
np.random.seed(seed) # генерация данных и часть аугментаций
torch.manual_seed(seed) # веса, dropout, перемешивание на CPU
torch.cuda.manual_seed_all(seed) # без CUDA вызов безвреден
if deterministic:
# переменная должна быть задана до первой операции на CUDA
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
torch.use_deterministic_algorithms(True) # только детерминированные алгоритмы
def make_generator(seed: int) -> torch.Generator:
"""Отдельный генератор для DataLoader(shuffle=True, generator=...)."""
g = torch.Generator()
g.manual_seed(seed) # свой генератор под перемешивание батчей
return g
def seed_worker(worker_id: int) -> None:
"""worker_init_fn для DataLoader: у каждого воркера свой, но воспроизводимый seed."""
worker_seed = torch.initial_seed() % 2**32 # уникальный, но воспроизводимый seed воркера
np.random.seed(worker_seed)
random.seed(worker_seed)
Four sources that set_seed touches (as on the figure):
| Source | What it covers in the course |
|---|---|
random |
the Python standard library; later, part of the augmentations |
numpy.random |
generating and preparing numbers and data |
torch on CPU |
initial weights, dropout, shuffling on the processor |
torch on CUDA |
a separate generator on each NVIDIA GPU |
If you fix only one column of the table, the others keep adding noise.
Do not call the two functions below set_seed yet. They are needed in lesson 6, when a batch loader (DataLoader) appears: it cuts the dataset into batches and can read files in several background processes (workers). Each worker is its own process with its own generator state. make_generator returns a separate PyTorch generator object for shuffling batches; seed_worker sets the seed inside a worker so it differs across processes and still repeats from run to run. Today it is enough to type them next to set_seed so the file matches the tag.
The flag deterministic=True is about something else, not the seed. Even with one seed, PyTorch on a GPU sometimes picks a fast but non-deterministic algorithm (the same input → slightly different bits on the output). "Deterministic" here means: ask the library to take only variants whose result repeats bitwise. That can be slower, or it can fail if an operation has no such variant. The environment variable CUBLAS_WORKSPACE_CONFIG is needed by part of the CUDA math so determinism can turn on at all; set it before the first operation on the GPU. In this course the flag is off by default, and we run the reproducibility check on the CPU. That way we check our seed-fixing code, not the driver of a particular card.
3. Environment check
File: src/check_environment.py
"""Проверка окружения: версии, устройство, один тензорный расчёт."""
import platform
from importlib.metadata import version
import numpy as np
import torch
from device import pick_device
def main() -> None:
device = pick_device() # cuda → mps → cpu
print(f"Python : {platform.python_version()}")
print(f"Platform : {platform.platform()}")
print(f"torch : {torch.__version__}")
print(f"numpy : {np.__version__}")
print(f"Pillow : {version('Pillow')}")
print(f"Device : {device}")
print(f"CPU threads : {torch.get_num_threads()}")
x = torch.randn(2, 3, device=device) # маленький тензор на выбранном устройстве
y = x @ x.T # матричное умножение: дымовой тест «устройство считает»
assert y.shape == (2, 2), "неожиданная форма результата"
print(f"Tensor OK : shape={tuple(x.shape)}, device={x.device}")
if __name__ == "__main__":
main()
The script does one thing: it prints what you are working with, and it runs a small matrix multiply on the chosen device. If this step fails, there is no point in going further.
Run:
python src/check_environment.py
Sample output in this lesson (your Platform, Device, and thread count will differ):
Python : 3.14.0
Platform : macOS-26.5.2-arm64-arm-64bit-Mach-O
torch : 2.14.1
numpy : 2.5.3
Pillow : 12.3.0
Device : mps
CPU threads : 4
Tensor OK : shape=(2, 3), device=mps:0
The lines that matter: Device (compare it with the forecast from "Predict") and Tensor OK — the multiply on the chosen device succeeded. On a machine without NVIDIA and without Apple Silicon you will see Device: cpu and device=cpu. That is enough for the course.
4. Reproducibility check
File: experiments/check_determinism.py
"""Проверка воспроизводимости: один seed → одни и те же веса.
Считаем на CPU, чтобы не смешивать нашу проверку с недетерминизмом GPU.
"""
import argparse
import hashlib
import sys
from pathlib import Path
import torch
import torch.nn.functional as F
from torch import nn
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from seed import set_seed # noqa: E402
def weights_hash(model: nn.Module) -> str:
"""Короткий «отпечаток» всех весов модели."""
h = hashlib.sha256()
for p in model.parameters():
h.update(p.detach().cpu().numpy().tobytes()) # байты весов → в хэш
return h.hexdigest()[:12] # короткий отпечаток для печати
def train_tiny(steps: int, seed: int | None) -> tuple[str, float]:
"""Мини-обучение. seed=None: set_seed сознательно НЕ вызываем («забыл seed»)."""
if seed is not None:
set_seed(seed) # фиксируем все источники случайности
model = nn.Sequential(nn.Linear(16, 32), nn.ReLU(), nn.Linear(32, 2)) # крошечная сеть
opt = torch.optim.SGD(model.parameters(), lr=0.1)
x = torch.randn(256, 16) # синтетические признаки
y = (x[:, 0] > 0).long() # метка из знака первого признака
loss = torch.tensor(0.0)
for _ in range(steps):
opt.zero_grad()
loss = F.cross_entropy(model(x), y) # ошибка классификации
loss.backward()
opt.step()
return weights_hash(model), float(loss.detach())
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--steps", type=int, default=50)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--threads", type=int, default=None,
help="число потоков CPU (1 помогает, если хэши не совпали)")
args = ap.parse_args()
if args.threads:
torch.set_num_threads(args.threads) # на части CPU влияет на хэш
h1, l1 = train_tiny(args.steps, args.seed) # первый запуск с seed
h2, l2 = train_tiny(args.steps, args.seed) # тот же seed → отпечатки должны совпасть
h3, _ = train_tiny(args.steps, args.seed + 1) # другой seed → отпечаток другой
set_seed(args.seed) # один раз в начале...
h4, _ = train_tiny(args.steps, None) # ...и дальше «забываем» переустанавливать
h5, _ = train_tiny(args.steps, None) # генератор уже сдвинут → другой результат
same_ok = h1 == h2 and l1 == l2 # одинаковый seed → одинаковые веса и loss
diff_ok = h1 != h3 # разный seed → проверка не «мёртвая»
print(f"same seed ({args.seed}, {args.seed}) : {h1} {'==' if h1 == h2 else '!='} {h2} "
f"{'OK' if same_ok else 'FAIL'}")
print(f"different seed ({args.seed}, {args.seed + 1}) : {h1} {'!=' if diff_ok else '=='} {h3} "
f"{'OK' if diff_ok else 'FAIL'}")
print(f"forgot to reseed : {h4} {'!=' if h4 != h5 else '=='} {h5} (демо, не проверка)")
if same_ok and diff_ok:
print("determinism: OK (hash match)")
return 0
print("determinism: FAIL (см. раздел «Если не так» в уроке)")
return 1
if __name__ == "__main__":
sys.exit(main())
The idea is simple. We train a tiny network on random data and compute a "fingerprint" (a hash) of all its weights. Three experiments:
- One seed, two runs. The fingerprints must match. If they do not, reproducibility is broken and any later comparison is meaningless.
- Different seeds. The fingerprints must differ. Otherwise the check checks nothing (for example, the seed does not affect the result at all).
- "Forgot to reset the seed." We call
set_seedonce and run training twice in a row without resetting it. The second run starts from a generator that has already moved on, and it produces a different result. This is the most common reason "yesterday was better": the code is the same, the randomness is not.
We compute on the CPU on purpose: we are checking our code, not the non-determinism of a particular GPU.
Run:
python experiments/check_determinism.py
Sample output in this lesson:
same seed (42, 42) : 1415d3102ea2 == 1415d3102ea2 OK
different seed (42, 43) : 1415d3102ea2 != 8a6ef2f5d087 OK
forgot to reseed : 1415d3102ea2 != 8ab8dc6618c1 (демо, не проверка)
determinism: OK (hash match)
Read it line by line. The first: one seed twice — the fingerprints matched (OK). The second: another seed — a different fingerprint (OK). The third: the seed was set once and we "forgot" to reset it — the fingerprints diverged; that is a demonstration, not a failure criterion. The result is determinism: OK (hash match) and exit code 0. The twelve-character hashes on your machine may differ (library versions, CPU thread count); what matters are the signs == / != and the final OK. The third line of the program prints a short Russian note, (демо, не проверка): "demo, not a check."
Commands
When the files are typed, run the lesson end to end — two commands in a row. That checks both the environment and the seed: first "the bench is alive," then "the experiments are honest."
python src/check_environment.py
python experiments/check_determinism.py
In the terminal you first see the version block and the line Tensor OK, then three lines about the seed and the ending determinism: OK (hash match) — as in the samples above. If both commands finish that way, the lab for this lesson is assembled.
Smoke
Smoke is a short smoke run: you turn the commands on and immediately look at whether they print OK. This is not training the detector. check_determinism.py takes a few steps only to get a weight fingerprint and compare two runs. The default is 50 steps: on a weak machine that is already a noticeable wait, and a long run adds nothing to the seed check.
If the full run feels long, cut the training to five steps. The environment print is the same. The seed-check hashes will differ because there are fewer steps, and the shape of the output is the same. Look at OK: the exact hash digits change with the step count.
python src/check_environment.py
python experiments/check_determinism.py --steps 5
same seed (42, 42) : 6d2b0b1f27c7 == 6d2b0b1f27c7 OK
different seed (42, 43) : 6d2b0b1f27c7 != 90500ac35763 OK
forgot to reseed : 6d2b0b1f27c7 != c9bb06091d82 (демо, не проверка)
determinism: OK (hash match)
What to expect
Open the notes from "Predict" and compare them with the terminal. That is the point of this section, not "guess the right answer."
- The
Deviceline is the device you expected, or a clear reason for another one (for examplecpuif you have a CPU build of PyTorch). - One seed twice → the fingerprints matched (
same seed … OK). - "Forgot to reset" → the fingerprints diverged (the third line).
If the device or the seed lines do not match what you expected, look at "If it fails" below. Most often it is the environment or the CPU thread count, not "the idea of the lesson broke."
Exercise
Three short trials, so you can feel by hand where the randomness lives.
- Another seed:
python experiments/check_determinism.py --seed 7. Do the fingerprints change? Doesdeterminism: OKstay? - Comment out the line
set_seed(seed)insidetrain_tinyand run again. Which output lines changed, and why? - Run the two commands below: first with one thread, then with four. Do the fingerprints match between these two runs? Write down what you saw: the CPU thread count sometimes gets into the hash even with one seed.
python experiments/check_determinism.py --threads 1
python experiments/check_determinism.py --threads 4
If it fails
ModuleNotFoundError: No module named 'torch'. The virtual environment is probably not active, or the dependencies were not installed. The terminal prompt should start with(.venv); then runpip install -r requirements.txtagain.Device: cpueven though there is a GPU. Often this is a CPU build of PyTorch, or a missing driver. Checkpython -c "import torch; print(torch.cuda.is_available())". For the course this is fine: every lesson is designed for the CPU.- The
same seedline printsFAIL. On some processors the result depends on the thread count. Run with--threads 1:python experiments/check_determinism.py --threads 1. If it still does not match, open an issue in the course repository with the output ofcheck_environment.py, and we will look at it. - Windows:
source .venv/bin/activatedoes not work. Use.venv\Scripts\activate(PowerShell or cmd) or WSL.
Readiness checklist
Before the next lesson, make sure the lab answers in your repository and the lesson files are committed.
- Your repository exists,
.venvis active, and the lesson files are committed -
python src/check_environment.pyprintsTensor OK -
python experiments/check_determinism.pyprintsdeterminism: OK (hash match) - The three forecasts from "Predict" have been compared with the terminal
Typing trainer. The
device.pyandseed.pyfragments above are marked for the trainer. Why type by hand in the age of AI — on the landing page and in the guide to typing code.
FAQ
How is a CNN different from an ordinary fully connected network on pixels?
A fully connected network ties every pixel to every weight again. A convolutional network uses the same small window across the whole picture: fewer parameters, and the idea of a "local feature" stays. For crops of handwriting that is more natural than stretching every pixel into one long vector.
Why separate the detector (CNN) from the reader (CRNN)?
They have a different price of error and a different kind of answer: one class versus a string. The guard drops empty cells under a hard limit of "do not lose values"; the reader takes the symbols apart. If you pile everything into one model on day one, it is harder to see what actually broke — the threshold, the alphabet, or the network itself.
Why a separate .venv if PyTorch is already installed on the system?
The course packages should not mix with other projects. Otherwise the next tool will pull in someone else's torch, and this repository will pull in someone else's NumPy versions. A separate environment makes pip install -r requirements.txt predictable.
Why does the reproducibility check run on the CPU if I have a GPU?
On a GPU some operations can be non-deterministic even with a fixed seed. We compute on the processor on purpose, to check our code for fixing randomness, not the driver of a particular card. For the course itself a CPU is enough.
Is one line, torch.manual_seed(42), enough?
No. Randomness also lives in the random module, in numpy.random, and in the CUDA generator. Miss one source and noise remains in the comparison of experiments. That is why set_seed touches all four places.
Why does "forgot to reset the seed" give different fingerprints?
set_seed is set once, and after the first training the generator has already moved on. The second run takes the next random numbers — the weights differ, even though the code is the same. This is the typical reason for the phrase "yesterday was better."
My hashes differ from the ones in the article. Is that an error?
Not necessarily. Library versions, the platform, and the CPU thread count affect the exact bytes of the weights. What matters is that two runs with one seed match (OK) and runs with different seeds diverge. The number in the article is a snapshot from one machine.
Do I need an NVIDIA GPU for this series?
No. Device selection knows cuda and mps, and every lesson is designed for the CPU. A card will speed up heavier steps later, but the lab and the first models should pass on a CPU.
What comes next
There are no pictures, datasets, or models yet. Next is lesson 2, “Image → tensor”: one input shape, [1, 48, 160], for every model in the course. The link will appear when that lesson leaves draft.
Reference for comparison: lesson-01. Do not clone it.



Comments