Cheat sheets

Notebooks, Data Files and Profiling

Run notebooks safely, load and split datasets, keep big files out of git, profile time and memory, catch silent AI bugs.

  • Tasks and commands
  • Annotated code
  • Diagrams
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Notebook troubleshooting#

SymptomCauseFix
Works for me, breaks for othersCells run out of orderKernel > Restart & Run All before sharing
Clean notebook needs a deleted cellHidden state in the kernelRestart the kernel regularly
RAM keeps growingVariables persist across cellsdel variable_name and gc.collect()
Kernel dies silentlyUI hides the errorRead the terminal that runs Jupyter
print(df) shows textNot the last expressionEnd the cell with df
Import error after pip installPackage in another Python!pip install package in the notebook
Cell runs foreverWaits for input() or a loopKernel > Interrupt, or I twice
Colab files goneFree session ended after 90 minutes of inactivitydrive.mount('/content/drive')

From Lesson 00.05, 00.05 outputs/prompt-notebook-helper.md

Load, stream, convert, split#

dataset = load_dataset("stanfordnlp/imdb", split="train")cached after first load
stream = load_dataset("wikimedia/wikipedia", "20231101.en", split="train", streaming=True)
dataset.to_parquet("imdb_train.parquet")also to_csv, to_json
split = dataset.train_test_split(test_size=0.2, seed=42)
train_val = split["train"].train_test_split(test_size=0.125, seed=42)
train_ds, val_ds, test_ds = train_val["train"], train_val["test"], split["test"]
make_splits(ds, train_ratio=0.8, val_ratio=0.1, seed=42)data_utils helper
model_dir = snapshot_download("sentence-transformers/all-MiniLM-L6-v2")

From Lesson 00.09, 00.09 code/data_utils.py

Debug and profile tools#

TaskCode
Stop only on a bad lossif loss.item() > 100 or torch.isnan(loss): breakpoint()
Inspect in pdbp outputs.shape, p loss.item(), then c or q
Profile functionspython -m cProfile -s cumtime train.py
Profile lines@profile, then kernprof -l -v train.py
Memory by linepython -m memory_profiler your_script.py
Top allocationstracemalloc.take_snapshot().statistics("lineno")
GPU memorytorch.cuda.memory_allocated(), torch.cuda.memory_reserved()
Training curvesSummaryWriter("runs/experiment_1"), then tensorboard --logdir=runs

From Lesson 00.12

Silent AI bugs#

SymptomCauseFix
NaN after a few stepsLearning rate too highReduce by 10x. Add gradient clipping
NaN immediatelyLog of zero or negativetorch.log(x + 1e-8)
Loss stuck at ln(num_classes)No gradient flowRemove the accidental .detach()
99% test accuracyData leakagecheck_data_leakage(train_set, test_set)
OOMBatch too largeHalve the batch. torch.cuda.empty_cache()
OOM during backwardGradients not clearedoptimizer.zero_grad() each step
Slow, low GPU useData loading bottlenecknum_workers=4 and pin_memory=True
Tensor on the wrong deviceCPU tensor, GPU modelcheck_devices(model, *tensors)

From Lesson 00.12, 00.12 outputs/prompt-debug-ai-code.md

Notebook shortcuts#

CommandWhat it does
pip install jupyterlab then jupyter labStart JupyterLab
Escape / EnterCommand mode / edit mode
Shift+EnterRun cell, move to next
A / BInsert cell above / below
DDDelete cell
M / YConvert to markdown / code
Shift+TabShow function signature
Ctrl+Shift+HShow all shortcuts

From Lesson 00.05

Magic commands#

CommandWhat it does
%timeit np.random.randn(10000)Runs many times and averages. Microbenchmarks
%%timeRuns the cell once. Training runs
%matplotlib inlinePlots render in the notebook
!pip install scikit-learn! runs any shell command
%env CUDA_VISIBLE_DEVICESCheck an environment variable
%whoList all variables in memory
!which pythonCheck the kernel environment

From Lesson 00.05, 00.05 outputs/prompt-notebook-helper.md

Data pipeline#

downloadfirst loadstoreHugging FaceHubdatasets andmodelsprocessdatasetslibraryload or streamstoreLocal Cache~/.cache/huggingface/processFormatConversionCSV, JSON,Parquet, ArrowprocessData Splitstrain / val /testmodelYour TrainingPipelinedownloadfirst loadstoreHugging Face Hubdatasets and modelsprocessdatasets libraryload or streamstoreLocal Cache~/.cache/huggingface/processFormat ConversionCSV, JSON, Parquet,ArrowprocessData Splitstrain / val / testmodelYour TrainingPipeline

From Lesson 00.09

File formats#

SettingDefaultNote
CSVSlowLarge. Human readability, spreadsheets
JSONSlowLarge. APIs, nested data
ParquetFastSmall. Best storage format for AI work
ArrowFastestSmall. In memory, inside datasets
Train split80%Validation 10%, test 10%
Dataset cache~/.cache/huggingface/datasets/Model cache is ~/.cache/huggingface/hub/

From Lesson 00.09

Keep big files out of git#

TaskCode
Ignore weights and data*.safetensors, *.pt, data/*.parquet, models/
Track with Git LFSgit lfs track "*.safetensors"
Commit the LFS rulesgit add .gitattributes
Start DVCdvc init
Track data with DVCdvc add data/training_set.parquet
Commit the pointergit add data/training_set.parquet.dvc data/.gitignore
Push data to S3dvc remote add -d myremote s3://my-bucket/dvc-store then dvc push

From Lesson 00.09

Debug workflow#

1Before trainingrun check_shapes with a sample batch.2First 10 stepsdebug_print loss, outputs and gradients. No NaN.3During traininglog loss, learning rate and gradient norms toTensorBoard.4When it breaksdrop breakpoint() at the failure point.5For speedtime data loading, forward and backward. Profilememory near OOM.

From Lesson 00.12

Read the curves#

Loss not decreasing?
Learning rate too low, or an architecture issue.
Loss oscillating wildly?
Learning rate too high.
Train loss down, val loss up?
Overfitting.
Weight histograms collapse to zero?
Vanishing gradients.
Gradient histograms explode?
Add gradient clipping.

From Lesson 00.12

Tips#

  • Explore in notebooks, ship in scripts.
  • Use %timeit for microbenchmarks and %%time for training runs.
  • Always set a seed. The same seed gives the same split.
  • Use streaming when a dataset does not fit on disk.
  • Data loading often takes 60% of training time. Set num_workers > 0.

From Lesson 00.05, Lesson 00.09, Lesson 00.12