|
| 1 | +"""Tiny RL smoke test: sample from the current policy, reward completions that |
| 2 | +contain the target answer, and run a few importance-sampling policy-gradient steps. |
| 3 | +
|
| 4 | + uv --project examples run python examples/tiny/tiny_rl.py base_url=http://127.0.0.1:9003 |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import json |
| 10 | +import math |
| 11 | +import os |
| 12 | +import shutil |
| 13 | +import statistics |
| 14 | +from pathlib import Path |
| 15 | +from typing import Any, cast |
| 16 | + |
| 17 | +import chz |
| 18 | +import tinker |
| 19 | +from tinker import types |
| 20 | + |
| 21 | +BASE_URL = "http://127.0.0.1:9003" |
| 22 | + |
| 23 | +os.environ.setdefault("TINKER_API_KEY", "tml-dummy-key") |
| 24 | +os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") |
| 25 | + |
| 26 | + |
| 27 | +@chz.chz |
| 28 | +class Config: |
| 29 | + base_model: str = "Qwen/Qwen2.5-0.5B" |
| 30 | + base_url: str = os.getenv("TINKER_BASE_URL", os.getenv("BASE_URL", BASE_URL)) |
| 31 | + log_dir: str = str(Path(__file__).with_name("artifacts") / "tiny_rl") |
| 32 | + prompt: str = "Question: What is 2 + 2?\nAnswer:" |
| 33 | + target: str = "4" |
| 34 | + steps: int = 2 |
| 35 | + samples_per_prompt: int = 8 |
| 36 | + max_tokens: int = 16 |
| 37 | + temperature: float = 1.0 |
| 38 | + learning_rate: float = 1e-5 |
| 39 | + grad_clip_norm: float = 1.0 |
| 40 | + loss_fn: str = "importance_sampling" |
| 41 | + rank: int = 16 |
| 42 | + seed: int = 0 |
| 43 | + behavior_if_log_dir_exists: str = "delete" |
| 44 | + |
| 45 | + |
| 46 | +def reset_log_dir(path: Path, behavior: str) -> None: |
| 47 | + if not path.exists(): |
| 48 | + path.mkdir(parents=True) |
| 49 | + return |
| 50 | + if behavior == "delete": |
| 51 | + shutil.rmtree(path) |
| 52 | + path.mkdir(parents=True) |
| 53 | + return |
| 54 | + if behavior == "error": |
| 55 | + raise RuntimeError(f"Log directory already exists: {path}") |
| 56 | + raise ValueError(f"Unsupported behavior_if_log_dir_exists={behavior!r}") |
| 57 | + |
| 58 | + |
| 59 | +def write_metric(log_dir: Path, row: dict[str, Any]) -> None: |
| 60 | + with (log_dir / "metrics.jsonl").open("a", encoding="utf-8") as f: |
| 61 | + f.write(json.dumps(row, sort_keys=True) + "\n") |
| 62 | + |
| 63 | + |
| 64 | +def build_datum(prompt_tokens: list[int], completion_tokens: list[int], logprobs: list[float], advantage: float) -> types.Datum: |
| 65 | + tokens = prompt_tokens + completion_tokens |
| 66 | + prompt_pad = [0.0] * (len(prompt_tokens) - 1) |
| 67 | + return types.Datum( |
| 68 | + model_input=types.ModelInput.from_ints(tokens=tokens[:-1]), |
| 69 | + loss_fn_inputs=cast( |
| 70 | + Any, |
| 71 | + { |
| 72 | + "target_tokens": tokens[1:], |
| 73 | + "weights": prompt_pad + [1.0] * len(completion_tokens), |
| 74 | + "logprobs": prompt_pad + logprobs, |
| 75 | + "advantages": prompt_pad + [advantage] * len(completion_tokens), |
| 76 | + }, |
| 77 | + ), |
| 78 | + ) |
| 79 | + |
| 80 | + |
| 81 | +def main(config: Config) -> None: |
| 82 | + if config.steps < 1: |
| 83 | + raise ValueError("Tiny RL needs steps >= 1") |
| 84 | + log_dir = Path(config.log_dir) |
| 85 | + reset_log_dir(log_dir, config.behavior_if_log_dir_exists) |
| 86 | + |
| 87 | + client = tinker.ServiceClient(api_key=os.getenv("TINKER_API_KEY", "tml-dummy-key"), base_url=config.base_url) |
| 88 | + trainer = client.create_lora_training_client( |
| 89 | + base_model=config.base_model, |
| 90 | + rank=config.rank, |
| 91 | + seed=config.seed, |
| 92 | + train_attn=True, |
| 93 | + train_mlp=True, |
| 94 | + # Qwen2.5-0.5B ties lm_head to embed_tokens; LoRA on the tied head trips a |
| 95 | + # PEFT warning and vLLM cannot load lm_head adapter weights at all. |
| 96 | + train_unembed=False, |
| 97 | + ) |
| 98 | + tokenizer = trainer.get_tokenizer() |
| 99 | + prompt_tokens = tokenizer.encode(config.prompt, add_special_tokens=False) |
| 100 | + prompt = types.ModelInput.from_ints(tokens=prompt_tokens) |
| 101 | + sampling_params = types.SamplingParams(max_tokens=config.max_tokens, temperature=config.temperature) |
| 102 | + |
| 103 | + mean_reward = 0.0 |
| 104 | + for step in range(1, config.steps + 1): |
| 105 | + sampler = trainer.save_weights_and_get_sampling_client() |
| 106 | + sequences = sampler.sample(prompt=prompt, num_samples=config.samples_per_prompt, sampling_params=sampling_params).result().sequences |
| 107 | + |
| 108 | + rewards = [] |
| 109 | + for sequence in sequences: |
| 110 | + tokens, logprobs = list(sequence.tokens), list(sequence.logprobs or []) |
| 111 | + if not tokens or len(tokens) != len(logprobs): |
| 112 | + raise RuntimeError(f"Sampler must return aligned tokens and logprobs, got {len(tokens)} tokens and {len(logprobs)} logprobs") |
| 113 | + rewards.append(1.0 if config.target in tokenizer.decode(tokens) else 0.0) |
| 114 | + |
| 115 | + # Group-centered advantages; when every reward ties, fall back to a uniform |
| 116 | + # positive advantage so the update still exercises a nonzero gradient. |
| 117 | + mean_reward = statistics.fmean(rewards) |
| 118 | + advantages = [reward - mean_reward for reward in rewards] |
| 119 | + if all(abs(advantage) < 1e-8 for advantage in advantages): |
| 120 | + advantages = [1.0] * len(rewards) |
| 121 | + |
| 122 | + datums = [ |
| 123 | + build_datum(prompt_tokens, list(sequence.tokens), list(sequence.logprobs or []), advantage) |
| 124 | + for sequence, advantage in zip(sequences, advantages) |
| 125 | + ] |
| 126 | + fwdbwd = trainer.forward_backward(datums, config.loss_fn).result() |
| 127 | + trainer.optim_step(types.AdamParams(learning_rate=config.learning_rate, grad_clip_norm=config.grad_clip_norm)).result() |
| 128 | + |
| 129 | + loss = float(fwdbwd.metrics.get("loss:mean", 0.0)) |
| 130 | + if not math.isfinite(loss): |
| 131 | + raise RuntimeError(f"Loss must be finite, got {loss!r}") |
| 132 | + write_metric(log_dir, {"phase": "train", "step": step, "loss": loss, "mean_reward": mean_reward, "num_datums": len(datums)}) |
| 133 | + print(f"[tiny-rl] step={step:02d}/{config.steps} loss={loss:.6f} mean_reward={mean_reward:.2f} datums={len(datums)}") |
| 134 | + |
| 135 | + final_state_path = trainer.save_state("tiny-rl-final").result().path |
| 136 | + write_metric(log_dir, {"phase": "final", "step": config.steps, "final_state_path": final_state_path, "mean_reward": mean_reward}) |
| 137 | + print(f"[tiny-rl] mean_reward={mean_reward:.2f}") |
| 138 | + print(f"final_state_path={final_state_path}") |
| 139 | + |
| 140 | + |
| 141 | +if __name__ == "__main__": |
| 142 | + chz.nested_entrypoint(main, allow_hyphens=True) |
0 commit comments