broccoli-ml 0.26.0__py3-none-any.whl → 6.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
broccoli/cnn.py CHANGED
@@ -1,300 +1,12 @@
1
1
  import torch
2
2
  import torch.nn as nn
3
3
  import torch.nn.functional as F
4
- from torch.nn.modules.utils import _pair
5
- from einops import rearrange
6
4
  import math
7
- from typing import Type, Union, Tuple, Optional, Literal
5
+ from typing import Union
8
6
 
9
7
  from einops.layers.torch import Rearrange
10
8
 
11
9
 
12
- # # Helper function to calculate padding for 'same' mode
13
- # # Adapted from https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/conv.py
14
- # def _calculate_same_padding(
15
- # input_size: Tuple[int, int],
16
- # kernel_size: Tuple[int, int],
17
- # stride: Tuple[int, int],
18
- # dilation: Tuple[int, int],
19
- # ) -> Tuple[int, int, int, int]:
20
- # """Calculates padding for 'same' output shape."""
21
- # ih, iw = input_size
22
- # kh, kw = kernel_size
23
- # sh, sw = stride
24
- # dh, dw = dilation
25
-
26
- # # Effective kernel size
27
- # eff_kh = (kh - 1) * dh + 1
28
- # eff_kw = (kw - 1) * dw + 1
29
-
30
- # # Calculate required total padding
31
- # out_h = (ih + sh - 1) // sh
32
- # out_w = (iw + sw - 1) // sw
33
- # pad_h = max((out_h - 1) * sh + eff_kh - ih, 0)
34
- # pad_w = max((out_w - 1) * sw + eff_kw - iw, 0)
35
-
36
- # # Distribute padding (similar to TensorFlow 'SAME' behavior)
37
- # pad_top = pad_h // 2
38
- # pad_bottom = pad_h - pad_top
39
- # pad_left = pad_w // 2
40
- # pad_right = pad_w - pad_left
41
- # return (pad_left, pad_right, pad_top, pad_bottom)
42
-
43
-
44
- # # Custom Convolution Layer
45
- # class ConvLayer(nn.Module):
46
- # """
47
- # A 2D Convolution layer implemented using torch.nn.Unfold and a custom linear layer.
48
-
49
- # This layer mimics the behavior of torch.nn.Conv2d but allows injecting
50
- # a different linear layer implementation for processing the unfolded patches.
51
-
52
- # Args:
53
- # in_channels (int): Number of channels in the input image.
54
- # out_channels (int): Number of channels produced by the convolution.
55
- # kernel_size (int or tuple): Size of the convolving kernel.
56
- # stride (int or tuple, optional): Stride of the convolution. Default: 1.
57
- # padding (int, tuple or str, optional): Padding added to all four sides
58
- # of the input. Can be an int, a tuple of two ints (padH, padW),
59
- # a tuple of four ints (padLeft, padRight, padTop, padBottom),
60
- # or the strings 'valid' (no padding) or 'same' (padding for same
61
- # output spatial dims as input). Default: 0 ('valid').
62
- # dilation (int or tuple, optional): Spacing between kernel elements. Default: 1.
63
- # bias (bool, optional): If True, adds a learnable bias to the output.
64
- # The bias is handled by the underlying linear layer. Default: True.
65
- # linear (Type[nn.Module], optional): The class of the linear layer
66
- # to use for the kernel operation. Must accept (in_features, out_features, bias)
67
- # in its constructor. Defaults to torch.nn.Linear.
68
- # """
69
-
70
- # def __init__(
71
- # self,
72
- # in_channels: int,
73
- # out_channels: int,
74
- # kernel_size: Union[int, Tuple[int, int]],
75
- # stride: Union[int, Tuple[int, int]] = 1,
76
- # padding: Union[
77
- # int, Tuple[int, int], Tuple[int, int, int, int], Literal["valid", "same"]
78
- # ] = 0,
79
- # dilation: Union[int, Tuple[int, int]] = 1,
80
- # bias: bool = True,
81
- # linear_module: Type[nn.Module] = nn.Linear,
82
- # ):
83
- # super().__init__()
84
- # self.in_channels = in_channels
85
- # self.out_channels = out_channels
86
- # self.kernel_size = _pair(kernel_size)
87
- # self.stride = _pair(stride)
88
- # self.dilation = _pair(dilation)
89
- # self.bias = bias
90
- # self.linear_module = linear_module
91
- # self.padding_mode = (
92
- # padding # Store the original padding mode ('same', 'valid', int, or tuple)
93
- # )
94
-
95
- # # Calculate the number of input features for the linear layer
96
- # # It's the number of channels times the kernel area
97
- # self.linear_in_features = (
98
- # in_channels * self.kernel_size[0] * self.kernel_size[1]
99
- # )
100
-
101
- # # Instantiate the linear layer (kernel)
102
- # self.kernel = self.linear_module(
103
- # self.linear_in_features, out_channels, bias=bias
104
- # )
105
-
106
- # # We will use F.pad for manual padding, so unfold padding is 0
107
- # self.unfold = nn.Unfold(
108
- # kernel_size=self.kernel_size,
109
- # dilation=self.dilation,
110
- # padding=0, # Manual padding handled in forward
111
- # stride=self.stride,
112
- # )
113
-
114
- # # Determine numeric padding values for F.pad
115
- # if isinstance(padding, str):
116
- # if padding not in ["valid", "same"]:
117
- # raise ValueError("padding must be 'valid', 'same', an int, or a tuple")
118
- # # 'same' padding calculation depends on input size, defer to forward pass
119
- # # 'valid' padding means 0
120
- # self._padding_val = (
121
- # (0, 0, 0, 0) if padding == "valid" else None
122
- # ) # None indicates 'same'
123
- # elif isinstance(padding, int):
124
- # self._padding_val = (padding,) * 4
125
- # elif isinstance(padding, tuple) and len(padding) == 2:
126
- # # (padH, padW) -> (padW_left, padW_right, padH_top, padH_bottom)
127
- # self._padding_val = (padding[1], padding[1], padding[0], padding[0])
128
- # elif isinstance(padding, tuple) and len(padding) == 4:
129
- # # (padLeft, padRight, padTop, padBottom) - already in F.pad format
130
- # self._padding_val = padding
131
- # else:
132
- # raise TypeError(
133
- # "padding must be 'valid', 'same', an int, or a tuple of 2 or 4 ints"
134
- # )
135
-
136
- # def _calculate_output_shape(self, h_in: int, w_in: int) -> Tuple[int, int]:
137
- # """Calculates the output height and width."""
138
- # if self._padding_val is None: # 'same' padding
139
- # # For 'same' padding, output size matches input size if stride is 1.
140
- # # If stride > 1, output size is ceil(input_size / stride)
141
- # # The _calculate_same_padding helper ensures this behavior.
142
- # oh = math.ceil(h_in / self.stride[0])
143
- # ow = math.ceil(w_in / self.stride[1])
144
- # return oh, ow
145
- # else:
146
- # # Use the standard formula with the calculated numeric padding
147
- # pad_h = self._padding_val[2] + self._padding_val[3] # top + bottom
148
- # pad_w = self._padding_val[0] + self._padding_val[1] # left + right
149
- # kh, kw = self.kernel_size
150
- # sh, sw = self.stride
151
- # dh, dw = self.dilation
152
-
153
- # eff_kh = (kh - 1) * dh + 1
154
- # eff_kw = (kw - 1) * dw + 1
155
-
156
- # oh = math.floor((h_in + pad_h - eff_kh) / sh + 1)
157
- # ow = math.floor((w_in + pad_w - eff_kw) / sw + 1)
158
- # return oh, ow
159
-
160
- # def forward(self, x: torch.Tensor) -> torch.Tensor:
161
- # """
162
- # Performs the forward pass.
163
-
164
- # Args:
165
- # x (torch.Tensor): Input tensor of shape (N, C_in, H_in, W_in).
166
-
167
- # Returns:
168
- # torch.Tensor: Output tensor of shape (N, C_out, H_out, W_out).
169
- # """
170
- # _, C, H, W = x.shape
171
- # if C != self.in_channels:
172
- # raise ValueError(
173
- # f"Input channels {C} does not match expected {self.in_channels}"
174
- # )
175
-
176
- # # 1. Calculate and Apply Padding
177
- # if self._padding_val is None: # 'same' padding mode
178
- # pad_l, pad_r, pad_t, pad_b = _calculate_same_padding(
179
- # (H, W), self.kernel_size, self.stride, self.dilation
180
- # )
181
- # padded_x = F.pad(x, (pad_l, pad_r, pad_t, pad_b))
182
- # # Update H, W for output shape calculation after padding
183
- # # Note: _calculate_output_shape will correctly handle 'same' based on original H, W
184
- # elif self._padding_val != (0, 0, 0, 0):
185
- # padded_x = F.pad(x, self._padding_val)
186
- # else: # No padding ('valid' or explicit 0)
187
- # padded_x = x
188
-
189
- # # 2. Unfold to extract patches
190
- # # Input: (N, C_in, H_pad, W_pad)
191
- # # Output: (N, C_in * K_h * K_w, L), where L is the number of patches (H_out * W_out)
192
- # patches = self.unfold(padded_x)
193
- # num_patches = patches.shape[-1] # L
194
-
195
- # # 3. Reshape for the linear layer
196
- # # We want (N, L, C_in * K_h * K_w) to apply the linear layer patch-wise
197
- # # transpose switches the last two dimensions
198
- # patches_transposed = patches.transpose(1, 2) # Shape: (N, L, C_in * K_h * K_w)
199
-
200
- # # 4. Apply the linear layer (kernel) to each patch
201
- # # Input: (N, L, linear_in_features)
202
- # # Output: (N, L, out_channels)
203
- # linear_output = self.kernel(patches_transposed)
204
-
205
- # # 5. Reshape back to image format
206
- # # We need (N, out_channels, L) first
207
- # output_transposed = linear_output.transpose(1, 2) # Shape: (N, out_channels, L)
208
-
209
- # # Calculate output spatial dimensions
210
- # out_h, out_w = self._calculate_output_shape(H, W) # Use original H, W
211
-
212
- # # Check if the number of patches matches the calculated output dimensions
213
- # if num_patches != out_h * out_w:
214
- # # This might happen with certain combinations of stride/padding/dilation/input size
215
- # # if the calculation logic has an issue. nn.Unfold is usually robust.
216
- # print(
217
- # f"Warning: Mismatch in calculated patches. "
218
- # f"Expected L={out_h * out_w}, got {num_patches}. "
219
- # f"Using unfolded L={num_patches} to determine output shape."
220
- # )
221
- # # Attempt recovery if possible, though might indicate upstream calculation error
222
- # # Find factors of num_patches close to expected out_h, out_w
223
- # # This part is tricky and might not always yield the desired shape.
224
- # # For simplicity, we'll rely on nn.Unfold's L and reshape.
225
- # # A more robust solution might re-calculate H_out, W_out based *only* on L.
226
- # # For now, let's stick to the reshape based on calculated out_h, out_w,
227
- # # assuming they match L. If they don't, the reshape will fail.
228
- # pass # Proceed with calculated out_h, out_w
229
-
230
- # # Reshape using einops (or tensor.view)
231
- # # Input: (N, C_out, L) -> Output: (N, C_out, H_out, W_out)
232
- # output = rearrange(output_transposed, "n c (h w) -> n c h w", h=out_h, w=out_w)
233
- # # Alternative using view:
234
- # # output = output_transposed.view(N, self.out_channels, out_h, out_w)
235
-
236
- # return output
237
-
238
- # def extra_repr(self) -> str:
239
- # s = (
240
- # "{in_channels}, {out_channels}, kernel_size={kernel_size}"
241
- # ", stride={stride}"
242
- # )
243
- # if self.padding_mode != 0 and self.padding_mode != "valid":
244
- # s += ", padding={padding_mode}"
245
- # if self.dilation != (1,) * len(self.dilation):
246
- # s += ", dilation={dilation}"
247
- # # if self.groups != 1: # Not implemented
248
- # # s += ', groups={groups}'
249
- # if self.bias is False:
250
- # s += ", bias=False"
251
- # if self.linear_module != nn.Linear:
252
- # s += f", linear={self.linear.__name__}"
253
- # return s.format(**self.__dict__)
254
-
255
-
256
- # class WhiteningConv(ConvLayer):
257
- # def __init__(
258
- # self,
259
- # in_channels: int,
260
- # kernel_size: int,
261
- # eigenvectors: torch.Tensor,
262
- # bias: bool = True,
263
- # linear_module: Type[nn.Module] = nn.Linear,
264
- # ):
265
- # """
266
- # We end up using a concatenation of the eigenvector tensor with its negation,
267
- # as the tendency to use e.g. ReLU in neural networks means that useful
268
- # data may otherwise be lost (if one orientation of an eigenvector produces
269
- # a strong negative signal, this will be clipped to zero by ReLU, but a
270
- # strong positive signal from the negation of the eigenvector will be
271
- # preserved). Assuming a square kernel, out channels is thus
272
-
273
- # (kernel_size ** 2) * in_channels * 2
274
-
275
- # where the trailing "* 2" accounts for the doubling of the size of the
276
- # eigenvector tensor we're using by including the negative of each eigenvector
277
- # as well.
278
- # """
279
- # out_channels = kernel_size**2 * in_channels * 2
280
- # super().__init__(
281
- # in_channels,
282
- # out_channels,
283
- # kernel_size,
284
- # padding="same",
285
- # bias=bias,
286
- # linear_module=linear_module,
287
- # )
288
- # self.eigenvectors = torch.cat([eigenvectors, -eigenvectors], dim=0)
289
- # # bias updates if `bias`=True but weight doesn't,
290
- # # per Jordan (2024) https://arxiv.org/abs/2404.00498
291
- # # but weight is set to `requires_grad = False`:
292
- # # self.kernel.weight.requires_grad = False
293
- # with torch.no_grad():
294
- # self.kernel.weight.copy_(self.eigenvectors)
295
- # assert self.kernel.weight.requires_grad
296
-
297
-
298
10
  def spatial_tuple(size: Union[int, tuple], spatial_dimensions):
