|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include "../ops.hpp" |
| 4 | +#include "module.hpp" |
| 5 | + |
| 6 | +namespace infinicore::nn { |
| 7 | + |
| 8 | +class LayerNorm : public Module { |
| 9 | +public: |
| 10 | + /** |
| 11 | + * @brief Construct a LayerNorm layer |
| 12 | + * |
| 13 | + * @param normalized_shape Size of the feature dimension to normalize (typically hidden_size) |
| 14 | + * @param eps Small constant for numerical stability (default: 1e-6) |
| 15 | + * @param dtype Data type for the weight (default: DataType::F32) |
| 16 | + * @param device Device to create the weight on |
| 17 | + */ |
| 18 | + LayerNorm(size_t normalized_shape, |
| 19 | + double eps = 1e-6, |
| 20 | + const DataType &dtype = DataType::F32, |
| 21 | + const Device &device = Device()); |
| 22 | + |
| 23 | + /** |
| 24 | + * @brief Forward pass: apply LayerNorm |
| 25 | + * |
| 26 | + * @param x Input tensor of shape (*, normalized_shape) where * is any number of dimensions |
| 27 | + * @return Normalized tensor with same shape as input |
| 28 | + * |
| 29 | + * The normalization is applied over the last dimension. |
| 30 | + * For example: |
| 31 | + * Input: [batch, seq_len, hidden_size] -> normalize over hidden_size |
| 32 | + * Input: [batch, hidden_size] -> normalize over hidden_size |
| 33 | + */ |
| 34 | + Tensor forward(const Tensor &x) const; |
| 35 | + |
| 36 | + // Module information |
| 37 | + size_t normalized_shape() const { return normalized_shape_; } |
| 38 | + double eps() const { return eps_; } |
| 39 | + DataType dtype() const { return dtype_; } |
| 40 | + |
| 41 | + // String representation |
| 42 | + std::string extra_repr() const; |
| 43 | + |
| 44 | + // Accessors for parameters |
| 45 | + Tensor weight() const { return weight_; } |
| 46 | + Tensor bias() const { return bias_; } |
| 47 | + |
| 48 | +protected: |
| 49 | + // Parameters |
| 50 | + INFINICORE_NN_PARAMETER(weight); |
| 51 | + INFINICORE_NN_PARAMETER(bias); |
| 52 | + |
| 53 | +private: |
| 54 | + size_t normalized_shape_; // Size of the feature dimension |
| 55 | + double eps_; // Epsilon for numerical stability |
| 56 | + DataType dtype_; // Data type for weight |
| 57 | +}; |
| 58 | + |
| 59 | +} // namespace infinicore::nn |
0 commit comments