kgrabko commited on
Commit
31cfe2d
·
verified ·
1 Parent(s): 5e80710

Upload 2 files

Browse files
Files changed (2) hide show
  1. JiRackPyTorch_GPT5_class_70b.py +146 -0
  2. SWA_fusion_spec.md +19 -0
JiRackPyTorch_GPT5_class_70b.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==============================================================================
2
+ # COPYRIGHT (C) 2025 KONSTANTIN VLADIMIROVICH GRABKO. ALL RIGHTS RESERVED.
3
+ # PATENT PENDING | CMS MANHATTAN JIRACK TECHNOLOGY
4
+ #
5
+ # This software is licensed under the Commercial License Agreement V.1.2.
6
+ # Any use, modification, or distribution of this code requires compliance with
7
+ # the terms found in the LICENSE.md file in the root directory.
8
+ #
9
+ # NO PATENTING RIGHTS: Users are strictly prohibited from filing patent claims
10
+ # based on the BRE or SWA architectures disclosed herein.
11
+ # Contact: grabko@cmsmanhattan.com | +1 (516) 777-0945
12
+ # ==============================================================================
13
+ # Version: 70B Flagship Scale (GQA + SwiGLU + RoPE)
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ import math
19
+
20
+ # --- КОНФИГУРАЦИЯ 70B ---
21
+ VOCAB_SIZE = 50257
22
+ MODEL_DIM = 8192 # Стандарт 70B
23
+ NUM_HEADS = 64 # Головы для Queries
24
+ NUM_KV_HEADS = 8 # GQA (коэффициент 8:1)
25
+ NUM_LAYERS = 80 # Глубина 70B
26
+ MAX_SEQ_LEN = 2048
27
+ FFN_HIDDEN_DIM = 28672 # SwiGLU масштаб для 70B
28
+ HEAD_DIM = MODEL_DIM // NUM_HEADS
29
+ EPSILON = 1e-5
30
+ WINDOW_SIZE = 2048
31
+
32
+
33
+
34
+ class RMSNorm(nn.Module):
35
+ def __init__(self, dim, eps=EPSILON):
36
+ super().__init__()
37
+ self.eps = eps
38
+ self.weight = nn.Parameter(torch.ones(dim))
39
+ def forward(self, x):
40
+ return (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)) * self.weight
41
+
42
+ def precompute_freqs_cis(dim, seq_len, theta=10000.0):
43
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
44
+ t = torch.arange(seq_len)
45
+ freqs = torch.outer(t, freqs).float()
46
+ return torch.polar(torch.ones_like(freqs), freqs)
47
+
48
+ def apply_rotary_emb(xq, xk, freqs_cis):
49
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
50
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
51
+ freqs_cis = freqs_cis.view(1, xq_.size(1), 1, xq_.size(3))
52
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
53
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
54
+ return xq_out.type_as(xq), xk_out.type_as(xk)
55
+
56
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
57
+ if n_rep == 1:
58
+ return x
59
+ bs, slen, n_kv_heads, head_dim = x.shape
60
+ return (
61
+ x[:, :, :, None, :]
62
+ .expand(bs, slen, n_kv_heads, n_rep, head_dim)
63
+ .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
64
+ )
65
+
66
+ class MultiHeadAttention(nn.Module):
67
+ def __init__(self):
68
+ super().__init__()
69
+ self.n_kv_heads = NUM_KV_HEADS
70
+ self.n_rep = NUM_HEADS // NUM_KV_HEADS
71
+
72
+ self.wq = nn.Linear(MODEL_DIM, NUM_HEADS * HEAD_DIM, bias=False)
73
+ self.wk = nn.Linear(MODEL_DIM, NUM_KV_HEADS * HEAD_DIM, bias=False)
74
+ self.wv = nn.Linear(MODEL_DIM, NUM_KV_HEADS * HEAD_DIM, bias=False)
75
+ self.wo = nn.Linear(NUM_HEADS * HEAD_DIM, MODEL_DIM, bias=False)
76
+
77
+ def forward(self, x, freqs_cis, past_kv=None):
78
+ b, t, _ = x.shape
79
+ q, k, v = self.wq(x), self.wk(x), self.wv(x)
80
+
81
+ q = q.view(b, t, NUM_HEADS, HEAD_DIM)
82
+ k = k.view(b, t, self.n_kv_heads, HEAD_DIM)
83
+ v = v.view(b, t, self.n_kv_heads, HEAD_DIM)
84
+
85
+ q, k = apply_rotary_emb(q, k, freqs_cis[:t])
86
+
87
+ if past_kv is not None:
88
+ pk, pv = past_kv
89
+ k = torch.cat([pk, k], dim=1)
90
+ v = torch.cat([pv, v], dim=1)
91
+ if k.size(1) > WINDOW_SIZE:
92
+ k, v = k[:, -WINDOW_SIZE:], v[:, -WINDOW_SIZE:]
93
+
94
+ current_kv = (k.detach(), v.detach())
95
+ k = repeat_kv(k, self.n_rep)
96
+ v = repeat_kv(v, self.n_rep)
97
+
98
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
99
+ out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
100
+ return self.wo(out.transpose(1, 2).contiguous().view(b, t, MODEL_DIM)), current_kv
101
+
102
+ class SwiGLU(nn.Module):
103
+ def __init__(self):
104
+ super().__init__()
105
+ self.w1 = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
106
+ self.w2 = nn.Linear(FFN_HIDDEN_DIM, MODEL_DIM, bias=False)
107
+ self.w3 = nn.Linear(MODEL_DIM, FFN_HIDDEN_DIM, bias=False)
108
+ def forward(self, x):
109
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
110
+
111
+ class JiRackPyTorch(nn.Module):
112
+ def __init__(self):
113
+ super().__init__()
114
+ self.token_emb = nn.Embedding(VOCAB_SIZE, MODEL_DIM)
115
+ self.blocks = nn.ModuleList([nn.ModuleDict({
116
+ 'norm1': RMSNorm(MODEL_DIM),
117
+ 'attn': MultiHeadAttention(),
118
+ 'norm2': RMSNorm(MODEL_DIM),
119
+ 'ffn': SwiGLU()
120
+ }) for _ in range(NUM_LAYERS)])
121
+ self.norm_f = RMSNorm(MODEL_DIM)
122
+ self.head = nn.Linear(MODEL_DIM, VOCAB_SIZE, bias=False)
123
+ self.head.weight = self.token_emb.weight
124
+
125
+ self.register_buffer("freqs_cis", precompute_freqs_cis(HEAD_DIM, MAX_SEQ_LEN * 2))
126
+
127
+ signature = "Author: Konstantin Vladimirovich Grabko (CMS Manhattan) 2025"
128
+ self.register_buffer("proof_of_authorship", torch.tensor([ord(c) for c in signature], dtype=torch.uint8))
129
+
130
+ def get_author_info(self):
131
+ return "".join([chr(c) for c in self.proof_of_authorship.tolist()])
132
+
133
+ def forward(self, idx, targets=None, past_kv=None):
134
+ x = self.token_emb(idx)
135
+ new_kvs = []
136
+ for i, block in enumerate(self.blocks):
137
+ h, kv = block['attn'](block['norm1'](x), self.freqs_cis, past_kv[i] if past_kv else None)
138
+ x = x + h
139
+ x = x + block['ffn'](block['norm2'](x))
140
+ new_kvs.append(kv)
141
+ x = self.norm_f(x)
142
+ logits = self.head(x)
143
+ if targets is not None:
144
+ loss = F.cross_entropy(logits.view(-1, VOCAB_SIZE), targets.view(-1))
145
+ return logits, loss, new_kvs
146
+ return logits, new_kvs
SWA_fusion_spec.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Technical Specification: SwiGLU-Attention (SWA) Fusion Kernel
2
+ **Document ID:** CMS-SWA-2025-001
3
+ **Status:** Proprietary / High Performance
4
+
5
+ ### Abstract
6
+ In standard transformers, the Multi-Head Attention (MHA) and Feed-Forward Network (FFN) are executed as discrete kernels, forcing multiple round-trips to Global Memory (VRAM). SWA Fusion merges these into a single computational pass.
7
+
8
+ ### Computational Logic
9
+ The kernel pipelines the $Q, K, V$ projections simultaneously with the $W_1$ and $W_3$ projections of the SwiGLU layer.
10
+ 1. **Shared Input Latches:** Input $x$ is loaded into Shared Memory (SRAM) once.
11
+ 2. **Parallel Projections:** $$Y_{attn} = \text{Softmax}(\frac{QK^T}{\sqrt{d_k}})V$$
12
+ $$Y_{ffn} = (SiLU(xW_1) \otimes xW_3)W_2$$
13
+ 3. **Fused Accumulation:** $x_{out} = x + Y_{attn} + Y_{ffn}$ is computed in a single thread block before writing back to HBM.
14
+
15
+
16
+
17
+ ### Performance Target
18
+ - **Memory Bandwidth Reduction:** 30% lower VRAM traffic.
19
+ - **Hardware Target:** Optimized for AMD CDNA3 (MI300X) Matrix Cores.