# 04 – Clone-and-run verification (official decision-model repos, CPU only)

Every number below was copied from output I saw. Raw outputs: `verification\*_output.txt`. Scripts: `verification\*.py|ps1`.
Clone root: `./.copilot\session-state\14c48ac6-7170-4cd0-8c15-8482eb592b94\files\decision-models\repos` (shallow, `git clone --depth 1`).

## 0. Environment

| Item | Result (source: `01_env_and_repo_manifest_output.txt`) |
|---|---|
| Default `python` (miniconda base) | Python 3.14.6; **no torch**; `_ssl` DLL fails to load -> pip cannot reach PyPI (as warned) |
| `py` launcher | not installed |
| Env used for every torch run | `%LOCALAPPDATA%\miniconda3\envs\fb-local-test\python.exe` – Python 3.10.21, torch 2.9.1+cpu, transformers 4.49.0, numpy 1.26.4, OpenSSL 3.6.4, CUDA False. Pre-existing env; **nothing was installed** |
| Not installed in that env | gym, gymnasium, d4rl, minari, mujoco, mujoco_py, wandb, pyrallis, d3rlpy, tap, tensorflow |
| Pure-numpy script | ran with the base python 3.14 (numpy 2.5.2 present) |
| Local D4RL/Minari data | `~\.d4rl` and `~\.minari` do not exist; `decision-transformer\gym\data` holds only `download_d4rl_datasets.py` |

## 1. Repos (commit, license)