299
11
  """
300
12
  Converts an integer x to `tuple([x] * spatial_dimensions)`.
broccoli/linear.py CHANGED
@@ -1,5 +1,3 @@
1
- # UNDER CONSTRUCTION
2
-
3
1
  import math
4
2
  import torch
5
3
  from torch import nn
@@ -34,7 +32,8 @@ class SpectralNormLinear(nn.Module):
34
32
 
35
33
  def reset_parameters(self) -> None:
36
34
  weights = torch.empty(self.out_features, self.in_features)
37
- nn.init.kaiming_uniform_(weights, a=math.sqrt(5))
35
+ stdv = 1.0 / math.sqrt(self.in_features)
36
+ nn.init.uniform_(weights, a=-stdv, b=stdv)
38
37
  if self.use_bias:
39
38
  fan_in, _ = nn.init._calculate_fan_in_and_fan_out(weights)
40
39
  bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
@@ -77,7 +76,8 @@ class AnchoredLinear(nn.Module):
77
76
 
78
77
  def reset_parameters(self) -> None:
79
78
  weights = torch.empty(self.out_features, self.in_features)
80
- nn.init.kaiming_uniform_(weights, a=math.sqrt(5))
79
+ stdv = 1.0 / math.sqrt(self.in_features)
80
+ nn.init.uniform_(weights, a=-stdv, b=stdv)
81
81
  if self.use_bias:
82
82
  fan_in, _ = nn.init._calculate_fan_in_and_fan_out(weights)
83
83
  bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
@@ -95,7 +95,7 @@ class AnchoredLinear(nn.Module):
95
95
  )
96
96
 
97
97
 
98
- class ReparamLinear(nn.Module):
98
+ class WeightNormedLinear(nn.Module):
99
99
  """
