# U Standard Library Reference

Every function in U belongs to a namespace. Bare function calls are not allowed except `print()`. To use a namespace, import it at the top of your file:

```
import Math
import Tensor
import Dataframe
import NN
import Autograd
import IO
```

Built-in types (`I`, `N`, `S`, `B`, `Tree`, `[T]`, `{K:V}`) and `print()` require no import.

---

## Math

Basic math functions. All operate on `N` (double) values.

```
import Math
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `Math.sqrt(xx)` | `N → N` | Square root |
| `Math.abs(xx)` | `N → N` | Absolute value |
| `Math.floor(xx)` | `N → I` | Floor |
| `Math.ceil(xx)` | `N → I` | Ceiling |
| `Math.round(xx)` | `N → I` | Round to nearest |
| `Math.sin(xx)` | `N → N` | Sine |
| `Math.cos(xx)` | `N → N` | Cosine |
| `Math.tan(xx)` | `N → N` | Tangent |
| `Math.asin(xx)` | `N → N` | Arc sine |
| `Math.acos(xx)` | `N → N` | Arc cosine |
| `Math.atan(xx)` | `N → N` | Arc tangent |
| `Math.atan2(yy, xx)` | `(N, N) → N` | Two-argument arc tangent |
| `Math.exp(xx)` | `N → N` | e^x |
| `Math.ln(xx)` | `N → N` | Natural log |
| `Math.log2(xx)` | `N → N` | Base-2 log |
| `Math.log10(xx)` | `N → N` | Base-10 log |
| `Math.pow(base, exp)` | `(N, N) → N` | Power |
| `Math.min(aa, bb)` | `(N, N) → N` | Minimum |
| `Math.max(aa, bb)` | `(N, N) → N` | Maximum |
| `Math.clamp(xx, lo, hi)` | `(N, N, N) → N` | Clamp to range |
| `Math.PI` | `N` | 3.14159... |
| `Math.E` | `N` | 2.71828... |
| `Math.INF` | `N` | Infinity |

---

## System

System I/O and process control. `print()` is the only bare function — everything else is namespaced.

```
import System
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `print(xx)` | `Tree → none` | Print any value (bare — no import needed) |
| `System.log(msg)` | `S → none` | Log to stderr |
| `System.warn(msg)` | `S → none` | Warning to stderr |
| `System.error(msg)` | `S → none` | Error to stderr |
| `System.exit(code)` | `I → none` | Exit process |
| `System.args()` | `→ [S]` | Command-line arguments |
| `System.env(key)` | `S → S +N` | Environment variable |
| `System.time()` | `→ N` | Current time (seconds since epoch) |

---

## Tensor

N-dimensional array operations. The core numeric type for ML and scientific computing.

```
import Tensor
```

### Construction

| Function | Signature | Description |
|----------|-----------|-------------|
| `Tensor.zeros(shape)` | `[I] → Tensor` | All zeros |
| `Tensor.ones(shape)` | `[I] → Tensor` | All ones |
| `Tensor.full(shape, val)` | `([I], N) → Tensor` | Fill with value |
| `Tensor.eye(nn)` | `I → Tensor` | Identity matrix |
| `Tensor.from_data(data, shape)` | `([N], [I]) → Tensor` | From flat array |
| `Tensor.arange(start, stop, step)` | `(N, N, N) → Tensor` | Range |
| `Tensor.linspace(start, stop, count)` | `(N, N, I) → Tensor` | Evenly spaced |
| `Tensor.rand(shape)` | `[I] → Tensor` | Uniform random [0,1) |
| `Tensor.randn(shape)` | `[I] → Tensor` | Normal random (mean=0, std=1) |
| `Tensor.xavier_uniform(shape)` | `[I] → Tensor` | Xavier/Glorot init |
| `Tensor.he_normal(shape)` | `[I] → Tensor` | He/Kaiming init |

### Element-Wise Ops

