Studying how open-weight and frontier models fail on cultural knowledge in cyber and social-engineering attacks, and teaching them to secure critical infrastructure.
Part 1 covers the JAX foundation, written from scratch with every number derived: Qwen3-0.6B, a tokenizer, a growing KV cache and cached generation.
In middle school I was hooked on computer hacking. I wanted to go down to assembly level and see how an exploit can be reversed, and Stuxnet, a zero-day-powered worm, is the example that stayed with me. Now that I have matured, I want to use AI to research exactly this, and to teach models how to secure computer systems.
Frontier models keep expanding their cybersecurity capabilities, and they have shown they can find real, critical vulnerabilities in systems. So how far can open-weight and frontier models be pushed, or tricked, into committing fraud and social-engineering attacks?
Models lack cultural knowledge, and attackers can exploit that gap to trick them into helping launch cyber and social-engineering attacks. If the hypothesis holds, it becomes one of the biggest questions for RL, agentic research and model security in general.
The Open Post-Training System is how I test it: an Agent Swarm RL infrastructure on JAX and TPUs, built for long-horizon work. It finds loopholes in models and systems, then post-trains models to secure critical infrastructure. It is not only infrastructure. The infrastructure is the instrument for the research.
This also comes from my earlier work in computer security. In my early career I helped save many people from scams and similar attacks. Scammers prey on people’s lack of awareness about technology, and people in India often know this best. If you have ideas around it, I would like to hear them.
I report on this publicly as I build it. I have only just started, and there is more to be revealed over the next few months.
The first target is Qwen3-0.6B, a decoder-only Transformer. Before touching code I reconstructed it from its config and checkpoint and accounted for parameters, FLOPs and memory per component, then reconciled the total with the model card. The flow is: token ids, embedding, 28 Transformer blocks, final RMSNorm, LM head, vocabulary logits. The LM head reuses the embedding matrix, so it adds no parameters, but it still costs compute.
Parameter budget. The norms add 65,536 parameters (0.125 MiB), too small to draw.
| Component | Parameters | BF16 memory |
|---|---|---|
| Token embedding (tied LM head) | 155,582,464 | 296.75 MiB |
| Q, K, V, O projections | 176,160,768 | 336 MiB |
| Gate, up, down projections | 264,241,152 | 504 MiB |
| All RMSNorms (incl. QK-Norm) | 65,536 | 0.125 MiB |
| Total | 596,049,920 | 1,136.875 MiB |
Notation: is the vocabulary, the hidden size, the batch, the sequence length, and BF16 stores 2 bytes per value.
A pytree is a nested structure of dictionaries whose leaves are arrays, so jit, grad and tree_map understand it natively, and the same shape will later carry gradients and optimizer state. The safetensors file is flat, with 28 separate tensors per weight type. I rename them and stack each type along a new leading axis, so one array holds all 28 layers. That layout is what lets jax.lax.scan compile the layer body once instead of unrolling 28 copies.
layers = {name: jnp.stack([w[f"model.layers.{i}.{ckpt}.weight"] for i in range(28)], axis=0)
for name, ckpt in LAYER_WEIGHT_NAMES.items()} # each leaf: [28, ...]
params = {"embed_tokens": w["model.embed_tokens.weight"], "layers": layers, "final_norm": w["model.norm.weight"]}
layer_i = jax.tree_util.tree_map(lambda w: w[i], params["layers"]) # one layer’s weightsTwo choices matter. The forward pass is wrapped in jax.jit once, with params passed as an argument: if it were captured, JAX would bake roughly 1.2 GB of weights into the compiled program as constants, making compilation slow and heavy. And rope_theta is a fixed number, so it is static. The loader returns model(input_ids, key_cache, value_cache, cache_position), so generation code never touches the weights. The 0.6B checkpoint has no separate lm_head.weight: the logits come from the transposed embedding.
No transformers and no tokenizers: just tokenizer.json, tokenizer_config.json and my own implementation, plus regex (Python’s re lacks Unicode classes like \p{L}) and jinja2 for the chat template. Tokenizer boundaries decide loss masks, stop conditions and log-probabilities in post-training, so I want to know exactly what it does. It must be lossless, deterministic, and aligned with the embedding rows the model was trained with.
Ids 0 to 151,642 are ordinary BPE tokens, and 151,643 to 151,668 are added tokens such as <|im_start|> and <think>. The end-of-sequence token is <|im_end|> (151645) and the padding token is <|endoftext|> (151643). There is no beginning-of-sequence token. The last 267 embedding rows exist for hardware-friendly shapes and are never produced, so when sampling they should be masked out.
Decoding walks the pipeline backwards and buffers bytes across consecutive ordinary tokens, so a character split between tokens (an emoji is four bytes) comes out whole. skip_special_tokens drops the 14 special tokens but keeps added tokens such as <think>. One thing to watch: user text containing <|im_end|> becomes the real control token, which is a prompt-injection surface in agent loops.
The chat format is rendered from the Jinja template in the config. With the generation prompt and thinking switched off, one user message becomes:
<|im_start|>user What is reinforcement learning?<|im_end|> <|im_start|>assistant <think> </think>
For batches, rows are encoded, optionally truncated, and padded with <|endoftext|> to the longest row, with an attention mask (1 for real tokens, 0 for padding). The padding side is a parameter, because batched generation and training usually want different sides.
Every layer runs the same operations on its own slice of the pytree. Yellow squares run once, blue squares run in every layer, and the coral square is where the KV cache is written.
RMSNorm normalizes each token’s vector independently. Unlike LayerNorm there is no mean subtraction and no bias, so the only learned parameter is the per-channel scale . The mean of squares is computed in FP32, the result is cast back to the input dtype, and only then multiplied by .
RoPE rotates pairs of dimensions in each query and key head. With head size there are 64 pairs, and I use the split-half pairing: dimension is paired with .
Qwen3 uses Grouped-Query Attention: 16 query heads share 8 key-value heads, so each KV head serves two query heads. I never copy K or V. The query heads are reshaped into groups, and the single KV head broadcasts across its group inside the matrix multiply.
The feed-forward block is a gated MLP called SwiGLU: three matrix multiplies, with SiLU applied to the gate branch only and the two branches multiplied elementwise. Each decoder layer then has two residual connections, and only the branch inputs are normalized; the residual stream itself stays raw.
After the last block, the final RMSNorm feeds the LM head, which multiplies by the transposed embedding. Weight tying removes duplicate parameters, not the compute.
| Component | Forward FLOPs (× BT) |
|---|---|
| Q, K, V, O projections | 352,321,536 |
| All RMSNorms | 577,536 |
| RoPE | 258,048 |
| Gate, up, down projections | 528,482,304 |
| SiLU and gating | 258,048 |
| Residual additions | 57,344 |
| LM head | 311,164,928 |
| Total, linear in T | 1,193,119,744 |
| Attention scores and weighted values | 229,376 × T (so 229,376 BT² overall) |
Without a cache, every generated token recomputes the whole sequence. Past tokens’ keys and values never change, so we store them: keys after RoPE, values as they are, shaped [28, B, capacity, 8, 128]. We track capacity (allocated) separately from cache_size (valid), and double the capacity whenever it is full, instead of fixing a maximum length that would be arbitrary and wasteful.
Cache slots. After prefill only the first n are valid; padding slots are stale and masked, then overwritten one decode step at a time.
Because the cache has unused slots, the causal mask is built from absolute positions rather than a lower-triangular T × T matrix. A slot that has not been written yet sits at a position greater than every query, so it is always masked. That is why the model receives the full-capacity buffers and array shapes stay fixed between growth events.
Still open: attention runs over the capacity, not the valid length, so masked slots are still computed (up to about twice the necessary score cost); and the functional updates may copy the buffers each step, which buffer donation or a scan-carry design could fix. I will decide from a profile, not from guessing.
Every model call is wrapped by the same three steps, and generation has two phases. Prefill runs the prompt through once. Decode feeds one token per step at position cache_size. The prompt is right-padded to a multiple of 64 so the prefill step recompiles only when it crosses a bucket.
cache.ensure_capacity(T) # double the buffers if needed logits, k, v = model(ids, cache.key_cache, cache.value_cache, cache.cache_size) cache.set_cache(k, v, T) # store buffers, advance cache_size token = int(jnp.argmax(logits[0, n - 1])) # prefill: last REAL position; decode: index 0
We pass the full-capacity buffers to the model, not the filled-only view, because the layers write into the free slots. We stop on <|im_end|> or <|endoftext|> before appending, so the stop token never reaches the output, and we skip the forward pass after the last token we will emit. Text is streamed by decoding the whole generated list and printing only the new suffix, holding back a trailing � until the rest of a multi-byte character arrives. A worked example with a 100-token prompt:
| Step | Tokens fed | cache_position | Capacity check | cache_size after |
|---|---|---|---|---|
| Prefill | 128 (100 + 28 pads) | 0 | 0 + 128 ≤ 128 | 100 |
| Decode 1 | 1 | 100 | 101 ≤ 128 | 101 |
| Decode 28 | 1 | 127 | 128 ≤ 128 | 128 |
| Decode 29 | 1 | 128 | 129 > 128, double to 256 | 129 |
Compilation, by call: prefill compiles once per padded-length bucket, decode compiles once per cache capacity, and cache_position is a runtime value, so it never triggers a recompile on its own.
Wiring the cache end to end surfaced six real bugs. Most were silent: JAX happily returns wrong arrays and drops out-of-range writes without an error.
What went wrongA typo wrote the value update into the key-cache variable.
FixEach cache is written from its own tensor.
What went wrongThe value tensor was reshaped for the matmul, then returned in place of the cache.
FixA separate attention-only variable; the real cache is returned.
What went wrongThe layer call skipped the cache arguments, so rope_theta landed in a cache slot.
FixPass caches and cache_position end to end through the scan.
What went wrongThe loop fed the whole growing sequence every step and added its length to the cache.
FixPrefill once, then one token per step at cache_size.
What went wrongThe filled-only view has zero slots at the start, so there was nowhere to write.
FixPass the full-capacity buffers; the position mask hides unwritten slots.
What went wrongA partial binding params by keyword collided with positional arguments.
FixA small wrapper over one compiled forward; weights passed as an argument.
Verification plan: compare cached and uncached logits on the same tokens, including across a capacity expansion, and check that greedy generation matches the recompute-everything loop.
The JAX foundation is in place. The next parts build toward the research in the project title.