Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5a03969
chore: scaffold py-edu-gemma-moe with trainite init
aaishwarymishra Nov 12, 2026
2aee8a2
feat: swap GPT-2 tokenizer for corpus-trained 8192 BPE
aaishwarymishra Nov 12, 2026
46af175
feat: split digits and whitespace, train pad in vocab
aaishwarymishra Nov 12, 2026
b1c03b9
feat: port benchmark and HumanEval+ evaluation from reference
aaishwarymishra Nov 12, 2026
3b16f5c
feat: add 15M MoE and dense configs
aaishwarymishra Nov 12, 2026
10208bb
feat: shard extraction, add dataset_size cap
aaishwarymishra Nov 12, 2026
09e4fe7
refactor: inline HumanEval helpers into trainer
aaishwarymishra Nov 12, 2026
487b561
refactor: move configs into configs/
aaishwarymishra Nov 12, 2026
3bf62e2
feat: add Vast SkyPilot launch
aaishwarymishra Nov 12, 2026
4f1f051
fix: pass a Regex to the tokenizer Split
aaishwarymishra Nov 12, 2026
5e3d05d
feat: add a tokenizer recipe knob with GPT-2 control configs
aaishwarymishra Nov 13, 2026
6a68ae4
refactor: drop the tokenizer ablation, keep the code tokenizer
aaishwarymishra Nov 13, 2026
cfecb67
refactor: match the reference run's GPT-2 pre-tokenizer
aaishwarymishra Nov 13, 2026
9e0334a
chore(py-edu-gemma-moe): rename ClearML project, qualify task names
aaishwarymishra Nov 13, 2026
e59f8f4
feat(py-edu-gemma-moe): direct Vast launcher in place of SkyPilot
aaishwarymishra Nov 13, 2026
329da0c
feat(py-edu-gemma-moe): walkthrough notebook for the dense/MoE run
aaishwarymishra Nov 18, 2026
ff1cd89
docs(py-edu-gemma-moe): drop the private Vast launcher
aaishwarymishra Nov 18, 2026
4c15d81
build(py-edu-gemma-moe): install base skypilot, not the Vast extra
aaishwarymishra Nov 18, 2026
1b45d07
docs(py-edu-gemma-moe): rewrite the README in the style of the other …
aaishwarymishra Nov 18, 2026
52a6850
refactor(py-edu-gemma-moe): drop the gpt2 suffix from the tokenizer c…
aaishwarymishra Nov 18, 2026
f8737f1
docs(py-edu-gemma-moe): frame the example as teaching Python, not den…
aaishwarymishra Nov 18, 2026
51da401
docs(py-edu-gemma-moe): explain how the HumanEval noise floor is comp…
aaishwarymishra Nov 18, 2026
5aeaf57
remove reduntant items from gitignore
aaishwarymishra Nov 18, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ Working examples are in the [`examples/`](examples/) directory:
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`string_reversal`](examples/string_reversal/) | Train a decoder-only transformer to reverse strings. Demonstrates the full pipeline: data generation, training, evaluation, and inference logging. |
| [`counting`](examples/counting/) | Train a decoder-only transformer to count the number of occurrences of a target token in a sequence. |
| [`py-edu-gemma-moe`](examples/py-edu-gemma-moe/) | Teach a 15M Gemma 4 model to write Python, with a dense vs. MoE feed-forward comparison and a walkthrough notebook. |

Each example is a standalone project — `cd` into it, install dependencies, and run `python main.py config.yaml`.

Expand Down
4 changes: 4 additions & 0 deletions examples/py-edu-gemma-moe/.skyignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
data/
outputs/
.venv/
__pycache__/
168 changes: 168 additions & 0 deletions examples/py-edu-gemma-moe/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
# Teaching a 15M Gemma 4 Model to Write Python

How much Python can a 15M-parameter decoder learn from scratch? This example trains Gemma 4 models
on Python functions and scores them on HumanEval+ mini, where the model gets a signature and docstring
and has to write the body.

The example trains two variants on the same corpus. They differ only in the feed-forward block: one
dense MLP, one mixture-of-experts with the same parameters active per token. That makes the MoE a
side question: does expert storage buy measurable Python ability at this scale, or not yet?

The base project was generated with `trainite==0.2.0`:

```bash
trainite init py-edu-gemma-moe --model gemma4-moe gemma4-dense --dataset python-edu --trainer decoder-trainer --run-name gemma4_moe__py_edu_15m
```