100
100
  ...
101
101
  """
@@ -120,7 +120,8 @@ class ReparamLinear(nn.Module):
120
120
 
121
121
  def reset_parameters(self) -> None:
122
122
  weights = torch.empty(self.out_features, self.in_features)
123
- nn.init.kaiming_uniform_(weights, a=math.sqrt(5))
123
+ stdv = 1.0 / math.sqrt(self.in_features)
124
+ nn.init.uniform_(weights, a=-stdv, b=stdv)
124
125
  if self.use_bias:
125
126
  fan_in, _ = nn.init._calculate_fan_in_and_fan_out(weights)
126
127
  bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
@@ -131,8 +132,7 @@ class ReparamLinear(nn.Module):
131
132
  return F.linear(x, self.weights(), self.bias)
132
133
 
133
134
  def __repr__(self) -> str:
134
- # Optional: A nice representation for printing the module.
135
135
  return (
136
- f"AnchoredLinear(in_features={self.in_features},"
136
+ f"WeightNormedLinear(in_features={self.in_features},"
137
137
  f"out_features={self.out_features}, bias={self.use_bias})"
138
138
  )
broccoli/rope.py CHANGED
@@ -27,13 +27,28 @@ SOFTWARE.
27
27
  """
28
28
 
29
29
  from __future__ import annotations
