Download compatibility/src/fidel_compatibility/operators.py from 4E-AI/Fidel2.0-1B: direct link, hf CLI and curl.
- Browser
- Download file 7.91 kB
-
https://huggingface.co/4E-AI/Fidel2.0-1B/resolve/main/compatibility/src/fidel_compatibility/operators.py
- Command line
-
hf download hf://4E-AI/Fidel2.0-1B/compatibility/src/fidel_compatibility/operators.py
-
curl -L -o operators.py https://huggingface.co/4E-AI/Fidel2.0-1B/resolve/main/compatibility/src/fidel_compatibility/operators.py
7.91 kB
| """Fresh inference operators specified by the released native execution.""" | |
| import torch | |
| import torch.nn.functional as F | |
| def rmsnorm(x, weight, eps=1e-5): | |
| if x.shape[-1] != weight.numel() or x.device != weight.device: | |
| raise ValueError("Normalization width/device mismatch") | |
| inverse = torch.rsqrt(x.float().square().mean(-1, keepdim=True) + eps) | |
| return (x * inverse.to(x.dtype)) * weight.to(x.dtype) | |
| def bc_norm(x, weight, eps=1e-5): | |
| """Native Mamba B/C norm: FP32 multiply before its single output cast.""" | |
| if x.is_cuda: | |
| from .math_primitives import extension | |
| return extension().bc_norm(x.contiguous(),weight.float().contiguous(),eps)[0] | |
| values = x.float() | |
| inverse = torch.rsqrt(values.square().mean(-1, keepdim=True) + eps) | |
| return ((values * inverse) * weight.float()).to(x.dtype) | |
| def route_top2(logits, noise_weight): | |
| if logits.ndim != 2 or logits.shape[1] != 16 or noise_weight.shape != (16,): | |
| raise ValueError("The released router requires 16 experts") | |
| # The native adapter casts both source tensors to FP16 before its kernel. | |
| value = logits.to(torch.float16).float() | |
| nw = noise_weight.to(torch.float16).float() | |
| sp = lambda t: torch.where(t > 20., t, torch.log2(1. + torch.exp2(t * 1.44269504)) * .69314718) | |
| value = value + torch.zeros_like(value) * sp(nw) | |
| probability = sp(value).clamp_min(0.).sqrt() | |
| # Native strict-greater serial loops break ties toward the lowest index. | |
| first = probability.argmax(-1, keepdim=True) | |
| remaining = probability.scatter(1, first, -torch.inf) | |
| second = remaining.argmax(-1, keepdim=True) | |
| selected = torch.cat((first, second), 1) | |
| masked = torch.full_like(value, -10000., dtype=torch.float16) | |
| return masked.scatter(1, selected, probability.gather(1, selected).to(torch.float16)).contiguous() | |
| def expert_dispatch(masked): | |
| """Original causal expert/token ordering, including inactive padded slots.""" | |
| if masked.ndim != 2 or masked.shape[1] != 16 or masked.shape[0] < 1: | |
| raise ValueError("Expected a nonempty [tokens,16] mask") | |
| length = masked.shape[0] | |
| counts = (masked > 0).sum(0) | |
| capacity = max(1, int(counts.max())) | |
| tokens = torch.arange(length, device=masked.device).expand(16, -1) | |
| ordered = torch.where(masked.T > 0, tokens, length).sort(1).values[:, :capacity] | |
| valid = ordered < length | |
| ordered = ordered.clamp_max(length - 1) | |
| probs = torch.where(valid, masked.T.gather(1, ordered), 0.) | |
| return ordered.to(torch.int32), probs, counts | |
| def swiglu(packed): | |
| if packed.ndim != 2 or packed.dtype != torch.bfloat16 or packed.shape[1] % 2: | |
| raise ValueError("Expected interleaved BF16 [rows,2*width]") | |
| x, gate = packed[:, 0::2].float(), packed[:, 1::2].float() | |
| sigmoid = 1. / (1. + torch.exp2(gate * -1.4426950408889634)) | |
| return ((x * gate) * sigmoid).to(torch.bfloat16) | |
| def recombine(expert, tokens, probs, length): | |
| if expert.ndim != 3 or expert.shape[0] != 16 or expert.shape[-1] != 512: | |
| raise ValueError("The released recombiner requires [16,capacity,512]") | |
| if tokens.shape != expert.shape[:2] or probs.shape != tokens.shape or length < 1: | |
| raise ValueError("Invalid expert slot layout") | |
| buffer = torch.zeros((16, length, 512), device=expert.device, dtype=torch.bfloat16) | |
| expert, probs = expert.to(torch.bfloat16), probs.to(torch.bfloat16) | |
| for e in range(16): | |
| valid = (probs[e] > 0) & (tokens[e] < length) & (tokens[e] >= 0) | |
| destination = tokens[e, valid].long() | |
| if destination.unique().numel() != destination.numel(): | |
| raise ValueError("Duplicate active slots would race in the native kernel") | |
| buffer[e, destination] = (expert[e, valid].float() * probs[e, valid, None].float()).to(torch.bfloat16) | |
| return buffer.sum(0) | |
| def rotary(q, k, positions=None, *, base=10000.): | |
| if q.shape[-1] % 2 or q.shape[-1] != k.shape[-1]: | |
| raise ValueError("RoPE requires matching even widths") | |
| length, width = q.shape[1], q.shape[-1] | |
| if positions is None: | |
| positions = torch.arange(length, dtype=torch.float32, device=q.device) | |
| # Released RotaryEmbedding constructs its nonpersistent tables on CPU before | |
| # moving the module. Preserve those bytes instead of using GPU cos/sin. | |
| inv = 1. / (base ** (torch.arange(0, width, 2, dtype=torch.float32) / width)) | |
| freqs = torch.outer(positions.to(device="cpu", dtype=torch.float32), inv) | |
| cos = freqs.cos().to(device=q.device, dtype=q.dtype)[None, :, None] | |
| sin = freqs.sin().to(device=q.device, dtype=q.dtype)[None, :, None] | |
| def apply(value): | |
| rotated = torch.stack((-value[..., 1::2], value[..., ::2]), -1).flatten(-2) | |
| return value * torch.stack((cos, cos), -1).flatten(-2) + rotated * torch.stack((sin, sin), -1).flatten(-2) | |
| return apply(q), apply(k) | |
| def attention(q, k, v): | |
| """Right-aligned causal GQA using the current PyTorch SDPA primitive.""" | |
| if q.ndim != 4 or k.shape != v.shape or q.shape[2] % k.shape[2] or q.shape[1] > k.shape[1]: | |
| raise ValueError("Invalid causal GQA operands") | |
| qt = q.transpose(1, 2) | |
| repeats = q.shape[2] // k.shape[2] | |
| kt, vt = (t.repeat_interleave(repeats, 2).transpose(1, 2) for t in (k, v)) | |
| if q.shape[1] == k.shape[1]: | |
| out = F.scaled_dot_product_attention(qt, kt, vt, is_causal=True) | |
| else: | |
| nq, nk = q.shape[1], k.shape[1] | |
| mask = torch.arange(nk, device=q.device)[None] <= torch.arange(nq, device=q.device)[:, None] + nk - nq | |
| out = F.scaled_dot_product_attention(qt, kt, vt, attn_mask=mask, dropout_p=0.) | |
| return out.transpose(1, 2).contiguous() | |
| def attention_reduction_profile(length): | |
| if not 1<=length<=8192:raise ValueError('Released attention key length must be within1..8192') | |
| if length<=64 or 97<=length<=128:return 8,12 | |
| if length<=96:return 32,1 | |
| if length<=192:return 16,1 | |
| if length<=288:return 4,24 | |
| return 4,1 | |
| def causal_attention_row(q,k,v): | |
| """The release's manual attention row, with pinned non-B200 BMM arithmetic.""" | |
| scale=q.shape[-1]**-.5 | |
| portable=q.is_cuda and torch.cuda.get_device_capability(q.device)!=(10,0) | |
| if portable: | |
| if q.shape[-1]!=96:raise ValueError('The released attention uses head width 96') | |
| from .math_primitives import f32_batched_product | |
| streams,stride=attention_reduction_profile(k.shape[-2]) | |
| scores=f32_batched_product(q,k.transpose(-1,-2),streams=streams,stride=stride)*scale | |
| else:scores=q@k.transpose(-1,-2)*scale | |
| probability=scores.softmax(-1) | |
| output=f32_batched_product(probability,v,streams=32,stride=1) if portable else probability@v | |
| return scores,probability,output | |
| def prompt_cross_products(padded,keys,values): | |
| """Pinned conditioning query/key and probability/value products.""" | |
| rank=padded.shape[-1] | |
| portable=padded.is_cuda and torch.cuda.get_device_capability(padded.device)!=(10,0) | |
| if portable: | |
| if rank not in (64,128):raise ValueError('Released conditioners use ranks 64 and 128') | |
| from .math_primitives import extension | |
| if rank==64 and keys.shape[0]==1: | |
| from .math_primitives import f32_batched_product | |
| scores=f32_batched_product(padded.float()[None],keys.float().T[None],streams=2,stride=1)[0]/(rank**.5) | |
| else: | |
| partitions=rank//32 if keys.shape[0]<110 else 1 | |
| scores=extension().dense_fma(padded.float().contiguous(),keys.float().contiguous(),partitions)/(rank**.5) | |
| else:scores=(padded@keys.T)/(rank**.5) | |
| probability=scores.softmax(-1) | |
| context=extension().dense_fma(probability.contiguous(),values.T.contiguous(),1) if portable else probability@values | |
| return scores,probability,context | |