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