# How KiT Is Trained: Flow Matching Objective Explained

> Using a 

Source: https://gaodong.ai/en/kit/3-train/02-how-it-learns

---

# How it learns {#它是怎么学会的}

After finishing this section, you will be able to explain in three sentences what each step of KiT training does, and in the next section you will be able to understand the dozen or so core lines of the training script.

## First, think of a game {#先想一个游戏}

Take a clear photo and sprinkle a layer of snowflake noise on it. With a light sprinkle, the original is still visible; with a heavy one, only snowflakes remain.

Have a person practice: give them a photo covered in snowflakes, tell them "how much was sprinkled," and ask them to point out "where the snowflakes are and which direction to wipe." With enough practice, they can start from a screen full of snowflakes and gradually wipe out a decent photo.

KiT's training is exactly this game, with the photo replaced by "the next 20 K-lines."

## One step of training {#训练的一步}

Randomly cut a segment from the data: the first 400 bars are history, and the following 20 bars are the real future (using 1-hour bars as an example).

Written as formulas, these are the three lines in Sections 3.1 and 3.5 of the paper:

- Mixing: z = (1 − t)·x + t·ε, where x is the real future and ε is noise
- The correct answer (the "velocity"): v = ε − x
- Loss: the mean squared error between the model output and v, averaged only over the future Lh bars

### Why predict the "velocity" instead of directly predicting the answer {#为什么预测-速度-而不是直接预测答案}

z is a straight line between x and ε: as t goes from 0 to 1, z moves uniformly from data to noise. The direction of this line is the same everywhere, namely ε − x. Once the model has learned "where this line points, at any position and any t," at inference time it can walk backward along it from noise back to data.

Because the line is straight, the steps can be large when walking backward: a 32-step Euler method is enough. For comparison, the diffusion baselines in the paper's appendix: TimeGrad needs 100 diffusion steps per future K-line generated (and generates them one by one), and Diffusion-TS samples with 200 steps.

### Tensor shapes {#张量形状}

Taking 1-hour bars and a batch of B as an example:

| Tensor | Shape | Description |
|---|---|---|
| `x_ctx` | [B, 400, 5] | History, five values after standardization |
| `x_tgt` | [B, 20, 5] | The real future, standardized the same way |
| `t` | [B] | One flow time per sample |
| `eps` | [B, 20, 5] | Standard normal noise |
| Model input | [B, 420, 5] | History and the noised future concatenated (the model adds 4 registers internally) |
| Model output `v` | [B, 20, 5] | Only the future segment |

### Inputs are standardized first: MAD + tanh soft clipping {#输入先标准化-mad-tanh-软截断}

The five ratio values differ greatly in magnitude and have extreme values (limit-up moves, flash crashes, volume spikes). Before entering the model, each (market, granularity, feature) is scaled by a fixed scale s, then soft-clipped (`kit_v1/data/normalize.py`):

- s = 1.4826 × median absolute deviation (MAD), computed only on training-period data and stored in `stats.json`
- y = 6 · tanh(x / s / 6)

tanh leaves values in the normal range almost unchanged, while extreme values are smoothly compressed to within ±6 instead of being cut off directly. The paper's phrasing is "training is stable, yet outliers are not lost." After prediction, atanh reverses the transformation.

At inference it's the reverse: starting from t = 1 (pure noise), each step walks back a little along the direction the model gives, and reaching t = 0 gives the prediction. This is the slider you drag on the course homepage.

## How t is sampled {#t-怎么抽}

t is not sampled uniformly. The paper uses logit-normal: first draw a number from the standard normal distribution, then pass it through a sigmoid. This way t mostly falls near 0.5, so training effort is spent mainly on the middle difficulty of "half data, half noise"; the cases of all noise or almost no noise carry little information for learning.

In code it's just one line: `t = torch.sigmoid(torch.randn(B))`.

## Three more "deliberately dropping things" tricks {#还有三个-故意丢东西-的技巧}

During training, some conditions are randomly dropped (Section 3.5 of the paper):

1. Replace the stock and industry identities with "unknown"
2. Clear all identities: market, industry, stock, granularity
3. Zero out the entire history

This way the model simultaneously learns how to predict "with identity / without identity" and "with history / without history." The `--cfg-w` and `--hist-cfg-w` at inference time amplify the effect of a certain condition by taking the difference between these predictions (classifier-free guidance, CFG). As mentioned in the previous chapter, they are off by default.

## The paper's training configuration {#论文的训练配置}

| Item | Value |
|---|---|
| Optimizer | AdamW, β1 = 0.9, β2 = 0.95, weight decay 0.1 |
| Learning rate | Peak 1e-4, with 1000 warmup steps |
| Precision | BF16 |
| Global batch | 4096 |
| Gradient clipping | 1.0 |
| Parameter EMA | Decay 0.9999 (the open-source weights are the EMA copy) |
| Hardware | 128 NVIDIA H200 GPUs |
| Stopping criterion | Average validation loss per (market, granularity) no longer decreasing |
| Model size | KiT-S 31 million, KiT-M 101 million, KiT-L 284 million parameters |

128 H200 GPUs — we don't have those. In the next section, we'll run the same training objective on a single 16GB GPU with 100 stocks and see what happens.

::: tip The official training code has not been released yet
The `kit_v1/train/README.md` in the official repository says "TBD. Training code will be released here." The next section uses a minimal script written for this course, relying only on the model and data code already made public in the repository, with the training objective written according to the paper.
:::

**小测验：** 训练时，损失算在哪一段上？
- A. 历史和未来都算
- B. 只算未来那 Lh 根
- C. 只算历史那 Lc 根

答案：只算未来那 Lh 根。历史是干净的输入，只提供上下文；被加噪、要模型去还原的只有未来那段，损失也只算那段（论文式 8）。

## Check {#检查一下}

- [ ] I can state five things about one training step
- [ ] I know the correct answer for "velocity" is noise − truth
- [ ] I know why t is mostly sampled around 0.5

Next section: [Train a small KiT from scratch](/kit/3-train/03-train-small).