| Function | Signature | Description |
|----------|-----------|-------------|
| `Tensor.add(aa, bb)` | `(Tensor, Tensor) → Tensor` | a + b |
| `Tensor.sub(aa, bb)` | `(Tensor, Tensor) → Tensor` | a - b |
| `Tensor.mul(aa, bb)` | `(Tensor, Tensor) → Tensor` | a * b |
| `Tensor.div(aa, bb)` | `(Tensor, Tensor) → Tensor` | a / b |
| `Tensor.scale(tt, ss)` | `(Tensor, N) → Tensor` | t * scalar |
| `Tensor.neg(tt)` | `Tensor → Tensor` | -t |
| `Tensor.abs(tt)` | `Tensor → Tensor` | |t| |
| `Tensor.sqrt(tt)` | `Tensor → Tensor` | √t |
| `Tensor.clamp(tt, lo, hi)` | `(Tensor, N, N) → Tensor` | Clip to range |
| `Tensor.where(cond, aa, bb)` | `(Tensor, Tensor, Tensor) → Tensor` | Conditional select |

### Reductions

| Function | Signature | Description |
|----------|-----------|-------------|
| `Tensor.sum(tt)` | `Tensor → N` | Sum all elements |
| `Tensor.mean(tt)` | `Tensor → N` | Mean |
| `Tensor.max(tt)` | `Tensor → N` | Maximum |
| `Tensor.min(tt)` | `Tensor → N` | Minimum |
| `Tensor.argmax(tt)` | `Tensor → I` | Index of maximum |
| `Tensor.argmin(tt)` | `Tensor → I` | Index of minimum |
| `Tensor.norm(tt)` | `Tensor → N` | L2 norm |
| `Tensor.dot(aa, bb)` | `(Tensor, Tensor) → N` | Dot product |

### Linear Algebra

| Function | Signature | Description |
|----------|-----------|-------------|
| `Tensor.matmul(aa, bb)` | `(Tensor, Tensor) → Tensor` | Matrix multiply |
| `Tensor.transpose(tt)` | `Tensor → Tensor` | Transpose |
| `Tensor.reshape(tt, shape)` | `(Tensor, [I]) → Tensor` | Zero-copy reshape |
| `Tensor.cat(aa, bb)` | `(Tensor, Tensor) → Tensor` | Concatenate |
| `Tensor.stack(tensors, count)` | `([Tensor], I) → Tensor` | Stack 1D → 2D |

### Activations

| Function | Signature | Description |
|----------|-----------|-------------|
| `Tensor.relu(tt)` | `Tensor → Tensor` | max(0, x) |
| `Tensor.sigmoid(tt)` | `Tensor → Tensor` | 1 / (1 + e^-x) |
| `Tensor.tanh(tt)` | `Tensor → Tensor` | Hyperbolic tangent |
| `Tensor.softmax(tt)` | `Tensor → Tensor` | Softmax (last dim) |
| `Tensor.gelu(tt)` | `Tensor → Tensor` | GELU (tanh approx) |
| `Tensor.swish(tt)` | `Tensor → Tensor` | x · sigmoid(x) |
| `Tensor.silu(tt)` | `Tensor → Tensor` | Same as swish |
| `Tensor.leaky_relu(tt, alpha)` | `(Tensor, N) → Tensor` | max(αx, x) |
| `Tensor.elu(tt, alpha)` | `(Tensor, N) → Tensor` | ELU |
| `Tensor.relu6(tt)` | `Tensor → Tensor` | clamp(relu(x), 0, 6) |

---

## NN

Neural network layers and operations.