| Repo (clone dir) | Commit (HEAD, date) | License (file) |
|---|---|---|
| kzl/decision-transformer | `e2d82e68f330c00f763507b3b01d774740bee53f` (2022-02-07) | MIT (`LICENSE.md`) |
| jannerm/trajectory-transformer | `8834a6ed04ceeab8fdb9465e145c6e041c05d71b` (2022-10-06) | MIT (`LICENSE`) |
| jannerm/diffuser | `7ea422860cc0106e5ca5949d980f04b799d5462c` (2022-12-20) | MIT (`LICENSE`) |
| anuragajay/decision-diffuser (exists) | `01ce528c30b4733dc59aa6203e46ec165561158d` (2023-05-01) | **No LICENSE file found** (`code\README.md` has no "licen" match) |
| huggingface/transformers (NOT cloned; 3 raw files in `..\hf\`) | main @ `439bba079891ecd766900e8ce80ee961b94ef132` at fetch time | Apache-2.0 (`hf\LICENSE`, header "Apache License Version 2.0") |
| Farama-Foundation/D4RL | `89141a689b0353b0dac3da5cba60da4b1b16254d` (2024-11-18) | [Code Apache-2.0; datasets CC BY 4.0 unless otherwise noted](https://github.com/Farama-Foundation/D4RL/blob/89141a689b0353b0dac3da5cba60da4b1b16254d/README.md#licenses) |
| Farama-Foundation/Minari | `e23025e865478452ee0153250c694091ecd08682` (2026-11-13) | Farama custom text embedding MIT + Apache-2.0 (`LICENSE`) |
| tinkoff-ai/CORL | `6afec90484bbf47dee05fdf525e26a3ebe028e9b` (2023-08-01) | Apache-2.0 (`LICENSE`) |
| takuseno/d3rlpy | `38c34b6f99fde82875e2ad81d1ba1f7a7da34137` (2025-09-11) | MIT (`LICENSE`) |
| young-geng/CQL | `21efac46faadef7d24ecf03a8091ab9cc3a613fd` (2022-10-14) | MIT (`LICENSE`) |
| google-research/robotics_transformer | `4569641b8111f3f402c32d8e24becd2a6e952ecc` (2023-02-10) | Apache-2.0 (`LICENSE`) |

Notes: the robotics_transformer repo ships ~4 GB of checkpoints (`trained_checkpoints\`); I deleted that working-tree folder after cloning (git shows it as deleted; the `.git` pack still holds it). HF files: `hf\modeling_decision_transformer.py` (29,255 B, sha256 `6F60582B…282D`), `hf\configuration_decision_transformer.py` (3,317 B). Numbers in §3 come from the **installed transformers 4.49.0**, not from main; I confirmed that file also passes `position_ids=torch.zeros(...)` (line 930) and has `wpe` (lines 498/609-610).

## 2. Official Decision Transformer – code reading (kzl/decision-transformer, `gym\`)

Key files: `gym\decision_transformer\models\decision_transformer.py`, `gym\decision_transformer\models\trajectory_gpt2.py`, `gym\decision_transformer\training\seq_trainer.py`, `trainer.py`, `gym\experiment.py`, `gym\decision_transformer\evaluation\evaluate_episodes.py`, `gym\data\download_d4rl_datasets.py`; Atari variant `atari\mingpt\model_atari.py`.

**Modules (`decision_transformer.py`)** – `transformers.GPT2Config(vocab_size=1, n_embd=hidden_size, **kwargs)` + repo's own `GPT2Model` whose only change is that positional embeddings are removed (`trajectory_gpt2.py:521` `wpe` commented, `:680-681` `hidden_states = inputs_embeds  # + position_embeds`). Heads/embeds (lines 40-53): `embed_timestep = nn.Embedding(max_ep_len, H)`, `embed_return = Linear(1,H)`, `embed_state = Linear(state_dim,H)`, `embed_action = Linear(act_dim,H)`, `embed_ln = LayerNorm(H)`, `predict_state = Linear(H,state_dim)`, `predict_action = Sequential(Linear(H,act_dim), Tanh)`, `predict_return = Linear(H,1)`.

**Forward, shape by shape (B=batch, K=seq_length, H=hidden)**
1. inputs: `states [B,K,state_dim]`, `actions [B,K,act_dim]`, `returns_to_go [B,K,1]`, `timesteps [B,K]` (long), `attention_mask [B,K]`.
2. each modality embedded by its own `Linear` -> `[B,K,H]`; the **same** `embed_timestep(timesteps)` `[B,K,H]` is *added to each of R, s, a* (acts as positional embedding).
3. `torch.stack((R,s,a), dim=1).permute(0,2,1,3).reshape(B,3K,H)` -> interleaved **(R_1, s_1, a_1, R_2, s_2, a_2, …)**; then `embed_ln` (decision_transformer.py:75-79). Attention mask is stacked the same way -> `[B,3K]`.
4. GPT-2 stack (causal) -> `[B,3K,H]`; reshape `[B,K,3,H]` -> permute `[B,3,K,H]` so `x[:,0]`=R tokens, `x[:,1]`=s tokens, `x[:,2]`=a tokens.
5. Readout (lines 97-99): `action_preds = predict_action(x[:,1])` (**action from the state token s_t**, shape `[B,K,act_dim]`); `return_preds = predict_return(x[:,2])` and `state_preds = predict_state(x[:,2])` (next return / next state from the action token; unused by the paper's loss).
6. `get_action` left-pads to `max_length` K with zeros, mask 0, and returns `action_preds[0,-1]`.

**Data/loss (`experiment.py`, `seq_trainer.py`)**: batch sampled by trajectory ∝ length; window `[si:si+K]`; `rtg = discount_cumsum(rewards[si:], gamma=1.)[:K+1]` (l.141, appends a 0 if too short, right after l.141), divided by `scale=1000` (l.152); pad: states 0 (then normalised), actions **-10**, rtg 0, timesteps 0, mask 0 (around l.147-155). Trainer passes `rtg[:,:-1]` (seq_trainer.py:14); loss = `mean((action_pred - action_target)**2)` over masked-in tokens only (seq_trainer.py:18-19, 254 loss_fn), `AdamW(lr=1e-4, wd=1e-4)`, linear warm-up 10,000 steps, `clip_grad_norm_(0.25)`. Defaults: embed 128, 3 layers, 1 head, K=20, dropout 0.1, batch 64, `n_inner=4*embed`, relu, `n_positions=1024`; Hopper: `max_ep_len=1000`, targets 3600/1800, scale 1000, obs 11, act 3. Inference (`evaluate_episode_rtg`): `R_{t+1} = R_t - r_t/scale` and `timesteps` appended with t+1.

### 2.1 Official vs HF (verified by running)
`03_official_vs_hf_and_causality_output.txt`: the official `DecisionTransformer` could be imported only after two in-script compat shims (no repo edit): `transformers.file_utils.add_code_sample_docstrings` -> no-op decorator, and `GPT2Config.n_ctx = 1024` (without them: `TypeError ... tokenizer_class` then `AttributeError 'GPT2Config' object has no attribute 'n_ctx'`).

| Model (Hopper 11/3, H128, 3L, 1H, n_inner 512) | Params |
|---|---|
| Official `DecisionTransformer` | **727,695** (transformer 595,200 = wte 128 + blocks 594,816 + ln_f 256; embed_timestep 128,000; embed_return 256; embed_state 1,536; embed_action 512; embed_ln 256; predict_state 1,419; predict_action 387; predict_return 129) |
| HF `DecisionTransformerModel` | **858,767** |
| Difference | **131,072** = HF's `wpe` 1024×128 |

HF passes `position_ids=zeros`, i.e. it adds the single vector `wpe[0]` to all tokens (a learned constant bias), whereas the official code adds nothing. After copying official weights into HF (matching names, `encoder.`↔`transformer.`) and zeroing `wpe`, `max|diff|` on action/state/return preds = **0.0 / 0.0 / 0.0** (eval mode, B=4, K=20).

## 3. HF `DecisionTransformerModel` on CPU (`02_hf_dt_inspect.py`, installed transformers 4.49.0)

**Config defaults** (`DecisionTransformerConfig()`): state_dim 17, act_dim 4, hidden 128, max_ep_len 4096, n_layer 3, n_head 1, n_inner None (->512), relu, n_positions 1024, dropouts 0.1, action_tanh True.
**Official Hopper config**: state_dim 11, act_dim 3, hidden 128, max_ep_len 1000, 3 layers, 1 head, n_inner 512, n_positions 1024.

| Module | Defaults (17/4, ep 4096) | Hopper (11/3, ep 1000) |
|---|---|---|
| **TOTAL** | **1,256,854** | **858,767** |
| encoder (GPT2 stack incl. wte/wpe/ln_f) | 726,272 | 726,272 |
| – wte (1×128) / wpe (1024×128) | 128 / 131,072 | 128 / 131,072 |
| – 3 blocks (each 198,272: ln 256, attn 66,048, ln 256, mlp 131,712) | 594,816 | 594,816 |
| – ln_f | 256 | 256 |
| embed_timestep | 524,288 (4096×128) | 128,000 (1000×128) |
| embed_return / embed_state / embed_action | 256 / 2,304 / 640 | 256 / 1,536 / 512 |
| embed_ln | 256 | 256 |
| predict_state / predict_action / predict_return | 2,193 / 516 / 129 | 1,419 / 387 / 129 |

**Forward pass, random tensors** (defaults B=2,K=20; Hopper B=64,K=20; sample 0 left-padded with 5 masked steps):
inputs `states (B,20,sd)`, `actions (B,20,ad)`, `returns_to_go (B,20,1)`, `timesteps (B,20)` int64, `attention_mask (B,20)` int64. Hook-measured shapes (Hopper, B=64): `embed_state/action/return/timestep -> (64,20,128)`; `embed_ln -> (64,60,128)` (3K=60); `encoder.drop`, `encoder.h[0]`, `encoder -> (64,60,128)`; `predict_return (64,20,1)`, `predict_state (64,20,11)`, `predict_action (64,20,3)`. Outputs: `state_preds (64,20,11)`, `action_preds (64,20,3)`, `return_preds (64,20,1)`, `last_hidden_state (64,60,128)`. Defaults gave the same pattern with B=2 and dims 17/4 (`action_preds (2,20,4)`). Random-init tanh output range B=64: min -0.6243, max 0.6356.

**Causality/readout test** (random-init, eval, K=20, t=7; final run in `03_…_output.txt`): perturbing a_7 changes `action_pred[7]` by **0.0** (and t=6 by 0.0) but `action_pred[8]` by 8.97e-4 and the *state-pred* (read from the a-token) at t=7 by 0.558; perturbing s_7 changes `action_pred[7]` by 0.151 and t=6 by 0.0; perturbing R_7 changes `action_pred[7]` by 3.1e-3 (small because untrained weights are tiny); perturbing all tokens t>=8 changes `action_pred[:, :8]` by **0.0**. => action at t depends on R_≤t, s_≤t, a_<t, confirming "action head reads the s_t token".

## 4. CORL Decision Transformer (`algorithms\offline\dt.py`) – `05_corl_dt_check.py`
The module imports d4rl/gym/pyrallis/wandb (missing), so I extracted `TransformerBlock` and `DecisionTransformer` via `ast` and ran them (random tensors). Differences from the original: native `nn.MultiheadAttention` (pre-LN), GELU, dropout on embeddings, `return_emb(returns_to_go.unsqueeze(-1))` takes `[B,K]`, `timestep_emb` has `episode_len+seq_len` rows, readout `action_head(out[:, 1::3])`, masked MSE `(loss*mask).mean()` (dt.py:476-478), AdamW lr 1e-4 wd 1e-4, warm-up 10k, clip 0.25, `reward_scale=0.001`, `seq_len=20`.
Hopper dims (11/3, H128, 3L, 1H): **728,579 params** (timestep_emb 130,560; blocks 594,816 = 198,272 each; attention 66,048; mlp 131,712; emb_norm 256; out_norm 256; action_head 387). Causal-mask buffer `(60,60)`. Shapes: emb_norm `(4,60,128)`, output `(4,20,3)`. Causality: perturb a_7 -> `pred[7]` diff 0.0; perturb s_7 -> 0.374. One random-data train step: masked-MSE loss 0.383069, grad-norm (pre-clip) 1.468703 (mechanics only, not performance).

## 5. Trajectory Transformer – `06_trajectory_transformer_check.py`
Files: `trajectory\models\transformers.py` (GPT, `offset_tokens`, per-dimension `EinLinear` head in `models\ein.py`), `trajectory\datasets\sequence.py` (joined = obs+act+reward+value, discounted value with 0.99), `trajectory\utils\discretization.py` (`QuantileDiscretizer`), `config\offline.py` (N=100, discount 0.99, n_layer 4, n_head 4, n_embd 32 (×n_head=128 in `scripts\train.py:63`), batch 256, lr 6e-4, action_weight 5, subsampled seq 10), `scripts\train.py:50` block_size = 10×transition_dim − 1.
Run (Hopper dims): transition_dim 16, block_size 159, vocab 100 -> **1,225,472 params** (tok_emb 204,928 [1601×128]; blocks 793,088; ln_f 256; head 206,848 [16×101×128]; pos_emb (1,159,128) as a parameter). Random tokens `(2,159)` -> logits `(2,159,101)`; loss on random tokens 8.4237 (weighted ×5 on action dims, so not comparable to ln(101)=4.6151). Discretizer demo (N=4, 12 toy points): thresholds `[0.1 0.4 0.7 1. 9.]`, indices `[0 0 0 1 1 1 2 2 2 3 3 3]`, reconstruction `[0.25 … 0.55 … 0.85 … 5.]`. (Needed `PYTHONIOENCODING=utf-8` for a ✓ print; `trajectory.utils` stubbed because `tap` is missing.)

## 6. Diffuser – `07_diffuser_check.py`
Files: `diffuser\models\diffusion.py` (`GaussianDiffusion`, `p_losses`, `apply_conditioning`), `models\temporal.py` (`TemporalUnet`), `config\locomotion.py` (horizon 32, n_diffusion_steps 20, dim_mults (1,2,4,8), predict_epsilon False, action_weight 10, l2 loss, batch 32, lr 2e-4, ema 0.995).
Run (Hopper dims, package stubbed because d4rl/gym missing): channels `[(14,32),(32,64),(64,128),(128,256)]`, **3,956,302 params**; `x (4,32,14)`, `cond[0] (4,11)`, `t (4,)` -> output `(4,32,14)`; `p_losses` on random data 1.2015947; loss_weights `(32,14)`, first-step action weights `[10,10,10]`.

## 7. Decision Diffuser (read only; no run)
`code\diffuser\models\diffusion.py`: `GaussianDiffusion` with `returns_condition` + classifier-free guidance (`eps = eps_uncond + w*(eps_cond − eps_uncond)`, l.126-130, `condition_guidance_w=0.1` default); `GaussianInvDynDiffusion` (l.291+) uses an inverse-dynamics model (`ARInvModel`) that predicts `a_t` from the concatenation `(s_t, s_{t+1})` (l.507-517); that the diffusion part models states only is the paper's claim and was not checked in code here; training loss `0.5*(diffuse_loss + inv_loss)` (l.536). Folders: `code\{analysis,config,diffuser,scripts}`, `materials\` (web page). No LICENSE.

## 8. Offline-RL pieces
- **IQL (CORL `iql.py`)** – `asymmetric_l2_loss` (l.233-234), `_update_v` (l.408), `_update_q` target `r + (1−done)·γ·V(s')` (inside `_update_q`, l.422+), `_update_policy` weights `exp(β·adv)` clamped at 100 (l.442+). Defaults: γ 0.99, `iql_tau` 0.7, β 3.0. Run `08_corl_iql_expectile.py` (function extracted by ast): τ=0.7 loss(u=+2)=2.8000, loss(u=−2)=1.2000; τ=0.9 → 3.6000/0.4000; expectile of Q=[0,1,2,10] (mean 3.250) is V=3.250 (τ .5), **4.935 (τ .7)**, 7.750 (τ .9); target with r=1,V'=5: **5.95**; exp_adv at β=3: adv −1 → 0.0498, 0 → 1.0, +1 → 20.0855, ≥+2 → 100.0 (clamp).
- **TD3+BC (`td3_bc.py`)** read: target `r + not_done·γ·min(Q1',Q2')` (l.325-326); actor loss `−λ·Q.mean() + MSE(π, a)` with `λ = α/|Q|.mean().detach()`, α=2.5 (l.347-349), policy_noise 0.2, clip 0.5, policy_freq 2.
- **CQL (`cql.py`)** read: `cql_temp` 1.0, `cql_alpha` 10.0 in config (5.0 as class default), `cql_n_actions` 10, importance sampling True, `logsumexp(cat_q/temp)*temp` (l.666), lagrange option. The young-geng/CQL repo was cloned but not inspected or run.
- **d3rlpy** is real/official (takuseno): `d3rlpy\algos\transformer\decision_transformer.py` has `DecisionTransformer` and `DiscreteDecisionTransformer`; not run (not installed).
- **Datasets**: D4RL `d4rl\offline_env.py:get_dataset` returns keys `observations, actions, rewards, terminals` (+ `timeouts`, `next_observations` when present; terminals reshaped to `(N,)`); the DT repo's `download_d4rl_datasets.py` converts those flat arrays into a list of per-trajectory dicts and pickles `data/{env}-{type}-v2.pkl` (splitting on `terminals` or `timeouts`, or episode_step==999). Minari: `EpisodeData` fields `id, observations, actions, rewards, terminations, truncations, infos` (`minari\dataset\episode_data.py:8-17`); `StepData` TypedDict `observation, action, reward, terminated, truncated, info`; API `MinariDataset.sample_episodes / iterate_episodes / __getitem__ / recover_environment` (storage backends `_storages\hdf5_storage.py`, `arrow_storage.py`). D4RL README states datasets moved to Minari.

## 9. RT-1 (`robotics_transformer`, inspect only)
`transformer_network.py` (`TransformerNetwork`, defaults `vocab_size=256, token_embedding_size=512, num_layers=1, layer_size=4096, num_heads=8, time_sequence_length=1, dropout 0.1, use_token_learner=True`), `transformer.py` (`_TransformerLayer`, `Transformer`), `tokenizers\action_tokenizer.py` (each action dim discretised into `vocab_size` buckets), `tokenizers\image_tokenizer.py`, `tokenizers\token_learner.py`, `film_efficientnet\*` (FiLM-conditioned EfficientNet), `sequence_agent.py`. Per time step the token sequence is `[context-image tokens…, action tokens…]` with a causal look-ahead mask (l.170-212 `_default_attention_mask`, band_part). TensorFlow not installed -> nothing executed; the exact tokens-per-image / tokens-per-action counts come from runtime specs and were **not** verified here.

## 10. Numpy toy (`04_numpy_rtg_bellman.py`, base python)
- Rewards `[1,0,2,0,3]`, γ=1 -> RTG `[6,5,5,3,3]`; R_0 = Σr = 6; R_t = r_t + R_{t+1} holds; γ=0.9 gives `[4.5883 3.987 4.43 2.7 3.]`. Window si=1, K=3 -> `rtg[si:][:K+1] = [5,5,3,3]` (model gets first 3); scaled by 10 -> `[0.5,0.5,0.3,0.3]`; si=3 -> only `[3,3]` available. Inference update `R_{t+1}=R_t−r_t` from target 6 reproduces `[6,5,5,3,3]`.
- 3-state chain (γ=0.9; s1→terminal gives reward 1): Q after backup 1 `Q(s1,adv)=1`; backup 2 `Q(s0,adv)=0.9, Q(s1,stay)=0.9`; backup 3 `Q(s0,stay)=0.81`; converged (backup 4 unchanged); greedy `[1 1 0]`, V* `[0.9 1. 0.]`. TD target example `y = 0 + 0.9·1.0 = 0.9`. TD(0)-style backups on the fixed trajectory converge to the RTG `[6,5,5,3,3]` (MC = TD for γ=1, deterministic single trajectory).

## 11. What could NOT be run / verified (and why)
| Item | Reason |
|---|---|
| D4RL/Minari data statistics in this model-inspection run | No dataset was loaded in this run. The separate D4RL follow-up found cached v2 HDF5 files and [recounted them](./verification/10_d4rl_counts_output.json) with h5py; that is file inspection, not Gym/MuJoCo training, evaluation or a Minari recount. |
| Official DT training / Hopper evaluation (`experiment.py`) | needs gym `Hopper-v3` (mujoco_py), wandb, dataset pickle; also full training out of scope |
| HF DT pretrained checkpoints / HF Hopper rollout | no network-based model download attempted; not needed |
| Trajectory-Transformer beam-search planning, real discretizer on D4RL data | needs d4rl dataset |
| Diffuser/Decision Diffuser sampling, value guide, inverse-dynamics run | no data/env; Decision Diffuser not instantiated (code read only; code is large and depends on gym/d4rl) |
| CORL IQL/CQL/TD3+BC full training | no d4rl; only the loss function of IQL was run |
| d3rlpy, young-geng/CQL | d3rlpy not installed; CQL repo not inspected |
| RT-1 | TensorFlow not installed; ~4 GB checkpoints deleted; code read only |
| Exact `transformers main` numbers | local runs use installed 4.49.0; main raw files only inspected |

## 12. Files produced
`verification\01_env_and_repo_manifest.ps1` (+`_output.txt`), `02_hf_dt_inspect.py`, `03_official_vs_hf_and_causality.py`, `04_numpy_rtg_bellman.py`, `05_corl_dt_check.py`, `06_trajectory_transformer_check.py`, `07_diffuser_check.py`, `08_corl_iql_expectile.py` – each with `*_output.txt`. Caveat: causal-test deltas depend on random seeds (seed 0 per script, but weights/tensors differ between runs because script 03 loaded different weights after the shim); quoted values are from the final saved output.

