Instructions to use yb1n/0409_deep_hw with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use yb1n/0409_deep_hw with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="yb1n/0409_deep_hw", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("yb1n/0409_deep_hw", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from transformers import PreTrainedModel | |
| try: | |
| from .configuration_custom import CustomConfig | |
| except ImportError: | |
| from configuration_custom import CustomConfig | |
| class MultiHeadAttention(nn.Module): | |
| """๋ฉํฐ ํค๋ ์ดํ ์ (Multi-Head Attention)์ ๊ตฌํํฉ๋๋ค.""" | |
| def __init__(self, hidden_size, num_heads, dropout=0.1): | |
| super().__init__() | |
| if hidden_size % num_heads != 0: | |
| raise ValueError("hidden_size must be divisible by num_heads") | |
| self.num_heads = num_heads | |
| self.head_size = hidden_size // num_heads | |
| # Query, Key, Value๋ฅผ ๋ง๋ค๊ธฐ ์ํ ์ ํ ๊ณ์ธต(linear layers)์ ๋๋ค. | |
| self.linear_q = nn.Linear(hidden_size, hidden_size) | |
| self.linear_k = nn.Linear(hidden_size, hidden_size) | |
| self.linear_v = nn.Linear(hidden_size, hidden_size) | |
| self.linear_out = nn.Linear(hidden_size, hidden_size) | |
| self.dropout = nn.Dropout(dropout) | |
| def _split_heads(self, x, batch_size, seq_len): | |
| # hidden_size๋ฅผ num_heads์ head_size๋ก ๋๋์ด head๋ณ ํํ(representation)์ ๋ง๋ญ๋๋ค. | |
| return x.view(batch_size, seq_len, self.num_heads, self.head_size).transpose(1, 2) | |
| def forward(self, x, pad_mask=None): | |
| batch_size, seq_len, hidden_size = x.size() | |
| # ์ ํ ์ดํ ์ (self-attention)์ด๋ฏ๋ก query, key, value๊ฐ ๋ชจ๋ ๊ฐ์ ์ ๋ ฅ์์ ๋์ต๋๋ค. | |
| query = self._split_heads(self.linear_q(x), batch_size, seq_len) | |
| key = self._split_heads(self.linear_k(x), batch_size, seq_len) | |
| value = self._split_heads(self.linear_v(x), batch_size, seq_len) | |
| # ์ค์ผ์ผ๋ ๋ท ํ๋ก๋ํธ ์ดํ ์ (scaled dot-product attention) ์ ์๋ฅผ ๊ณ์ฐํฉ๋๋ค. | |
| scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size) | |
| if pad_mask is not None: | |
| # ํจ๋ฉ ๋ง์คํฌ(padding mask)๊ฐ 0์ธ ์์น๋ attention์์ ์ ์ธํฉ๋๋ค. | |
| pad_mask = pad_mask.unsqueeze(1).unsqueeze(2) | |
| scores = scores.masked_fill(pad_mask == 0, torch.finfo(scores.dtype).min) | |
| attn_weights = F.softmax(scores, dim=-1) | |
| attn_weights = self.dropout(attn_weights) | |
| context_by_heads = torch.matmul(attn_weights, value) | |
| context = context_by_heads.transpose(1, 2).contiguous().view(batch_size, seq_len, hidden_size) | |
| context = self.linear_out(context) | |
| return context, attn_weights, scores | |
| class PositionWiseFeedForward(nn.Module): | |
| """์์น๋ณ ํผ๋ํฌ์๋ ๋คํธ์ํฌ(Position-Wise Feed-Forward Network, FFN)๋ฅผ ๊ตฌํํฉ๋๋ค.""" | |
| def __init__(self, hidden_size, intermediate_size, dropout=0.1): | |
| super().__init__() | |
| # ์ฒซ ๋ฒ์งธ ์ ํ ๋ณํ(linear transformation): hidden_size๋ฅผ intermediate_size๋ก ํ์ฅ(expand)ํฉ๋๋ค. | |
| self.linear_expand = nn.Linear(hidden_size, intermediate_size) | |
| # ๋น์ ํ ํ์ฑ ํจ์(non-linear activation function)์ ๋๋ค. | |
| self.activation = nn.ReLU() | |
| # ๋ ๋ฒ์งธ ์ ํ ๋ณํ(linear transformation): ์๋ hidden_size๋ก ํฌ์(project)ํฉ๋๋ค. | |
| self.linear_proj = nn.Linear(intermediate_size, hidden_size) | |
| # ๋๋กญ์์(dropout)์ ๊ณผ์ ํฉ(overfitting)์ ์ค์ด๋ ์ ๊ทํ(regularization)์ ๋๋ค. | |
| self.dropout = nn.Dropout(dropout) | |
| def forward(self, x): | |
| # ์์ ํ(forward pass): expand -> activation -> project -> dropout ์์์ ๋๋ค. | |
| x = self.linear_expand(x) | |
| x = self.activation(x) | |
| x = self.linear_proj(x) | |
| x = self.dropout(x) | |
| return x | |
| class EncoderBlock(nn.Module): | |
| """Transformer์ ๋จ์ผ ์ธ์ฝ๋ ๋ธ๋ก(Encoder Block)์ ๊ตฌํํฉ๋๋ค.""" | |
| def __init__(self, hidden_size, num_heads, intermediate_size, dropout=0.1, layer_norm_eps=1e-12): | |
| super().__init__() | |
| # ๋ฉํฐ ํค๋ ์ ํ ์ดํ ์ (Multi-Head Self-Attention) ๊ณ์ธต์ ๋๋ค. | |
| self.mha = MultiHeadAttention(hidden_size=hidden_size, num_heads=num_heads, dropout=dropout) | |
| self.mha_norm = nn.LayerNorm(hidden_size, eps=layer_norm_eps) | |
| self.dropout = nn.Dropout(dropout) | |
| # ์์น๋ณ ํผ๋ํฌ์๋ ๋คํธ์ํฌ(Position-Wise Feed-Forward Network, FFN)์ ๋๋ค. | |
| self.pff = PositionWiseFeedForward( | |
| hidden_size=hidden_size, | |
| intermediate_size=intermediate_size, | |
| dropout=dropout, | |
| ) | |
| self.pff_norm = nn.LayerNorm(hidden_size, eps=layer_norm_eps) | |
| def forward(self, x, pad_mask=None): | |
| # Attention ์๋ธ๋ ์ด์ด(sub-layer): residual connection ํ layer normalization์ ์ ์ฉํฉ๋๋ค. | |
| attn_output, _, _ = self.mha(x, pad_mask) | |
| x = self.mha_norm(x + self.dropout(attn_output)) | |
| # FFN ์๋ธ๋ ์ด์ด(sub-layer): residual connection ํ layer normalization์ ์ ์ฉํฉ๋๋ค. | |
| ffn_output = self.pff(x) | |
| x = self.pff_norm(x + ffn_output) | |
| return x | |
| class PositionEncoding(nn.Module): | |
| """์ฌ์ธ/์ฝ์ฌ์ธ ์์น ์ธ์ฝ๋ฉ(sinusoidal positional encoding)์ ๊ตฌํํฉ๋๋ค.""" | |
| def __init__(self, hidden_size, max_len=5000, dropout=0.1): | |
| super().__init__() | |
| self.dropout = nn.Dropout(p=dropout) | |
| pe = torch.zeros(max_len, hidden_size) | |
| position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) | |
| denominator = torch.exp(torch.arange(0, hidden_size, 2, dtype=torch.float) * (-math.log(10000.0) / hidden_size)) | |
| # ์ง์ ์ฐจ์์๋ sine, ํ์ ์ฐจ์์๋ cosine ๊ฐ์ ๋ฃ์ต๋๋ค. | |
| pe[:, 0::2] = torch.sin(position * denominator) | |
| pe[:, 1::2] = torch.cos(position * denominator[: pe[:, 1::2].shape[1]]) | |
| # register_buffer๋ ํ์ต ํ๋ผ๋ฏธํฐ(parameter)๋ ์๋์ง๋ง ๋ชจ๋ธ๊ณผ ํจ๊ป ์ ์ฅ๋๋ tensor์ ๋๋ค. | |
| self.register_buffer("pe", pe.unsqueeze(0)) | |
| def forward(self, x): | |
| # ์ ๋ ฅ ์๋ฒ ๋ฉ(embedding)์ ์์น ์ ๋ณด(positional information)๋ฅผ ๋ํฉ๋๋ค. | |
| x = x + self.pe[:, : x.size(1)] | |
| return self.dropout(x) | |
| class TransformerEncoder(PreTrainedModel): | |
| """ํ ํฐ ์๋ฒ ๋ฉ(token embedding)๊ณผ EncoderBlock ์คํ์ผ๋ก ๊ตฌ์ฑ๋ Transformer Encoder์ ๋๋ค.""" | |
| config_class = CustomConfig | |
| base_model_prefix = "transformer_encoder" | |
| def __init__(self, config): | |
| super().__init__(config) | |
| self.embedding = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) | |
| self.pos_encoder = PositionEncoding( | |
| hidden_size=config.hidden_size, | |
| max_len=config.max_position_embeddings, | |
| dropout=config.hidden_dropout_prob, | |
| ) | |
| self.layers = nn.ModuleList( | |
| [ | |
| EncoderBlock( | |
| hidden_size=config.hidden_size, | |
| num_heads=config.num_attention_heads, | |
| intermediate_size=config.intermediate_size, | |
| dropout=config.hidden_dropout_prob, | |
| layer_norm_eps=config.layer_norm_eps, | |
| ) | |
| for _ in range(config.num_hidden_layers) | |
| ] | |
| ) | |
| self.post_init() | |
| def _init_weights(self, module): | |
| # Hugging Face ์ด๊ธฐํ(initialization) ํ๋ฆ์์ ์ฌ์ฉํ๋ ๊ฐ์ค์น ์ด๊ธฐํ์ ๋๋ค. | |
| if isinstance(module, nn.Linear): | |
| module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) | |
| if module.bias is not None: | |
| module.bias.data.zero_() | |
| elif isinstance(module, nn.Embedding): | |
| module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) | |
| if module.padding_idx is not None: | |
| module.weight.data[module.padding_idx].zero_() | |
| elif isinstance(module, nn.LayerNorm): | |
| module.bias.data.zero_() | |
| module.weight.data.fill_(1.0) | |
| def forward(self, input_ids, pad_mask=None): | |
| # input_ids๋ฅผ ์๋ฒ ๋ฉ(embedding)ํ ๋ค ์์น ์ธ์ฝ๋ฉ(positional encoding)์ ๋ํฉ๋๋ค. | |
| x = self.embedding(input_ids) | |
| x = self.pos_encoder(x) | |
| # ์ฌ๋ฌ EncoderBlock์ ์์๋๋ก ํต๊ณผ์ํต๋๋ค. | |
| for layer in self.layers: | |
| x = layer(x, pad_mask) | |
| return x | |
| class CustomTransformerEncoderModel(TransformerEncoder): | |
| """Hugging Face AutoModel์์ ์ฌ์ฉํ ์ ์๋ TransformerEncoder ๋ณ์นญ(alias)์ ๋๋ค.""" | |
| pass | |