Customizations on top of the generated project:

1. **Preprocessor (`preprocessors/python_bpe.py`)**: a byte-level BPE fitted on the corpus replaces the
GPT-2 tokenizer.
2. **Dataset (`dataset_impl/python_edu.py`)**: rows are parsed with `ast` and only self-contained
top-level functions are kept, instead of training on whole files.
3. **Trainer (`trainer.py`)**: HumanEval+ mini evaluation via the official EvalPlus evaluator, run
with and without the prompt's docstring.

## Task and data

[`Avelina/python-edu-cleaned`](https://huggingface.co/datasets/Avelina/python-edu-cleaned) is 6.05 GB
of Python source, 7,677,467 rows, Open Data Commons Attribution (ODC-BY). HumanEval hands the model a
signature and a docstring and asks for the body, so `load_function_dataset` turns each row into
prompt/completion pairs instead of training on whole files:

* Only top-level `def`/`async def`, no decorators and no inline suites.
* Only absolute imports, and only from the standard library plus a small allowlist of common data
packages (`numpy`, `pandas`, `torch`, `sklearn`, ...).
* No reference to module-level globals the function does not define, so the body stands alone.
* The prompt is the file's imports plus the signature (and its docstring, when `require_docstring` is
on); the completion is the body. `<eos>` is appended and prompt tokens are masked out of the loss.

The data splits 80/10/10 into train/val/test with `DataWithAutoSplit`. Sequences are capped at 512
tokens, with an 8192-token BPE vocabulary fitted once on the corpus.

Both configs set `require_docstring: false`, which roughly quadruples the usable corpus at the cost of
prompts that are only a signature. A single example:

```text
def add(a, b):
return a + b
```

## The two models

| | `configs/dense.yaml` | `configs/moe.yaml` |
|---|---|---|
| model | `Gemma4DenseModel` | `Gemma4MoEModel` |
| feed-forward | `dense_intermediate_size: 1536` | `dense_intermediate_size: 768`, `num_experts: 3`, `expert_dim: 384`, `top_k: 2` |
| loss | `CausalLMCrossEntropyLoss` | `GemmaMoECausalLMLoss`, `aux_loss_coef: 0.01` |
| parameters, total | 13,051,400 | 15,425,056 |
| parameters per token | 13,051,400 | 13,065,760 |
| training time, 4 epochs | 7h57m | 12h27m |
| seconds per step | 0.1380 | 0.2144 |

Both arms share the rest of the config: 8 layers, hidden size 256, 4 attention heads with 2 KV heads,
head dimension 64, the `sssg` sliding/global pattern with a 512-token window, batch size 64, AdamW at
6e-4, bf16, 4 epochs, one RTX 3090 each.

## Metrics

* `loss`: teacher-forced cross-entropy on completion tokens.
* `token_accuracy`: token-level accuracy on completion tokens.
* HumanEval+ mini (`humaneval/...`): 164 problems, greedy decoding, scored by EvalPlus' official
evaluator. Each checkpoint solves the set twice, once with the docstring in the prompt and once with
it stripped, which separates code synthesis from copying the description.

## Results

| | dense | MoE |
|---|---|---|
| validation loss | 1.0639 | 1.0637 |
| token accuracy | 0.7494 | 0.7495 |
| HumanEval+ base, docstring | 15/164 | 16/164 |
| HumanEval+ base, stripped | 19/164 | 18/164 |
| HumanEval+ plus, docstring | 12/164 | 13/164 |
| HumanEval+ plus, stripped | 16/164 | 15/164 |

The pretraining run does not separate the two models. The extra 2.4M expert parameters moved the
validation loss by 0.0002 and HumanEval by one task, while costing 1.6x the training time. The experts
are storage, not arithmetic: 768 shared + 2 of 3 x 384 = 1536 per token, exactly the dense FFN width,
so both arms do the same work per token.

That is a statement about this budget, not about MoE in general. Both arms stopped after four
pretraining epochs on next-token prediction, and neither was post-trained. Nothing here rules out the
experts becoming useful under more training or a later code post-training stage; it only says the
storage on its own does not pay off yet.

### Noise floor

The counts come from 164 problems, so they are a sample, not a measurement. At the observed 9-12%
pass rate the binomial standard error is `sqrt(p * (1 - p) / 164)`, or 2.3-2.5 points (3.8-4.1
tasks). A one-task gap is well inside that.

