|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +import math |
| 17 | +from typing import Any, Self |
| 18 | + |
| 19 | +import torch |
| 20 | +import torch.nn as nn |
| 21 | +import torch.nn.functional as F |
| 22 | + |
| 23 | + |
| 24 | +class Conv1dFlatWeights(nn.Conv1d): |
| 25 | + """Conv1d with weights+bias stored in a single 2D tensor |
| 26 | +
|
| 27 | + There are conv1d used in some LLM, in mamba mixer for example. Because the weight is not 2d, we cannot apply |
| 28 | + many of the emerging optimizers originally introduced for 2d weights of Linear layers without bias. Since |
| 29 | + convolution can be viewed as a matrix multiplication with im2col (either implicit or explicit), we can flatten |
| 30 | + the weight into a single 2D tensor and then apply the emerging optimizers to it. |
| 31 | +
|
| 32 | + Bias is not commonly used in most LLM's anymore, but they are often included in this type of conv1d. |
| 33 | + Since bias is mathematically the 0 order term of the polynomial, we can combine weight and bias into a |
| 34 | + single 2D tensor. |
| 35 | +
|
| 36 | + Arguments are the same as ::class:`torch.nn.Conv1d`. |
| 37 | +
|
| 38 | + Note: |
| 39 | + This implementation potentially introduces a small overhead because of split weights can combining gradients |
| 40 | + of it. This should be trivial compared to computational cost of LLM training. If it becomes a concern, a |
| 41 | + kernel can be developed to eliminate the overhead. |
| 42 | +
|
| 43 | + Note: |
| 44 | + Similar flattening logic can be applied to N-D convolution. But since we don't have use cases of them in LLM |
| 45 | + yet, they are not supported despite the __init__() function is generalized enough to support N-D convolution. |
| 46 | +
|
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 50 | + super().__init__(*args, **kwargs) |
| 51 | + |
| 52 | + assert self.padding_mode == "zeros", "Only zeros padding is supported" |
| 53 | + |
| 54 | + self.weight: nn.Parameter[torch.Tensor] |
| 55 | + self.bias: nn.Parameter[torch.Tensor] | None | str |
| 56 | + |
| 57 | + flat_weight_shape = [self.out_channels, math.prod(self.weight.shape[1:])] |
| 58 | + if self.bias is not None: |
| 59 | + flat_weight_shape[1] += 1 |
| 60 | + flat_weight_buffer = torch.empty(flat_weight_shape, device=self.weight.device, dtype=self.weight.dtype) |
| 61 | + if self.bias is not None: |
| 62 | + flat_weight_buffer[..., :-1].copy_(self.weight.view(self.out_channels, -1)) |
| 63 | + flat_weight_buffer[..., -1].copy_(self.bias) |
| 64 | + del self.bias |
| 65 | + self.has_bias = True |
| 66 | + self.bias = "dummy" # Trick con1d.extra_repr() to not print bias=False |
| 67 | + else: |
| 68 | + flat_weight_buffer.copy_(self.weight.view(self.out_channels, -1)) |
| 69 | + self.has_bias = False |
| 70 | + del self.weight |
| 71 | + |
| 72 | + self.weight = nn.Parameter(flat_weight_buffer) |
| 73 | + |
| 74 | + @classmethod |
| 75 | + def from_conv1d(cls, conv1d: nn.Conv1d) -> Self: |
| 76 | + conv1d_flat = cls( |
| 77 | + in_channels=conv1d.in_channels, |
| 78 | + out_channels=conv1d.out_channels, |
| 79 | + kernel_size=conv1d.kernel_size, |
| 80 | + bias=conv1d.bias is not None, |
| 81 | + stride=conv1d.stride, |
| 82 | + padding=conv1d.padding, |
| 83 | + dilation=conv1d.dilation, |
| 84 | + groups=conv1d.groups, |
| 85 | + padding_mode=conv1d.padding_mode, |
| 86 | + device=conv1d.weight.device, |
| 87 | + dtype=conv1d.weight.dtype, |
| 88 | + ) |
| 89 | + |
| 90 | + if conv1d.bias is not None: |
| 91 | + conv1d_flat.weight.data[..., :-1].copy_(conv1d.weight.data.view(conv1d.out_channels, -1)) |
| 92 | + conv1d_flat.weight.data[..., -1].copy_(conv1d.bias.data) |
| 93 | + else: |
| 94 | + conv1d_flat.weight.data.copy_(conv1d.weight.data.view(conv1d.out_channels, -1)) |
| 95 | + return conv1d_flat |
| 96 | + |
| 97 | + @property |
| 98 | + def weight_shape(self) -> tuple[int, int, int]: |
| 99 | + return (self.out_channels, self.in_channels // self.groups, self.kernel_size[0]) |
| 100 | + |
| 101 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 102 | + if self.has_bias: |
| 103 | + weight = self.weight[..., :-1].view(self.weight_shape) |
| 104 | + bias = self.weight[..., -1] |
| 105 | + else: |
| 106 | + weight = self.weight.view(self.weight_shape) |
| 107 | + bias = None |
| 108 | + |
| 109 | + return F.conv1d(x, weight, bias, self.stride, self.padding, self.dilation, self.groups) |
| 110 | + |
| 111 | + def extra_repr(self) -> str: |
| 112 | + base_repr = super().extra_repr() |
| 113 | + return f"{base_repr}, flattened_param_shape={tuple(self.weight.shape)}" |
0 commit comments