# 0. Crash course for Android developers

You can start with the engineering skills you already use: trace data, check contracts, isolate a change, measure a result, and preserve a rollback. The new skill is understanding a program whose useful behavior depends on learned numerical parameters. This course connects that idea to a complete, deliberately small experiment before you modify a production checkpoint.

The course uses **TinyNet**, an original classifier with 16 numerical inputs and three output classes. It is not an image recognizer, speech model, or diffusion model. Its purpose is to make shapes, gradients, pruning, and recovery observable without downloading a dataset or a pretrained checkpoint. The package contains the implementation, generated example checkpoints, tests, and recorded results. [E04]

**Run status:** The Python learning lab and 15 structural tests were executed on CPU with Python 3.13.5 and PyTorch 2.10.0+cpu. The optional ONNX exporter and Kotlin integration example were not executed. No Android, GPU, NPU, HDemucs, or diffusion performance result is implied. [E04]

## Course map

| Lesson | Engineering deliverable |
|---|---|
| [0.1 Set up a small, reproducible workspace](#01-set-up-a-small-reproducible-workspace) | An isolated environment and a successful test run |
| [0.2 Read Python as an Android engineer](#02-read-python-as-an-android-engineer) | A readable model class and a verified checkpoint |
| [0.3 Think in tensors and contracts](#03-think-in-tensors-and-contracts) | Correct shapes, axis meanings, and payload calculations |
| [0.4 Read a network one operation at a time](#04-read-a-network-one-operation-at-a-time) | A shape trace and parameter count |
| [0.5 Understand one training step](#05-understand-one-training-step) | A working forward, loss, backward, and update cycle |
| [0.6 Separate learning from evaluation](#06-separate-learning-from-evaluation) | A split policy that prevents avoidable leakage |
| [0.7 Profile before changing the model](#07-profile-before-changing-the-model) | A baseline record with narrowly defined measurements |
| [0.8 Make your first structural edit](#08-make-your-first-structural-edit) | A smaller model plus tests of the edit itself |
| [0.9 Recover the model and test distillation](#09-recover-the-model-and-test-distillation) | A controlled comparison of two recovery methods |
| [0.10 Cross the export and quantization boundary](#010-cross-the-export-and-quantization-boundary) | An explicit conversion contract and parity checklist |
| [0.11 Integrate and measure on Android](#011-integrate-and-measure-on-android) | A deployment plan with a golden input and output |
| [0.12 Choose the next model and graduate](#012-choose-the-next-model-and-graduate) | A model-specific experiment proposal |

These are skill gates, not a six-month prerequisite. Move forward when you can explain the result and reproduce the exercise. A course can introduce a method; it cannot establish that a particular production model will tolerate that method.

## 0.1 Set up a small, reproducible workspace

**Goal:** Run a model experiment without first solving a GPU, dataset-download, or Android build problem.

Extract the ZIP and open a terminal in `Model_Refactoring_Complete`. The core course uses the Python standard library and PyTorch. It does not require Android Studio, CUDA, ONNX, or a paid service. That statement applies to the supplied CPU lab, not to training arbitrary models. [E04]

Create a virtual environment so this experiment has its own installed packages. The environment is similar in purpose to separating toolchain dependencies between projects, although it does not make results independent of the operating system or processor. Python documents `venv` and `pip` as the relevant environment and package tools. [R67]

```bash
python -m venv .venv
```

On Windows PowerShell, invoke the environment's interpreter directly. This avoids requiring an activation-script policy change:

```powershell
.\.venv\Scripts\python.exe -m pip install -r crash_course/requirements-cpu.txt --index-url https://download.pytorch.org/whl/cpu
.\.venv\Scripts\python.exe -m unittest crash_course.test_contracts -v
.\.venv\Scripts\python.exe -m crash_course.run --out runs/first
```

On macOS or Linux:

```bash
.venv/bin/python -m pip install -r crash_course/requirements-cpu.txt --index-url https://download.pytorch.org/whl/cpu
.venv/bin/python -m unittest crash_course.test_contracts -v
.venv/bin/python -m crash_course.run --out runs/first
```

The requirement pins the tested base version, `torch==2.10.0`. A suitable wheel must exist for your operating system, processor, and Python version. Installing packages requires network access or a local wheel cache. Running the lab after installation does not download data. Keep the tested environment and a new environment distinct in your reports.

The command refuses a nonempty output directory. Use `runs/second` for another experiment instead of replacing the evidence from `runs/first`. The included reference run is in `evidence/crash_course`; do not use that path for a rerun.

**Exercise:** Run the tests, then the learning lab. Open `report.json` and locate the Python version, PyTorch version, seed, selected candidate, source hashes, and final test results.

**Exit check:** You can explain which files are code, which are model parameters, and which are evidence. You have not mistaken a package installation failure for a model failure.

## 0.2 Read Python as an Android engineer

**Goal:** Read a model implementation without treating every unfamiliar Python expression as a new ML concept.

A Python class can own other objects, expose methods, and validate its inputs. `self` refers to the instance. `__init__` initializes it. A type hint such as `width: int` documents the expected type but does not itself enforce all runtime constraints. Assignment can give two names to the same mutable object. These are language concerns, not learning algorithms. [R68]

In this course, a PyTorch model is an `nn.Module`. Submodules assigned to module attributes participate in PyTorch's parameter traversal. A `ModuleList` registers its contained modules; a plain Python list is not a substitute when those modules need to appear in the model state and optimizer parameter collection. Calling `model(x)` invokes the module call machinery around `forward`, including registered hooks. [R62]

Read this actual component from `crash_course/models.py`:

```python
class ResidualFFN(nn.Module):
    def __init__(self, width: int, inner: int) -> None:
        super().__init__()
        self.up = nn.Linear(width, inner)
        self.act = nn.GELU()
        self.down = nn.Linear(inner, width)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x + self.down(self.act(self.up(x)))
```

Start with the control flow. The input goes through `up`, `act`, and `down`; the result is added to the original input. The class construction determines the layer dimensions. Loading a checkpoint supplies values for those layers. Neither operation, by itself, teaches the network a task.

A useful Android analogy is a component implementation plus its persisted state. The analogy stops at interchangeability: changing a neural layer's dimensions usually invalidates some saved parameter shapes. Renaming a configuration value does not resize the checkpoint.

```python
from pathlib import Path
from crash_course.models import load_model

model = load_model(Path("evidence/crash_course/selected.pt"))
print(model)
print(model.config)
```

The loader reconstructs the exact TinyNet configuration and uses strict state-dictionary loading. Save architecture metadata with the weights, not just a filename such as `small.pt`. PyTorch's save/load tutorial distinguishes the state dictionary from the model class needed to interpret it. Load only trusted artifacts. [R69]

**Exercise:** Find `stem`, `blocks`, and `head` in the printed model. Confirm that the selected model has two residual blocks while the original teacher has three.

**Exit check:** You can identify where the architecture is defined and where the learned numbers enter that architecture. You use `deepcopy` for a pruning candidate rather than `candidate = baseline`, which would alias the original object. [R68]

## 0.3 Think in tensors and contracts

**Goal:** Know what every axis means before changing its length.

A tensor is a numerical array. In PyTorch it also has properties such as a dtype and a device. Shapes alone do not tell you whether an axis means color channels, time samples, tokens, or classes. Document those meanings as part of the input contract. A float tensor holding RGB values in the wrong order can be structurally valid and semantically wrong. [R59]

Common conventions you will encounter are shown below. These are conventions to verify, not universal layouts that every model accepts.

| Example contract | Meaning |
|---|---|
| `[B, C, H, W]` | Batch, channels, image height, image width |
| `[B, C, T]` | Batch, audio channels, time samples |
| `[B, T, D]` | Batch, sequence positions, feature width |
| `[B, C, F, H, W]` | One possible video layout with frame axis `F` |
| `[B, 16] -> [B, 3]` | TinyNet's features and class scores |

The first four rows describe possible application contracts. A video checkpoint may use another order or operate on latent representations rather than pixels. Its implementation is the authority.

The following is a payload calculation, not a peak-RAM measurement:

```python
import torch

image = torch.zeros(1, 3, 32, 32, dtype=torch.float32)
logical_bytes = image.numel() * image.element_size()
assert logical_bytes == 12_288
```

There are 3,072 values, each represented by four bytes. The logical payload is therefore 12,288 bytes. Runtime allocations, object metadata, retained intermediates, and workspace are not included. Views can also share underlying storage, so summing every visible tensor's payload can double-count memory. [R50, E04]

**Changing shape is not the same as changing axis order.** `permute` rearranges axes. `reshape` requests a new shape while preserving the relevant element ordering; it is not an RGB-to-planar conversion just because the final dimensions match. A reshape may return a view or require a copy, depending on the existing layout. [R50]

```python
x = torch.arange(24).reshape(1, 2, 3, 4)
correct = x.permute(0, 2, 3, 1)
wrong = x.reshape(1, 3, 4, 2)
assert correct.shape == wrong.shape
assert not torch.equal(correct, wrong)
```

That assertion is part of the executed tests. It models a deployment bug worth learning early: both sides agree on dimensions while disagreeing on the meaning of the values. [E04]

**Exercise:** Calculate the FP32 payload of `[1, 32, 64, 64]`, then halve both spatial dimensions. The answers are 524,288 bytes and 131,072 bytes. Halving height and width quarters the number of values in this tensor. It does not prove that the whole model's peak memory falls by the same factor.

**Exit check:** For an input and an intermediate tensor, you can state the shape, axis meanings, dtype, device, and logical payload without calling that payload total process memory.

## 0.4 Read a network one operation at a time

**Goal:** Translate a model listing into a sequence of numerical interfaces.

For a batched input, `nn.Linear(16, 32)` produces 32 features from 16 input features. Its weight has shape `[32, 16]`, and its bias has shape `[32]`. PyTorch computes the corresponding affine mapping as `x @ weight.T + bias`. The layer therefore has `16 * 32 + 32 = 544` parameters. [R63]

TinyNet applies this sequence:

```text
features [B, 16]
  -> stem Linear(16, 32)
  -> [B, 32]
  -> residual block, repeated three times
       Linear(32, 64) -> GELU -> Linear(64, 32)
       add the block input
  -> head Linear(32, 3)
  -> logits [B, 3]
```

Each residual branch expands and contracts the feature width without changing its external shape. One branch has `32*64 + 64 + 64*32 + 32 = 4,192` parameters. Three branches plus the stem and the 99-parameter head total 13,219 parameters. These counts are verified by the supplied tests. [E04]

GELU is a nonlinear activation function, not a trainable projection. Its standard definition is `x * Phi(x)`, where `Phi` is the standard normal cumulative distribution function. PyTorch also provides a configurable approximation. In this block, GELU changes values but not the tensor shape and adds no learned parameters. Replacing it with another function changes the computation even when all dimensions still match. [R64]

Convolution adds another kind of contract. A `Conv2d(3, 8, kernel_size=3, padding=1)` with its default stride and dilation maps `[B, 3, H, W]` to `[B, 8, H, W]`. Its filters mix local spatial neighborhoods and input channels. The tested example has 224 parameters. Convolution output dimensions depend on kernel, stride, padding, dilation, and grouping. [R47, E04]

A normalization layer is not just a harmless rescale. LayerNorm computes statistics over its configured final dimensions. Shrinking those dimensions or replacing whole-image statistics with tile-local statistics can change the result. Learn which axes participate before applying a memory optimization. [R70]

Attention is a separate operation for mixing information across positions. In the usual scaled dot-product form, queries and keys determine weights used to combine values. Changing the number of heads, the projection widths, or the positions each token can attend to are different transformations. Do not begin by deleting heads from an unfamiliar implementation. Chapter 7 develops the dependency checks. [R27]

**Exercise:** Use `parameter_count(model)` and `trace_shapes(model, torch.zeros(1, 16))`. Match every reported shape to the sequence above. The trace records metadata only; it does not store tensors for later inspection. [E04]

**Exit check:** You can explain the difference between a learned linear layer, a nonlinear activation function, a residual addition, and a tensor produced by any of them.

## 0.5 Understand one training step

**Goal:** Distinguish running a model from changing its learned parameters.

Inference computes an output using the current parameters. Training computes an objective, differentiates it, and applies an update. For this classifier, the head emits logits, which are unnormalized scores for the three classes. `CrossEntropyLoss` accepts those scores directly with the target class indices. Do not insert a softmax before this loss in the class-index example. [R65]

A loss function is the numerical objective you choose to minimize. Its value is not automatically the product metric. A lower classification loss does not measure the speed of your Android app, and a lower reconstruction loss does not establish that a video keeps the intended character identity.

Autograd records differentiable operations and computes gradients when `backward()` is called. A parameter's gradient describes the local derivative of the objective with respect to that parameter. It is not a reliable standalone ranking of how safely an entire layer can be deleted. [R60]

This is the core order used by the supplied training routine:

```python
optimizer.zero_grad(set_to_none=True)
logits = model(features)
loss = torch.nn.functional.cross_entropy(logits, labels)
loss.backward()
optimizer.step()
```

`zero_grad` clears gradients from the previous update. `backward` computes new gradients. `step` applies the optimizer's update. The executed test checks that a weight has not changed after `backward` alone and does change after `step`. Learning rate controls the update scale; it is a training configuration value rather than a model weight. [R61, E04]

There are two controls you must keep separate:

```python
model.eval()
with torch.inference_mode():
    prediction = model(features)
```

`eval()` changes module training/evaluation behavior where that distinction exists, such as dropout or batch normalization. It does not disable autograd. `inference_mode()` changes gradient-tracking behavior and related overhead. Conversely, `no_grad()` does not call `eval()` for you. The course tests the distinction directly. During distillation, the teacher forward pass uses `no_grad()` so its outputs can safely be used as fixed training targets. [R73, E04]

The basic mathematics needed here is limited: vector and matrix dimensions, weighted sums, functions, the meaning of a derivative, and averages over examples. You can learn deeper optimization theory while doing experiments rather than postponing every experiment until you finish a mathematics curriculum.

**Exercise:** Set a breakpoint before `backward`, after `backward`, and after `step`. Inspect one parameter and its `.grad`. Explain why gradient accumulation occurs when gradients are not cleared. [R61]

**Exit check:** You can identify the forward pass, objective, gradient computation, parameter update, and evaluation mode as five separate concerns.

## 0.6 Separate learning from evaluation

**Goal:** Avoid selecting a smaller model using evidence that it has already been trained or repeatedly tuned to satisfy.

Use three roles for data. Training examples drive parameter updates. Validation examples guide choices such as which block to remove or which recovery recipe to retain. A held-out test set measures the final selected procedure. When you repeatedly use test results to make choices, that set is no longer an untouched test. Preprocessing learned from data must also be fitted without leaking evaluation information. [R37]

The course generates 2,048 training examples, 512 validation examples, and 512 final test examples using separate random seeds. Their labels come from an explicitly defined nonlinear rule, not from the teacher. The code selects the removed block and the recovery candidate using validation cross-entropy. Only after selection does it evaluate the teacher and selected candidate on the final test data. [E04]

That design demonstrates data roles, not real-world representativeness. For a production application, the unit of separation matters. Two adjacent frames from one video should not automatically be treated as independent examples across training and evaluation. Propose splits by video, scene, speaker, recording session, subject, or source according to what could leak in your task. Record why that unit was chosen.

Your evaluation also needs to match the actual function. A classifier can use accuracy and class-specific errors. A separator needs appropriate reference stems or a separately designed listening evaluation. Image and video generation require controlled prompts, seeds, output settings, and task-specific review. Do not replace all these questions with one generic metric or use a small set of random prompts as a universal quality certificate. See Chapter 3.

**Exercise:** Before inspecting any new candidate results, write this rule in your experiment note: select the CE or KD student with lower validation cross-entropy, with CE winning ties. Then confirm that `run.py` follows that rule. It does not select whichever method produces the more impressive story.

**Exit check:** You can name every dataset's role and explain which decisions it influenced. You have a final evaluation set or explicitly label the work as exploratory when no untouched test exists.

## 0.7 Profile before changing the model

**Goal:** Identify the quantity that actually needs to improve.

Model file size, parameter payload, an intermediate tensor's size, allocator reservations, and process memory are different measurements. A file can get smaller while runtime memory stays high. A model can use fewer arithmetic operations while an unsupported operator forces an expensive backend transition. Chapter 2 provides the full accounting framework. [R16, R21]

Begin with four records: the architecture and checkpoint identity, quality on the fixed evaluation cases, warmed inference timing for a defined input, and a memory measurement appropriate to your platform. Record initialization time separately. Record accelerator synchronization where applicable. Profiling tools can perturb execution, so perform the final timing run without expensive tracing attached. [R09]

The course exposes a deliberately modest inspection function:

```python
from crash_course.run import trace_shapes

rows = trace_shapes(model, torch.zeros(1, 16))
for row in rows:
    print(row["module"], row["shape"], row["logical_output_bytes"])
```

The hooks retain names, shapes, and scalar byte counts, not output tensors. They are removed in a `finally` block. The sum of the rows is not peak memory: outputs can share storage or have nonoverlapping lifetimes, and the trace does not include every internal allocation. The recorded run does not claim a peak-RAM result. [E04]

The timing exercise uses one CPU thread, batch size one, 30 warmup calls per model, and 200 measured calls per model. It alternates model order and saves every sample. These measurements describe this small implementation in the recorded environment. They are not a forecast for a phone. [E04]

**Exercise:** Choose one objective for the next change: lower measured latency, lower measured peak memory, or smaller parameter storage. State what evidence would support improvement and what would falsify your hypothesis. Do not write only "make it lighter."

**Exit check:** You can distinguish a calculated quantity from an observed one and can name the baseline against which the next measurement will be compared.

## 0.8 Make your first structural edit

**Goal:** Change the architecture deliberately and verify the edit independently of its task quality.

TinyNet's residual blocks preserve their input shape. That makes bypassing one block executable without adding a shape adapter. It does not make bypassing the block behavior-preserving. The course tests each block removal separately on validation data and selects the candidate with the lowest validation loss. Those single-removal results do not prove that removing several blocks together is safe. [E04]

```python
from crash_course.models import drop_block, shrink_inner

# Valid for TinyNet. Not a recipe for deleting an HDemucs encoder stage.
candidate = drop_block(teacher, index=chosen_index)
candidate = shrink_inner(candidate, inner=32)
```

The second transformation keeps the residual width at 32 while shrinking the internal branch width from 64 to 32. It removes matching rows from the first projection, matching entries from its bias, and matching columns from the second projection. It preserves the second bias. Simply setting the unwanted weights to zero would leave the original dense tensor dimensions in place. [E04; R01, R02]

The supplied pruning routine includes checks for empty, duplicate, negative, and out-of-range indices. Its correctness test compares the smaller branch with an original-sized branch whose removed intermediate units are masked to zero. That comparison should match within tolerance. Comparing the smaller branch with the unmodified original should not generally match. These are different tests with different purposes. [E04]

The course ranks retained inner units by the absolute weight sum of the first projection. This is an intentionally simple heuristic. It is not a claim that these are the most important units for another model or even the best units for this task.

After replacing parameter objects, build a new optimizer for the candidate. Otherwise an existing optimizer may still reference the original objects. Also update configuration metadata so saving and reloading reconstructs the smaller architecture. The course tests both the numerical transformation and the save/load round trip. [E04]

**Exercise:** Inspect parameter counts after block removal and after inner-width reduction. The recorded sizes are 13,219, 9,027, and 4,867 respectively. Then inspect quality separately. A successful shape test cannot establish preserved classification performance. [E04]

**Exit check:** You have an untouched baseline, a candidate with physically smaller tensors, an explicit architecture configuration, and tests that would fail if your connected tensor slices were wrong.

## 0.9 Recover the model and test distillation

**Goal:** Compare ordinary fine-tuning with teacher-guided recovery instead of assuming one must win.

Fine-tuning continues parameter updates from an existing checkpoint. Knowledge distillation adds information from a teacher to the student's training objective. The teacher and student need not have identical internal layers, but the selected target must be meaningfully comparable. For this classifier, both models predict the same three classes. [R04]

The lab starts two students from identical copied candidate weights. Each sees the same training examples in the same minibatch order and receives 200 optimizer steps. One uses only cross-entropy against the known labels. The other combines that loss with a soft-target objective from a frozen teacher. Online distillation also performs teacher inference, so equal student update counts do not mean equal total compute. [E04]

The soft-target calculation is:

```python
with torch.no_grad():
    teacher_logits = teacher(features)

soft_loss = torch.nn.functional.kl_div(
    torch.nn.functional.log_softmax(student_logits / temperature, dim=-1),
    torch.nn.functional.softmax(teacher_logits / temperature, dim=-1),
    reduction="batchmean",
) * temperature ** 2
```

Temperature controls the softened class distributions. PyTorch's KL loss expects log-probabilities for its first argument under the default target convention. The temperature-squared factor follows the standard soft-target distillation treatment. This classifier objective is not a drop-in loss for matching video frames, audio waveforms, or diffusion noise predictions. [R05, R66]

The recorded validation results are deliberately shown without choosing a favorable narrative:

| Candidate | Parameters | Validation accuracy | Validation cross-entropy |
|---|---:|---:|---:|
| Trained teacher | 13,219 | 94.73% | 0.1895 |
| Block removed and inner width pruned, before recovery | 4,867 | 91.80% | 0.2682 |
| Same candidate after supervised fine-tuning | 4,867 | 94.73% | 0.1503 |
| Same candidate after distillation | 4,867 | 94.53% | 0.1682 |

These are rounded values from one synthetic CPU run. The prespecified selection rule retained the supervised student because it had lower validation cross-entropy. On the final 512-example test set, the teacher achieved 93.16% accuracy and the selected student 94.53%. This does not establish that pruning improves generalization or that distillation is inferior in general. The experiment is too small and narrow to support those claims. [E04]

The hardware budget for larger recovery runs must include more than the student's checkpoint. It can include resident teacher and student weights, student gradients, optimizer state, live activations, workspace, and inputs. Freezing the teacher removes its parameter-gradient updates but not the cost of its forward pass. Offline teacher targets can separate teacher inference from student training, but require storage and a precisely recorded target-generation contract. [R73; proposed planning procedure]

The course's CPU execution is evidence that **this lab** needs no GPU. It is not evidence that a video-diffusion teacher and student fit on the same hardware. Before buying hardware for a real model, run or obtain a representative memory profile for the exact resolution, sequence length, batch size, precision, and training method.

**Exercise:** Read the loss curves, ablation results, and final selection in `report.json`. Describe what the run establishes and at least two questions it does not answer.

**Exit check:** You can implement teacher-free and teacher-guided recovery, freeze the teacher correctly, and report an unfavorable distillation result without discarding it.

## 0.10 Cross the export and quantization boundary

**Goal:** Treat a deployed graph as another implementation that needs its own tests.

An ONNX file describes a model graph and its data. ONNX Runtime is an execution engine for compatible graphs. An Execution Provider supplies backend implementations. Exporting successfully does not establish that the target backend supports every operation or that it executes them efficiently. [R49, R17]

Before quantization, export a full-precision candidate and compare its outputs against PyTorch. Otherwise a quantization regression and an export regression arrive at the same time. The optional `crash_course/export_onnx.py` exports a fixed `[1, 16]` input contract, validates the graph, and compares 32 generated inputs using CPU ONNX Runtime. It writes a parity record only after those checks pass.

```bash
python -m crash_course.export_onnx \
  evidence/crash_course/selected.pt \
  runs/export/selected.onnx
```

**Status:** This script is provided for execution in your environment. The preparation environment did not contain the optional ONNX dependencies, so no exported model or parity result is claimed or included. Install compatible `onnx`, `onnxscript`, `onnxruntime`, and `numpy` packages, record their versions, and inspect their supported export path before use. `numpy` is required even though the core course does not need it, because the parity comparison converts a tensor with `.numpy()`. The module checks for the three ONNX packages and reports them; a missing `numpy` instead surfaces later as an `ImportError`. On Windows, set `PYTHONUTF8=1` for this command: PyTorch's exporter writes progress characters that a console using the legacy cp1252 encoding cannot represent, which raises `UnicodeEncodeError` from inside `torch.onnx` after the export itself has already succeeded. [R13; proposed exercise]

Quantization changes numerical representation. Weight-only compression and quantized activations are different interventions. A four-bit weight file does not establish that the target device performs four-bit arithmetic. Support depends on graph operations, quantization form, runtime version, and backend kernels. Static quantization also requires representative calibration data. [R14]

For the first deployment exercise, keep the float model as a reference and add quantization as a second candidate. Compare numerical drift, task quality, model storage, runtime memory, and latency. Do not require exact floating-point equality after an intentional approximation. Set tolerances and task acceptance criteria before interpreting the result.

**Exercise:** Write a deployment manifest with input/output names, shapes, dtypes, feature meanings, preprocessing, checkpoint digest, export settings, and runtime version. Explain why dimensions alone would not catch the layout bug from Lesson 0.3.

**Exit check:** You have separate records for PyTorch quality, exported-model parity, and quantized-model quality. An export script is not being presented as an Android benchmark.

## 0.11 Integrate and measure on Android

**Goal:** Reuse your Android engineering skills without letting the app hide a model-contract failure.

Start with a numeric fixture rather than camera or microphone input. The lab writes `golden.json`, containing one `[1, 16]` feature vector and its expected three logits. This isolates tensor construction, model loading, and output interpretation from sensor preprocessing. The features are synthetic numbers, not image pixels. [E04]

The optional `android_example/TinyNetRunner.kt` shows the ONNX Runtime Java interface from Kotlin. Its responsibility is narrow: load a verified model file, construct the input tensor, run the named output, copy the scores, and release per-call resources. It is a source example, not a complete Android Studio application or a compiled device artifact. ONNX Runtime documents Java session creation, tensors, inference, and resource cleanup. [R72]

Use this integration contract:

```text
trusted exported model + golden input fixture
  -> Kotlin tensor construction
  -> ONNX Runtime CPU execution
  -> three raw output scores
  -> compare with expected output using stated tolerance
```

After this passes, integrate actual preprocessing for a real model. Keep inference off the UI thread, define who owns the session, close resources, handle invalid inputs, and prevent shutdown from racing with an active call. The included wrapper serializes access to its session; your application must still provide an appropriate lifecycle and worker context.

Only then investigate accelerators. Choose the runtime and provider using supported operations and measured behavior on the actual devices. NNAPI is deprecated starting with Android 15, so it should not be treated as the default future deployment strategy simply because older examples use it. The official Android guidance and runtime support for your selected version should guide backend selection. [R71, R16]

Measure initialization separately from repeated inference. Add sustained runs, memory pressure, foreground/background transitions, and thermal behavior to device testing. Android process-memory tools report different quantities from a tensor payload calculation; choose and label the measure used in your acceptance gate. [R21, R22, R23]

**Exercise:** Follow `android_example/README.md` after executing export locally. Compare the golden fixture before adding UI features. Fill the device-measurement template even when the outcome is that the smaller model is not faster.

**Exit check:** You can say whether a failure belongs to preprocessing, graph conversion, runtime support, application lifecycle, or model quality, rather than treating every failure as "the AI model is broken."

## 0.12 Choose the next model and graduate

**Goal:** Carry the method to another family without copying an inappropriate transformation.

Your next experiment should change one known bottleneck in a model you can already run and evaluate. The following routes are proposals, not executed production recipes.

| Next family | First bounded experiment | New knowledge to acquire |
|---|---|---|
| Image classifier | Reproduce baseline evaluation and physically prune a supported channel group | Image preprocessing, label mapping, convolution dependencies |
| Image diffusion | Profile text encoder, denoiser, scheduler calls, and decoder separately before changing one component | Latent representations, timesteps, conditioning, denoising objectives |
| Video diffusion | Fix prompt, frame count, resolution, and sampling settings; inspect the actual temporal-memory bottleneck | Temporal context, frame consistency, motion evaluation |
| Audio separation | Reproduce the checkpoint's own sample-rate and stem contract; test supported segmentation settings first | STFT, complex values, overlap, waveform alignment, reference stems |
| Language model | Verify tokenizer and decoding settings, then measure a controlled context-length workload | Tokens, attention, KV state, task-specific evaluation |

For diffusion, reducing denoising steps and removing neural layers are different changes. A scheduler determines how iterative updates are applied; the denoiser predicts a quantity at a particular noise level. A classifier's three-class KL loss is not automatically a diffusion-training objective. Read Chapter 12 before adapting the recovery loop. [R31, R38, R42]

For HDemucs, an encoder stage can change frequency or time resolution and participate in skip connections and the relationship between waveform and spectrogram paths. It is not interchangeable with the shape-preserving TinyNet branch. Use Appendix D to identify the architecture and its inference wrapper before deciding what to change. [R51, R55]

Build a short graduation record with your chosen checkpoint, the exact input contract, baseline measurements, one change, correctness tests, quality evaluation, and a keep-or-revert decision. A good decision can be to reject the modification because it damages quality or does not improve the measured bottleneck.

**Readiness test:** Explain, without relying on this text, why smaller weights may not reduce peak activations, why a passing shape test is insufficient, why the teacher can be frozen but still consume compute, and why desktop timing does not establish phone performance. Then run the course from a clean environment or explain any environment difference you introduced.

**Where to continue:** Chapters 1 through 3 formalize the baseline and evaluation process. Chapters 4 through 11 develop the transformation catalog. Chapters 12 through 14 address diffusion and deployment. Chapters 15 through 17 explain recorded experiments and acceptance. The glossary remains available through linked terminology throughout the book.

---