```
import NN
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `NN.linear(input, weight, bias)` | `(Tensor, Tensor, Tensor +N) → Tensor` | Dense layer: input @ W^T + b |
| `NN.conv2d(input, kernel, stride, padding)` | `(Tensor, Tensor, I, I) → Tensor` | 2D convolution |
| `NN.maxpool2d(input, size, stride)` | `(Tensor, I, I) → Tensor` | 2D max pooling |
| `NN.layer_norm(tt, gamma, beta, eps)` | `(Tensor, Tensor, Tensor, N) → Tensor` | Layer normalization |
| `NN.rms_norm(tt, weight, eps)` | `(Tensor, Tensor, N) → Tensor` | RMS normalization (Llama-style) |
| `NN.batch_norm(tt, g, b, mean, var, eps, training)` | `(...) → Tensor` | Batch normalization |
| `NN.dropout(tt, rate, training)` | `(Tensor, N, B) → Tensor` | Dropout |
| `NN.embedding(table, indices)` | `(Tensor, [I]) → Tensor` | Embedding lookup |
| `NN.attention(qq, kk, vv, heads, mask)` | `(Tensor, Tensor, Tensor, I, Tensor +N) → Tensor` | Multi-head attention |
| `NN.rope(qq, kk, head_dim)` | `(Tensor, Tensor, I) → none` | Rotary position embedding (in-place) |
| `NN.causal_mask(seq_len)` | `I → Tensor` | Upper-triangle mask (-∞) |

### Optimizers

| Function | Signature | Description |
|----------|-----------|-------------|
| `NN.sgd_step(params, grads, lr)` | `([Tensor], [Tensor], N) → none` | SGD: w -= lr * grad |
| `NN.adam_step(params, grads, mm, vv, lr, beta1, beta2, eps, step)` | `(...) → none` | Adam optimizer |

### Loss Functions

| Function | Signature | Description |
|----------|-----------|-------------|
| `NN.mse_loss(pred, target)` | `(Tensor, Tensor) → N` | Mean squared error |
| `NN.cross_entropy(logits, labels, batch)` | `(Tensor, [I], I) → N` | Cross-entropy loss |

---

## Autograd

Automatic differentiation via tape-based recording.

```
import Autograd
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `Autograd.begin()` | `→ none` | Start recording operations |
| `Autograd.end()` | `→ none` | Stop recording |
| `Autograd.leaf(tt)` | `Tensor → none` | Mark tensor as trainable parameter |
| `Autograd.backward(tape, loss_grad)` | `(Tape, Tensor +N) → none` | Compute all gradients |
| `Autograd.grad(tape, tt)` | `(Tape, Tensor) → Tensor +N` | Get gradient for a tensor |

Supported gradient operations: `add`, `mul`, `matmul`, `relu`, `scale`.

---

## Dataframe

Columnar data operations for tabular data.

```
import Dataframe
```

### Construction

| Function | Signature | Description |
|----------|-----------|-------------|
| `Dataframe.from_csv(path)` | `S → Dataframe +A` | Load CSV (async) |
| `Dataframe.from_csv_string(csv)` | `S → Dataframe` | Parse CSV string |
| `Dataframe.from_json(rows)` | `[Tree] → Dataframe` | From JSON array |
| `Dataframe.from_columns(cols)` | `{S: [Tree]} → Dataframe` | From column map |

### Selection & Filtering

| Function | Signature | Description |
|----------|-----------|-------------|
| `df.select(cols)` | `[S] → Dataframe` | Keep columns |
| `df.drop(col)` | `S → Dataframe` | Remove column |
| `df.head(nn)` | `I → Dataframe` | First n rows |
| `df.sort(col, desc)` | `(S, B) → Dataframe` | Sort by column |
| `df.filter_mask(mask)` | `Column → Dataframe` | Keep rows where mask=true |
| `df.unique(col)` | `S → Dataframe` | Deduplicate by column |
| `df.sample(nn)` | `I → Dataframe` | Random sample |

### Aggregation

| Function | Signature | Description |
|----------|-----------|-------------|
| `df.get_column(name)` | `S → Column` | Get column by name |
| `df.count()` | `→ I` | Row count |
| `df.groupby_agg(group, agg, func)` | `(S, S, S) → Dataframe` | GroupBy + aggregate ("sum"/"mean"/"count"/"min"/"max") |
| `df.with_column(name, col)` | `(S, Column) → Dataframe` | Add/replace column |
| `df.join(other, on, how)` | `(Dataframe, S, S) → Dataframe` | Join ("inner"/"left"/"right") |