Pairing the models on the same problems does not change the answer. With a one-task margin the
discordant counts differ by one, so an exact McNemar test returns `p = 1` for every possible
per-problem pairing. The docstring gaps, 15 vs 19 and 16 vs 18, are not significant either: even the
most favorable pairing gives `p = 0.125` and `p = 0.5`.

That covers sampling noise only. Each arm is a single seed, so how much HumanEval moves between
training runs, usually the larger term, is not measured here. The per-task outcomes a paired test
needs are written next to each run as `humaneval_samples*_eval_results.json`.

## Run the example

From this directory:

```bash
uv sync
uv run python main.py configs/dense.yaml
uv run python main.py configs/moe.yaml
```

The configs log to ClearML, so watch the run in the ClearML web UI. For local TensorBoard instead, set
`logger: tensorboard` and run:

```bash
uv run tensorboard --logdir outputs
```

Checkpoints and logs are written below `outputs/<run_name>/<timestamp>/`.

### Cloud

`sky.yaml` runs the same command on a rented GPU:

```bash
sky check
sky launch sky.yaml
```

Set `envs.CONFIG` to pick the arm, and edit the resource block to change the accelerator, price cap, or
provider (`cloud: aws`, `cloud: vast`, ...). Without a `cloud` entry SkyPilot picks any provider that
satisfies the request.

> [!NOTE]
> The numbers above were produced on Vast.ai with a small private `vastai` launcher, not
> `sky launch`: SkyPilot's Vast backend could not list or destroy instances and attached the wrong SSH
> keys at the time. `sky.yaml` is the portable path and works on any provider; the custom launcher is
> not part of this example.

## Walkthrough notebook

