deeprcurs-staff commited on
Commit
759eaab
·
verified ·
1 Parent(s): e83c6e9

Upload oicio/core/ternary_san.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. oicio/core/ternary_san.py +11 -12
oicio/core/ternary_san.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
  OICIO Core: Ternary Simple Attention Network
3
- Credits: deepRcurs Labs, @deeprcurs / Mzed Imamkh @mzedimamkh
4
 
5
  Menggabungkan:
6
  - BitNet b1.58: ternary {-1,0,1} absmean quantization
@@ -19,11 +19,12 @@ def hadamard_transform(x):
19
  """Fast Walsh-Hadamard Transform (FWHT) - fixed matrix, no weights, O(n log n)
20
  Dari Needle2: orthonormal Walsh-Hadamard transform
21
  Preserves leading dims, operates on last dim
 
22
  """
23
  orig_shape = x.shape
24
  n = orig_shape[-1]
25
- # Reshape to 2D for transform: [*, n]
26
- x_2d = x.reshape(-1, n)
27
  batch = x_2d.shape[0]
28
 
29
  # pad to power of 2 if needed
@@ -36,24 +37,22 @@ def hadamard_transform(x):
36
  n_padded = n
37
  pad = 0
38
 
 
39
  h = 1
40
  while h < n_padded:
41
- # x_2d: [batch, n_padded]
42
- x_reshaped = x_2d.view(batch, n_padded // (h*2), h, 2)
43
- a = x_reshaped[:, :, :, 0].clone()
44
- b = x_reshaped[:, :, :, 1].clone()
45
- x_reshaped[:, :, :, 0] = a + b
46
- x_reshaped[:, :, :, 1] = a - b
47
- x_2d = x_reshaped.view(batch, n_padded)
48
  h *= 2
49
 
50
  x_2d = x_2d / math.sqrt(n_padded)
51
 
52
- # Trim back to original n if padded
53
  if pad > 0:
54
  x_2d = x_2d[:, :n]
55
 
56
- # Restore original shape
57
  return x_2d.view(orig_shape)
58
 
59
  class BitLinear(nn.Module):
 
1
  """
2
  OICIO Core: Ternary Simple Attention Network
3
+ Credits: deepRcurs Labs, @deeprcurs / Mzed Imamkh, @mzedimamkh
4
 
5
  Menggabungkan:
6
  - BitNet b1.58: ternary {-1,0,1} absmean quantization
 
19
  """Fast Walsh-Hadamard Transform (FWHT) - fixed matrix, no weights, O(n log n)
20
  Dari Needle2: orthonormal Walsh-Hadamard transform
21
  Preserves leading dims, operates on last dim
22
+ Correct implementation like Rust: butterfly with add/sub only
23
  """
24
  orig_shape = x.shape
25
  n = orig_shape[-1]
26
+ # Clone to avoid in-place modification of original
27
+ x_2d = x.reshape(-1, n).clone()
28
  batch = x_2d.shape[0]
29
 
30
  # pad to power of 2 if needed
 
37
  n_padded = n
38
  pad = 0
39
 
40
+ # Correct FWHT like Rust: iterative butterfly
41
  h = 1
42
  while h < n_padded:
43
+ for i in range(0, n_padded, h*2):
44
+ for j in range(h):
45
+ a = x_2d[:, i+j].clone()
46
+ b = x_2d[:, i+j+h].clone()
47
+ x_2d[:, i+j] = a + b
48
+ x_2d[:, i+j+h] = a - b
 
49
  h *= 2
50
 
51
  x_2d = x_2d / math.sqrt(n_padded)
52
 
 
53
  if pad > 0:
54
  x_2d = x_2d[:, :n]
55
 
 
56
  return x_2d.view(orig_shape)
57
 
58
  class BitLinear(nn.Module):