30
- from math import pi, log
30
+ from math import pi
31
31
 
32
32
  import torch
33
- from torch.amp import autocast
33
+
34
34
  from torch.nn import Module
35
35
  from torch import nn, einsum, broadcast_tensors, is_tensor, tensor, Tensor
36
36
 
37
+ # Gracefully find the best way to import autocast
38
+ try:
39
+ from torch.amp import autocast as autocast_factory
40
+ except ImportError:
41
+ # Fallback: For PyTorch 1.6 to 1.9
42
+ from torch.cuda.amp import autocast
43
+
44
+ def autocast_factory(_, enabled=True):
45
+ """
46
+ A wrapper that mimics the modern autocast signature but calls the older
47
+ torch.cuda.amp.autocast, ignoring the device_type argument.
48
+ """
49
+ return autocast(enabled=enabled)
50
+
51
+
37
52
  from einops import rearrange, repeat
38
53
 
39
54
  from typing import Literal
@@ -74,7 +89,7 @@ def rotate_half(x):
74
89
  return rearrange(x, "... d r -> ... (d r)")
75
90
 
76
91
 
77
- @autocast("cuda", enabled=False)
92
+ @autocast_factory("cuda", enabled=False)
78
93
  def apply_rotary_emb(
79
94
  freqs, t, start_index=0, scale=1.0, seq_dim=-2, freqs_seq_dim=None
80
95
  ):