`walkthrough.ipynb` walks through the data, the collator, both architectures, and inference. It runs
on a 5,000-example slice of the corpus and loads the trained weights from
[`Blankyy/py-edu-gemma-15m`](https://huggingface.co/Blankyy/py-edu-gemma-15m), so it needs no ClearML
credentials. The weights and tokenizer (~114 MB) are cached by `huggingface_hub` on first run.

Open it from this directory with the example's `.venv` kernel.

## Files

* `configs/dense.yaml`, `configs/moe.yaml` — the two arms.
* `main.py` — single-run entry point.
* `trainer.py` — training loop, metrics, checkpoints, HumanEval+ evaluation.
* `config.py`, `utils.py` — config schema and wiring.
* `models/gemma4_dense.py`, `models/gemma4_moe.py` — the two architectures.
* `dataset_impl/python_edu.py` — function extraction and tokenization.
* `preprocessors/python_bpe.py` — corpus-trained BPE tokenizer.
* `walkthrough.ipynb` — end-to-end walkthrough with the published weights.
* `sky.yaml` — SkyPilot cloud launch.
115 changes: 115 additions & 0 deletions examples/py-edu-gemma-moe/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
from typing import Literal, Self
from pydantic import BaseModel, ConfigDict, Field, model_validator


class ModelConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
target: str = Field(alias="_target_")
collate_fn_target: str | None = None


class PreprocessorConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
target: str = Field(alias="_target_")


class DatasetConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
target: str = Field(alias="_target_")


class TransformConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
target: str = Field(alias="_target_")


class OutputConfig(BaseModel):
model_config = ConfigDict(validate_assignment=True)
root: str
run_name: str


class OptimizerConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
target: str = Field(alias="_target_", default="torch.optim.AdamW")
lr: float = Field(default=1e-3, gt=0.0)


class LossConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
target: str = Field(alias="_target_", default="trainite.models.basic_transformer.CausalLMCrossEntropyLoss")
ignore_index: int = -100


class DataLoaderConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
batch_size: int = Field(default=32, gt=0)
shuffle: bool = False
num_workers: int = Field(default=2, ge=0)


class SplitConfig(BaseModel):
model_config = ConfigDict(validate_assignment=True)
dataset: DatasetConfig
transform: TransformConfig | None = None
dataloader: DataLoaderConfig = Field(default_factory=DataLoaderConfig)


class DataConfigBase(BaseModel):
model_config = ConfigDict(validate_assignment=True)
train: SplitConfig
val: SplitConfig
test: SplitConfig | None = None


class DataWithAutoSplit(BaseModel):
model_config = ConfigDict(validate_assignment=True)
dataset: DatasetConfig
transform: TransformConfig | None = None
dataloader: DataLoaderConfig = Field(default_factory=DataLoaderConfig)
test_ratio: float = Field(default=0.2, ge=0.0, lt=0.5)
val_ratio: float = Field(default=0.1, gt=0.0, lt=0.3)

@model_validator(mode="after")
def check_split_ratios(self) -> Self:
train_ratio = 1.0 - self.test_ratio - self.val_ratio
if train_ratio <= 0.5:
raise ValueError("train ratio (1.0 - test_ratio - val_ratio) must be greater than 0.5")
if train_ratio > 0.9:
raise ValueError("train ratio (1.0 - test_ratio - val_ratio) must be less than or equal to 0.9")
return self


class TrainerConfig(BaseModel):
model_config = ConfigDict(extra="allow", validate_assignment=True)
epochs: int = Field(default=3, gt=0)
precision: Literal["float32", "fp16", "bf16"] = "float32"
log_every_steps: int = Field(default=10, gt=0)
early_stopping_patience: int | None = Field(default=3, gt=0)
inference_every_epochs: int | None = Field(default=None, gt=0)
inference_num_samples: int = Field(default=5, gt=0)
max_inference_new_tokens: int = Field(default=16, gt=0)
benchmark_every_epochs: int | None = Field(default=None, gt=0)
benchmark_num_samples: int = Field(default=10, gt=0)
max_benchmark_new_tokens: int = Field(default=128, gt=0)
humaneval_enabled: bool = True
humaneval_max_new_tokens: int = Field(default=192, gt=0)
humaneval_batch_size: int = Field(default=8, gt=0)
humaneval_strip_docstrings: bool = False
humaneval_truncate_at_top_level: bool = False
grad_clip_norm: float | None = Field(default=None, gt=0.0)


class ProjectConfig(BaseModel):
model_config = ConfigDict(validate_assignment=True)
project_name: str
preprocessor: PreprocessorConfig
model: ModelConfig
optimizer: OptimizerConfig = Field(default_factory=OptimizerConfig)
loss: LossConfig = Field(default_factory=LossConfig)
data: DataConfigBase | DataWithAutoSplit
trainer: TrainerConfig = Field(default_factory=TrainerConfig)
output: OutputConfig
logger: Literal["tensorboard", "clearml"] = "tensorboard"
seed: int = 42
device: str | None = None
70 changes: 70 additions & 0 deletions examples/py-edu-gemma-moe/configs/dense.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
project_name: py-edu-gemma
preprocessor:
_target_: preprocessors.python_bpe.load_python_bpe_tokenizer
vocab_size: 8192
cache_dir: outputs/tokenizers
model:
_target_: models.gemma4_dense.Gemma4DenseModel
collate_fn_target: models.gemma4_dense.CausalLMCollateFn
hidden_size: 256
num_layers: 8
num_attention_heads: 4
num_key_value_heads: 2
dense_intermediate_size: 1536
head_dim: 64
layer_types: null
layer_pattern: sssg
sliding_window: 512
rope_theta: 10000.0
global_rope_theta: 1000000.0
rotary_fraction: 1.0
global_rotary_fraction: 0.25
global_num_key_value_heads: 2
global_head_dim: 64
global_key_equals_value: true
attention_dropout: 0.0
optimizer:
_target_: torch.optim.AdamW
lr: 0.0006
loss:
_target_: models.gemma4_dense.CausalLMCrossEntropyLoss
ignore_index: -100
data:
dataset:
_target_: dataset_impl.python_edu.load_function_dataset
path: Avelina/python-edu-cleaned
dataset_size: null
split: train
max_length: 512
require_docstring: false
transform:
_target_: dataset_impl.python_edu.PythonEduTransform
max_length: 512
dataloader:
batch_size: 64
shuffle: true
num_workers: 8
test_ratio: 0.1
val_ratio: 0.1
trainer:
epochs: 4
precision: bf16
log_every_steps: 1000
early_stopping_patience: 2
inference_every_epochs: null
inference_num_samples: 2
max_inference_new_tokens: 16
benchmark_every_epochs: 1
benchmark_num_samples: 2
max_benchmark_new_tokens: 128
humaneval_enabled: true
humaneval_max_new_tokens: 192
humaneval_batch_size: 16
humaneval_strip_docstrings: true
grad_clip_norm: 1.0
output:
root: outputs
run_name: gemma4_dense__py_edu_15m
logger: clearml
seed: 42
device: null
Loading
Loading