---

## Column

Typed array operations on individual columns.

```
import Column
```

### Aggregation

| Function | Signature | Description |
|----------|-----------|-------------|
| `col.sum_I()` | `→ I` | Sum (integer column) |
| `col.sum_N()` | `→ N` | Sum (float column) |
| `col.mean()` | `→ N` | Mean |
| `col.min_I()` / `col.max_I()` | `→ I` | Min/max (integer) |
| `col.min_N()` / `col.max_N()` | `→ N` | Min/max (float) |

### Comparison (returns boolean Column)

| Function | Signature | Description |
|----------|-----------|-------------|
| `col.gt_I(val)` | `I → Column` | Greater than |
| `col.lt_I(val)` | `I → Column` | Less than |
| `col.eq_I(val)` | `I → Column` | Equal to |

### String Operations

| Function | Signature | Description |
|----------|-----------|-------------|
| `col.str_len()` | `→ Column[I]` | String lengths |
| `col.str_upper()` | `→ Column[S]` | Uppercase |
| `col.str_lower()` | `→ Column[S]` | Lowercase |
| `col.str_contains(pat)` | `S → Column[B]` | Contains substring |

### Conversion

| Function | Signature | Description |
|----------|-----------|-------------|
| `col.to_tensor()` | `→ Tensor` | Column → Tensor |

---

## Safetensors

Load model weights from HuggingFace safetensors format.

```
import Safetensors
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `Safetensors.load(path)` | `S → SafetensorFile +A` | Load from file |
| `Safetensors.parse(buffer)` | `[Q8] → SafetensorFile` | Parse from bytes |
| `Safetensors.get(file, name)` | `(SafetensorFile, S) → Tensor +N` | Get tensor by name |
| `Safetensors.info(file)` | `SafetensorFile → S` | List all tensors |

Supported dtypes: F16, BF16, F32, F64.

---

## Tokenizer

Text tokenization for NLP models.

```
import Tokenizer
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `Tokenizer.load(vocab)` | `S → Tokenizer` | Load from vocab text |
| `Tokenizer.encode(tok, text)` | `(Tokenizer, S) → [I]` | Text → token IDs |
| `Tokenizer.decode(tok, ids)` | `(Tokenizer, [I]) → S` | Token IDs → text |
| `Tokenizer.encode_bytes(text)` | `S → [I]` | Byte-level tokenization |

---

## KVCache

Key-value cache for autoregressive transformer generation.

```
import KVCache
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `KVCache.new(layers, max_seq, d_model)` | `(I, I, I) → KVCache` | Allocate cache |
| `KVCache.append(kv, layer, kk, vv)` | `(KVCache, I, Tensor, Tensor) → none` | Cache one token's K,V |
| `KVCache.get_k(kv, layer)` | `(KVCache, I) → Tensor` | Get cached keys |
| `KVCache.get_v(kv, layer)` | `(KVCache, I) → Tensor` | Get cached values |
| `KVCache.advance(kv)` | `KVCache → none` | Increment position |
| `KVCache.reset(kv)` | `KVCache → none` | Clear cache |

---

## IO

File and network I/O (async by default).

```
import IO
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `IO.read(path)` | `S → S +A` | Read file to string |
| `IO.write(path, data)` | `(S, S) → none +A` | Write string to file |
| `IO.read_bytes(path)` | `S → [Q8] +A` | Read file to bytes |
| `IO.write_bytes(path, data)` | `(S, [Q8]) → none +A` | Write bytes to file |

---

## Template Tags (no import needed)

Template tags are built-in and produce format-safe typed strings:

| Tag | Type | Example |
|-----|------|---------|
| `HTML\`...\`` | `Formats.HTML` | `HTML\`<p>{{name}}</p>\`` |
| `SQL\`...\`` | `Formats.SQL` | `SQL\`SELECT * FROM {{table}}\`` |
| `CSS\`...\`` | `Formats.CSS` | `CSS\`color: {{color}}\`` |
| `JSON\`...\`` | `Formats.JSON` | `JSON\`{"key": {{val}}}\`` |
| `Regex\`...\`` | `Formats.Regex` | `Regex\`[a-z]+\`` |
| `Dataframe\`...\`` | `Formats.Dataframe` | `Dataframe\`select {{cols}} from {{df}}\`` |
| `Shell\`...\`` | `Formats.Shell` | `Shell\`ls {{dir}}\`` |
| `URL\`...\`` | `Formats.URL` | `URL\`/api/{{resource}}\`` |
| `Markdown\`...\`` | `Formats.Markdown` | `Markdown\`# {{title}}\`` |

---

## Modifiers (no import needed)

| Modifier | Meaning | Example |
|----------|---------|---------|
| `+M` | Mutable | `count: I +M = 0` |
| `+N` | Nullable | `name: S +N = none` |
| `+R` | Heap (refcounted) | `data: [I] +R` |
| `+A` | Async | `f fetch(url: S) -> S +A` |
| `+V` | Vectorized / GPU | `Tensor.add(aa, bb) +V` |
| `+W` | Lazy (streaming) | `df.filter(pred) +W` |
| `+R(GPU)` | GPU-resident memory | `weights +R(GPU)` |


---

## GGUF

Load models from llama.cpp GGUF format.

```
import GGUF
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `GGUF.parse(buffer)` | `[Q8] → GGUFFile` | Parse GGUF from bytes |
| `GGUF.get(file, name)` | `(GGUFFile, S) → Tensor +N` | Get tensor (auto-dequantizes Q4_0/Q8_0/F16/BF16/F32) |
| `GGUF.get_u32(file, key)` | `(GGUFFile, S) → I` | Get metadata integer |
| `GGUF.get_f32(file, key)` | `(GGUFFile, S) → N` | Get metadata float |
| `GGUF.get_str(file, key)` | `(GGUFFile, S) → S` | Get metadata string |
| `GGUF.info(file)` | `GGUFFile → S` | List all tensors and metadata |

---

## BitNet

Ternary (1.58-bit) weight quantization and matmul.

```
import BitNet
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `BitNet.quantize(weight)` | `Tensor → BitNetWeight` | Float → 2-bit ternary (-1, 0, +1) |
| `BitNet.matmul(input, weight)` | `(Tensor, BitNetWeight) → Tensor` | Add/sub only — no float multiply |

---

## LoRA

Low-Rank Adaptation for model customization without retraining.

```
import LoRA
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `LoRA.load(file, layers, rank, alpha)` | `(SafetensorFile, I, I, N) → LoRAAdapter` | Load adapter from safetensors |
| `LoRA.linear(input, weight, bias, aa, bb, scale)` | `(...) → Tensor` | Linear + LoRA: W + A×B×scale |

---

## Steering

Activation steering for behavior control.

```
import Steering
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `Steering.load(file, name, strength, layer)` | `(...) → SteeringConfig` | Load vector from safetensors |
| `Steering.apply(hidden, config, current_layer)` | `(Tensor, SteeringConfig, I) → none` | Add direction to activations |
| `Steering.compute(positive, negative)` | `([Tensor], [Tensor]) → Tensor` | Compute from contrastive pairs |

---

## SessionPool

Multi-user inference with fork() and CoW memory sharing.

```
import SessionPool
```

| Function | Signature | Description |
|----------|-----------|-------------|
| `SessionPool.new(model, tokenizer, max, seq_len)` | `(...) → SessionPool` | Create pool |
| `SessionPool.warmup(pool, prompt)` | `(SessionPool, S) → none` | Pre-compute system prompt KV |
| `SessionPool.save_warmup(pool, path)` | `(SessionPool, S) → none` | Save to ZFS |
| `SessionPool.load_warmup(pool, path)` | `(SessionPool, S) → none` | Load from ZFS |
| `SessionPool.handle(pool, message, fd)` | `(SessionPool, S, I) → I` | fork() and handle request |
| `SessionPool.reap(pool)` | `SessionPool → none` | Clean up finished sessions |