@@ -363,7 +378,7 @@ class RotaryEmbedding(Module):
363
378
  all_freqs = broadcast_tensors(*all_freqs)
364
379
  return torch.cat(all_freqs, dim=-1)
365
380
 
366
- @autocast("cuda", enabled=False)
381
+ @autocast_factory("cuda", enabled=False)
367
382
  def forward(self, t: Tensor, seq_len: int | None = None, offset=0):
368
383
  should_cache = (
369
384
  self.cache_if_possible
broccoli/tensor.py CHANGED
@@ -58,48 +58,52 @@ class SigmaReparamTensor(nn.Module):
58
58
 
59
59
  class AnchoredReparamTensor(nn.Module):
60
60
  """
61
- Reparameterise a tensor as a normalised tensor of weights multiplied by a
62
- learnable scaling factor.
61
+ Reparameterises a tensor by decoupling its magnitude and direction.
63
62
 
64
- The tensor of weights is also reparameterised as the product of a learnable
65
- weight tensor with the (fixed) dominant right-singular vector of the
66
- weight tensor as it was initialised.
63
+ The direction is represented by a learnable weight tensor, normalised by the
64
+ Rayleigh quotient with respect to its initial dominant right-singular vector.
65
+ The magnitude is a separate learnable scalar.
67
66
 
68
- i.e this module represents a tensor reparameterised as:
67
+ The reparameterization is:
69
68
 
70
- W_reparam = scale * (W / ||W @ v_0||_2)
69
+ W_reparam = scale * (W / norm)
71
70
 
72
- where v_0 is the dominant right-singular vector of the initial tensor W_init.
71
+ where the norm is the Rayleigh quotient uᵀWv₀, with v₀ being the dominant
72
+ right-singular vector of the initial tensor and u = normalize(Wv₀).
73
73
  """
74
74
 
75
75
  def __init__(self, init_tensor: torch.Tensor):
76
- assert init_tensor.ndim == 2, "Input tensor must be a 2D matrix."
76
+ assert init_tensor.ndim == 2
77
+
77
78
  super().__init__()
78
79
 
79
- # Use the gradboard convention of calling something nondecay_* if we should
80
- # exclude it from weight decay
81
- self.nondecay_weight = nn.Parameter(init_tensor.clone(), requires_grad=True)
80
+ self.weight = nn.Parameter(init_tensor, requires_grad=True)
82
81
 
83
- # At initialization, compute the dominant right-singular vector (v_0)
84
- # and store it in a non-trainable buffer.
85
82
  with torch.no_grad():
86
- _, _, v_transpose = torch.linalg.svd(
87
- self.nondecay_weight, full_matrices=False
88
- )
89
- # v_transpose[0] is the first row of V^T, which is the first right-singular vector.
90
- self.register_buffer("anchor_vector", v_transpose[0])
83
+ _, sigma, v_transpose = torch.linalg.svd(self.weight, full_matrices=False)
91
84
 
92
- initial_norm = torch.linalg.vector_norm(
93
- self.nondecay_weight.mv(self.anchor_vector)
85
+ self.register_buffer("rayleigh_norm", sigma[:1])
86
+ self.register_buffer("initial_right_singular", v_transpose[0])
87
+ self.nondecay_scale = nn.Parameter(
88
+ sigma[:1].clone().detach(), requires_grad=True
94
89
  )
95
- self.scale = nn.Parameter(initial_norm.clone().detach(), requires_grad=True)
96
90
 
97
- def forward(self) -> torch.Tensor:
98
- # Calculate the L2 norm of the matrix-vector product W @ v_0
99
- norm = torch.linalg.vector_norm(self.nondecay_weight.mv(self.anchor_vector))
91
+ def _update_rayleigh_norm(self):
92
+ with torch.no_grad():
93
+ product = self.weight.mv(self.initial_right_singular)
94
+ normed_product = F.normalize(product, dim=0)
95
+ rayleigh_norm = torch.einsum(
96
+ "m,mn,n->",
97
+ normed_product,
98
+ self.weight,
99
+ self.initial_right_singular,
100
+ )
101
+ self.rayleigh_norm.data.copy_(rayleigh_norm)
100
102
 
101
- # Return the reparameterized tensor.
102
- return self.scale * (self.nondecay_weight / (norm + 1e-6))
103
+ def forward(self):
104
+ if self.training:
105
+ self._update_rayleigh_norm()
106
+ return self.nondecay_scale * (self.weight / (self.rayleigh_norm + 1e-6))
103
107
 
104
108
 
105
109
  class NormReparamTensor(nn.Module):
@@ -114,10 +118,11 @@ class NormReparamTensor(nn.Module):
114
118
 
115
119
  # Use the gradboard convention of calling something nondecay_* if we should
116
120
  # exclude it from weight decay
117
- self.nondecay_weight = nn.Parameter(init_tensor.clone(), requires_grad=True)
118
- self.scale = nn.Parameter(
119
- torch.linalg.norm(self.nondecay_weight).clone().detach(), requires_grad=True
121
+ self.weight = nn.Parameter(init_tensor.clone(), requires_grad=True)
122
+ self.nondecay_scale = nn.Parameter(
123
+ torch.linalg.norm(self.weight).clone().detach(), requires_grad=True
120
124
  )
121
125
 
122
126
  def forward(self) -> torch.Tensor:
123
- return self.scale * F.normalize(self.nondecay_weight)
127
+ norm = torch.linalg.norm(self.weight)
128
+ return self.nondecay_scale * (self.weight / (norm + 1e-6))