# KiT Model Structure: KlineDiT Sequence and AdaLN

> For readers who know Transformers: how KiT's KlineDiT arranges history and future into a single sequence, which conditions go through AdaLN, which are added…

Source: https://gaodong.ai/en/kit/3-train/01-model

---

# Model structure: KlineDiT {#模型结构-klinedit}

This section assumes you know what a Transformer's attention, residual connections, and LayerNorm are. After finishing this section, you'll be able to look at `kit_v1/model/dit.py` and state the shape and origin of every tensor in a single forward pass, so you won't get stuck reading the training code in the next section.

## One-sentence version {#一句话版本}

KiT is a DiT (Diffusion Transformer): it arranges the **clean history** and **noised future** into a single token sequence, processes it with a bidirectional-attention Transformer, and outputs a "velocity" only over the future segment.

## Input: one sequence, three segments {#输入-一条序列-三段}

Take the official KiT-L forecasting 1-hour bars as an example (`Lc=400`, `Lh=20`, `d_model=1024`):

```text
[ r1 r2 r3 r4 | x_1 … x_400 | z_1 … z_20 ]
  Registers 4    History (clean)    Future (noised)
```

**序列里的这一段……**

- **寄存器 r1…r4**：4 个可学习的向量。不对应任何 K 线，是给注意力一个“草稿纸”，存放全局信息。形状 [4, d]，每个样本共用。
- **历史 x_1…x_400**：干净的五个比例数。z 的前 Lc 个位置，就是标准化后的历史，从不加噪。in_proj 把 5 维线性投影到 d 维。
- **未来 z_1…z_20**：加噪的五个比例数。训练时是 (1-t)·x + t·ε，推理时从纯噪声开始。同样经过 in_proj。
- **每个 token 还要加上**：角色 + 日历。角色嵌入（0=历史，1=未来）；日历嵌入：一天里的时刻(16 维)、在交易时段的位置、星期、事件标记、月份、一年里的第几天，各自投影到 d 后相加。

The first few lines of the forward pass (`dit.py`):

```python
tok = (self.in_proj(z)                    # [B, L, 5]  -> [B, L, d]
       + self.role_emb(role_tok)          # 0=历史 1=未来
       + self.calendar(clock, sess, dow, event, month, yday))   # [B, L, d]
x = torch.cat([registers, tok], dim=1)    # [B, 4 + L, d]，L = Lc + Lh = 420
```

## Conditions go down two paths {#条件分两路走}

Beyond the K-lines, the model also knows many things: which market, which industry, which stock, what granularity, what time it is now, and what day of the week. The paper's design principle is:

- **Conditions identical across the whole window** (market, industry, stock, granularity, flow time t) → pooled into a single vector that modulates every layer via **AdaLN**
- **Conditions that differ per K-line** (time of day, day of week, holiday events…) → **added directly to that K-line's token**, preserving temporal alignment

The first path's computation:

```python
c_base = market_emb + sector_emb + inst_proj(inst_emb) + scale_emb   # [B, d]
h = silu(W1(t_emb(t) + c_base))                                      # SharedAdaLN
c_mod = W2(h)        # [B, 6d] → 每层的 shift1, scale1, gate1, shift2, scale2, gate2
```

The stock embedding table is low-rank: 8192 slots × 512 dimensions, then projected to 1024. Slot 0 means "unknown", so filling in `vocab_index: 0` also works (covered in the previous chapter).

One detail: **history tokens and future tokens receive different modulations**. The future computes `c_mod` with the real t, while history computes it again with t=0 (same set of weights). Because history is inherently in the "noise-free" state.

## Each layer: AdaLN + attention + SwiGLU {#每一层-adaln-注意力-swiglu}

```python
mod = where(role == 未来, c_mod_tgt, c_mod_ctx) + bias_i   # 按 token 角色选调制，再加每层自己的偏置
h = rmsnorm(x) * (1 + scale1) + shift1
x = x + gate1 * attention(h)          # 双向注意力，RoPE 位置编码，QK-Norm
h = rmsnorm(x) * (1 + scale2) + shift2
x = x + gate2 * swiglu(h)
```

Same "AdaLN-Zero" idea as the original DiT paper: `W2` and the output layer are both initialized to 0, so at the very start of training every layer is an identity mapping and the model outputs 0, making training more stable.

Attention **has no causal mask**; it only masks padded positions. So history can see the future's noised tokens, and the future can see all of history. This is fundamentally different from autoregressive models (generating bar by bar): the 20 bars are generated together, so there's no "one wrong bar drags the rest wrong". The paper lists this as an advantage over autoregressive models like Kronos.

## Output: take only the future segment {#输出-只取未来那段}

```python
x_tgt = x[:, 4 + Lc:, :]                          # [B, Lh, d]
h = rmsnorm(x_tgt) * (1 + scale_f) + shift_f      # 最后再调制一次
v_pred = out_proj(h)                              # [B, Lh, 5]：每根未来 K 线五个数的“速度”
```

## Three sizes {#三个尺寸}

| | KiT-S | KiT-M | KiT-L (open source) |
|---|---|---|---|
| Parameters | 31 million | 101 million | 284 million |
| Config file | `configs/dit_30m.yaml` | `configs/dit_100m.yaml` | `configs/dit_300m.yaml` |
| d_model | 512 | 768 | 1024 |
| Layers | 8 | 13 | 21 |
| Attention heads | 4 | 6 | 8 |
| FFN hidden dim | 1408 | 2048 | 2816 |

The numbers come from Table 3 in the paper's appendix. All three sizes were trained for 50,000 steps in the paper.

Verify KiT-L's parameter count yourself:

```bash
python -c "import torch;from kit_v1.infer import load_model_and_config as f;m,c=f('ckpt/step_market_284M.pt','tiny',0);print(sum(p.numel() for p in m.parameters()), c.model.n_layers, c.model.d_model)"
```

You should see:

```text
[info] loaded EMA weights (step=50000)
285789189 21 1024
```

285.8 million, about 2.1 million more than the 283.7M in the paper's table: the open-source weights' stock embedding table has 8192 slots (the config file says 4096), and the extra 4096 × 512 is exactly this number.

**小测验：** “这只股票是谁”和“这根 K 线是星期几”，分别通过什么进入模型？
- A. 都加到 token 上
- B. 股票身份走 AdaLN 调制每一层；星期几加到对应 K 线的 token 上
- C. 都走 AdaLN

答案：股票身份走 AdaLN 调制每一层；星期几加到对应 K 线的 token 上。整个窗口不变的条件走 AdaLN；随每根 K 线变化的条件直接加到 token 上，才能和那根 K 线对齐。

## Check yourself {#检查一下}

- [ ] I can write out the sequence length of a single forward pass for 1-hour bars: 4 + 400 + 20
- [ ] I know which conditions go through AdaLN and which are added to tokens
- [ ] I know why the 20 future K-lines are generated together without error accumulation

Next section: [how it learns](/kit/3-train/02-how-it-learns).
