|
|
"""
|
|
|
Boundary-Aware Intelligent Tokenizer Model
|
|
|
๋ฐ์ดํธ-๋ฌธ์ ๊ด๊ณ๋ฅผ ๋ช
์์ ์ผ๋ก ํ์ตํ๋ ๋ชจ๋ธ
|
|
|
"""
|
|
|
|
|
|
import torch
|
|
|
import torch.nn as nn
|
|
|
import torch.nn.functional as F
|
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
import math
|
|
|
|
|
|
|
|
|
from .unified_model import ByteEncoder, TransformerDecoder, CrossAttention, PositionalEncoding
|
|
|
|
|
|
|
|
|
class BoundaryAwareEncoder(nn.Module):
|
|
|
"""
|
|
|
๋ฐ์ดํธ-๋ฌธ์ ๊ฒฝ๊ณ๋ฅผ ๋ช
์์ ์ผ๋ก ํ์ตํ๋ ์ธ์ฝ๋
|
|
|
"""
|
|
|
|
|
|
def __init__(
|
|
|
self,
|
|
|
vocab_size: int = 260,
|
|
|
hidden_dims: List[int] = [512, 512, 640, 768, 768],
|
|
|
num_heads: int = 8,
|
|
|
dropout: float = 0.1,
|
|
|
max_seq_len: int = 512
|
|
|
):
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
|
self.byte_embedding = nn.Embedding(vocab_size, hidden_dims[0])
|
|
|
|
|
|
|
|
|
self.boundary_embedding = nn.Embedding(4, 128)
|
|
|
|
|
|
|
|
|
self.char_type_embedding = nn.Embedding(14, 128)
|
|
|
|
|
|
|
|
|
self.byte_count_embedding = nn.Embedding(5, 128)
|
|
|
|
|
|
|
|
|
self.char_position_embedding = nn.Embedding(4, 128)
|
|
|
|
|
|
|
|
|
structural_dim = 128 * 4
|
|
|
self.input_projection = nn.Linear(hidden_dims[0] + structural_dim, hidden_dims[0])
|
|
|
|
|
|
|
|
|
self.pos_encoding = PositionalEncoding(hidden_dims[0], max_seq_len, dropout)
|
|
|
|
|
|
|
|
|
self.layers = nn.ModuleList()
|
|
|
for i in range(len(hidden_dims)):
|
|
|
input_dim = hidden_dims[i-1] if i > 0 else hidden_dims[0]
|
|
|
output_dim = hidden_dims[i]
|
|
|
|
|
|
if input_dim != output_dim:
|
|
|
proj = nn.Linear(input_dim, output_dim)
|
|
|
else:
|
|
|
proj = None
|
|
|
|
|
|
layer = nn.TransformerEncoderLayer(
|
|
|
d_model=output_dim,
|
|
|
nhead=num_heads,
|
|
|
dim_feedforward=output_dim * 4,
|
|
|
dropout=dropout,
|
|
|
activation='gelu',
|
|
|
batch_first=True,
|
|
|
norm_first=True
|
|
|
)
|
|
|
|
|
|
self.layers.append(nn.ModuleDict({
|
|
|
'projection': proj,
|
|
|
'transformer': layer,
|
|
|
'norm': nn.LayerNorm(output_dim)
|
|
|
}))
|
|
|
|
|
|
|
|
|
|
|
|
self.merging_modules = nn.ModuleList()
|
|
|
|
|
|
for i in range(len(hidden_dims)):
|
|
|
dim = hidden_dims[i]
|
|
|
|
|
|
merge_module = nn.ModuleDict({
|
|
|
|
|
|
'boundary_detector': nn.Linear(dim, 3),
|
|
|
'merge_attention': nn.MultiheadAttention(dim, num_heads//2, dropout, batch_first=True),
|
|
|
'merge_gate': nn.Sequential(
|
|
|
nn.Linear(dim * 2, dim),
|
|
|
nn.ReLU(),
|
|
|
nn.Linear(dim, 1)
|
|
|
),
|
|
|
'merge_proj': nn.Linear(dim * 2, dim),
|
|
|
})
|
|
|
self.merging_modules.append(merge_module)
|
|
|
|
|
|
|
|
|
self.boundary_predictor = nn.Linear(hidden_dims[-1], 4)
|
|
|
|
|
|
|
|
|
self.char_type_predictor = nn.Linear(hidden_dims[-1], 14)
|
|
|
|
|
|
def forward(
|
|
|
self,
|
|
|
input_ids: torch.Tensor,
|
|
|
boundary_labels: Optional[torch.Tensor] = None,
|
|
|
char_types: Optional[torch.Tensor] = None,
|
|
|
byte_counts: Optional[torch.Tensor] = None,
|
|
|
char_indices: Optional[torch.Tensor] = None,
|
|
|
attention_mask: Optional[torch.Tensor] = None
|
|
|
) -> Dict[str, torch.Tensor]:
|
|
|
|
|
|
batch_size, seq_len = input_ids.shape
|
|
|
device = input_ids.device
|
|
|
|
|
|
|
|
|
byte_emb = self.byte_embedding(input_ids)
|
|
|
|
|
|
|
|
|
if boundary_labels is not None:
|
|
|
boundary_emb = self.boundary_embedding(boundary_labels)
|
|
|
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
estimated_boundaries = torch.zeros_like(input_ids)
|
|
|
|
|
|
|
|
|
ascii_mask = input_ids < 128
|
|
|
estimated_boundaries[ascii_mask] = 1
|
|
|
|
|
|
|
|
|
cont_mask = (input_ids >= 128) & (input_ids < 192)
|
|
|
estimated_boundaries[cont_mask] = 0
|
|
|
|
|
|
|
|
|
mb_start_mask = input_ids >= 192
|
|
|
estimated_boundaries[mb_start_mask] = 1
|
|
|
|
|
|
boundary_emb = self.boundary_embedding(estimated_boundaries)
|
|
|
|
|
|
|
|
|
if char_types is not None:
|
|
|
char_type_emb = self.char_type_embedding(char_types)
|
|
|
else:
|
|
|
|
|
|
char_type_emb = self.char_type_embedding(torch.zeros_like(input_ids))
|
|
|
|
|
|
|
|
|
if byte_counts is not None:
|
|
|
byte_count_emb = self.byte_count_embedding(torch.clamp(byte_counts, 0, 4))
|
|
|
else:
|
|
|
|
|
|
estimated_counts = torch.ones_like(input_ids)
|
|
|
|
|
|
estimated_counts[input_ids >= 240] = 4
|
|
|
estimated_counts[(input_ids >= 224) & (input_ids < 240)] = 3
|
|
|
estimated_counts[(input_ids >= 192) & (input_ids < 224)] = 2
|
|
|
byte_count_emb = self.byte_count_embedding(estimated_counts)
|
|
|
|
|
|
|
|
|
if char_indices is not None:
|
|
|
|
|
|
char_positions = torch.zeros_like(char_indices)
|
|
|
for b in range(batch_size):
|
|
|
current_char = -1
|
|
|
position = 0
|
|
|
for i in range(seq_len):
|
|
|
if char_indices[b, i] != current_char:
|
|
|
current_char = char_indices[b, i]
|
|
|
position = 0
|
|
|
else:
|
|
|
position += 1
|
|
|
char_positions[b, i] = min(position, 3)
|
|
|
|
|
|
char_pos_emb = self.char_position_embedding(char_positions)
|
|
|
else:
|
|
|
char_pos_emb = self.char_position_embedding(torch.zeros_like(input_ids))
|
|
|
|
|
|
|
|
|
|
|
|
structural_emb = torch.cat([
|
|
|
boundary_emb,
|
|
|
char_type_emb,
|
|
|
byte_count_emb,
|
|
|
char_pos_emb
|
|
|
], dim=-1)
|
|
|
|
|
|
combined_emb = torch.cat([byte_emb, structural_emb], dim=-1)
|
|
|
|
|
|
|
|
|
x = self.input_projection(combined_emb)
|
|
|
|
|
|
|
|
|
x = self.pos_encoding(x)
|
|
|
|
|
|
|
|
|
all_hidden_states = []
|
|
|
boundary_predictions = []
|
|
|
char_type_predictions = []
|
|
|
merge_info = []
|
|
|
|
|
|
for i, layer_dict in enumerate(self.layers):
|
|
|
|
|
|
if layer_dict['projection'] is not None:
|
|
|
x = layer_dict['projection'](x)
|
|
|
|
|
|
|
|
|
if attention_mask is not None:
|
|
|
|
|
|
current_seq_len = x.size(1)
|
|
|
if attention_mask.size(1) != current_seq_len:
|
|
|
|
|
|
key_padding_mask = torch.zeros(x.size(0), current_seq_len, dtype=torch.bool, device=x.device)
|
|
|
|
|
|
valid_len = min(attention_mask.size(1), current_seq_len)
|
|
|
key_padding_mask[:, :valid_len] = (attention_mask[:, :valid_len] == 0)
|
|
|
else:
|
|
|
key_padding_mask = (attention_mask == 0)
|
|
|
x = layer_dict['transformer'](x, src_key_padding_mask=key_padding_mask)
|
|
|
else:
|
|
|
x = layer_dict['transformer'](x)
|
|
|
|
|
|
x = layer_dict['norm'](x)
|
|
|
|
|
|
|
|
|
all_hidden_states.append(x.clone())
|
|
|
|
|
|
|
|
|
|
|
|
if i < len(self.merging_modules) and self.merging_modules[i] is not None:
|
|
|
merge_module = self.merging_modules[i]
|
|
|
batch_size, seq_len, hidden_dim = x.shape
|
|
|
|
|
|
|
|
|
if seq_len < 4:
|
|
|
continue
|
|
|
|
|
|
|
|
|
if i == 0 and input_ids is not None:
|
|
|
|
|
|
merge_decisions = torch.zeros(batch_size, seq_len - 1, device=x.device)
|
|
|
|
|
|
for b in range(batch_size):
|
|
|
for idx in range(seq_len - 1):
|
|
|
if idx < input_ids.shape[1] - 1:
|
|
|
current_byte = input_ids[b, idx].item()
|
|
|
next_byte = input_ids[b, idx + 1].item()
|
|
|
|
|
|
|
|
|
if 128 <= next_byte < 192:
|
|
|
merge_decisions[b, idx] = 1.0
|
|
|
|
|
|
elif current_byte >= 256 or next_byte >= 256:
|
|
|
merge_decisions[b, idx] = 0.0
|
|
|
|
|
|
|
|
|
x_pairs = torch.cat([x[:, :-1], x[:, 1:]], dim=-1)
|
|
|
merge_scores = merge_module['merge_gate'](x_pairs).squeeze(-1)
|
|
|
merge_probs = torch.sigmoid(merge_scores)
|
|
|
|
|
|
|
|
|
layer_merge_threshold = 0.5
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
|
|
|
|
x_pairs = torch.cat([x[:, :-1], x[:, 1:]], dim=-1)
|
|
|
merge_scores = merge_module['merge_gate'](x_pairs).squeeze(-1)
|
|
|
merge_probs = torch.sigmoid(merge_scores)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
layer_merge_threshold = 0.7 + (i / len(self.merging_modules)) * 0.2
|
|
|
|
|
|
|
|
|
merge_decisions = (merge_probs > layer_merge_threshold).float()
|
|
|
|
|
|
|
|
|
attn_output, attn_weights = merge_module['merge_attention'](x, x, x)
|
|
|
|
|
|
|
|
|
|
|
|
merged_indices = []
|
|
|
merged_x = []
|
|
|
new_mask = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
group_ids = torch.zeros(batch_size, seq_len, device=x.device)
|
|
|
group_ids[:, 0] = 0
|
|
|
group_ids[:, 1:] = 1 - merge_decisions
|
|
|
group_ids = group_ids.cumsum(dim=1).long()
|
|
|
|
|
|
|
|
|
max_groups = group_ids.max(dim=1)[0] + 1
|
|
|
max_group_size = max_groups.max().item()
|
|
|
|
|
|
|
|
|
|
|
|
new_x_list = []
|
|
|
new_mask_list = []
|
|
|
|
|
|
for b in range(batch_size):
|
|
|
|
|
|
unique_groups, inverse_indices = torch.unique(group_ids[b], return_inverse=True)
|
|
|
num_groups = len(unique_groups)
|
|
|
|
|
|
|
|
|
batch_new_x = torch.zeros(num_groups, hidden_dim, device=x.device)
|
|
|
group_counts = torch.zeros(num_groups, device=x.device)
|
|
|
|
|
|
|
|
|
batch_new_x = batch_new_x.index_add(0, inverse_indices, x[b])
|
|
|
group_counts = group_counts.index_add(0, inverse_indices, torch.ones(seq_len, device=x.device))
|
|
|
|
|
|
|
|
|
batch_new_x = batch_new_x / group_counts.unsqueeze(-1).clamp(min=1)
|
|
|
|
|
|
new_x_list.append(batch_new_x)
|
|
|
new_mask_list.append(torch.ones(num_groups, device=x.device))
|
|
|
|
|
|
|
|
|
max_new_len = max(t.size(0) for t in new_x_list)
|
|
|
padded_x_list = []
|
|
|
padded_mask_list = []
|
|
|
|
|
|
for batch_x, batch_mask in zip(new_x_list, new_mask_list):
|
|
|
pad_len = max_new_len - batch_x.size(0)
|
|
|
if pad_len > 0:
|
|
|
batch_x = torch.cat([batch_x, torch.zeros(pad_len, hidden_dim, device=x.device)], dim=0)
|
|
|
batch_mask = torch.cat([batch_mask, torch.zeros(pad_len, device=x.device)], dim=0)
|
|
|
padded_x_list.append(batch_x)
|
|
|
padded_mask_list.append(batch_mask)
|
|
|
|
|
|
new_x = torch.stack(padded_x_list)
|
|
|
valid_mask = torch.stack(padded_mask_list)
|
|
|
|
|
|
|
|
|
actual_len = valid_mask.sum(dim=1).max().long().item()
|
|
|
new_x = new_x[:, :actual_len]
|
|
|
valid_mask = valid_mask[:, :actual_len]
|
|
|
|
|
|
|
|
|
new_x = new_x + attn_output.mean(dim=1, keepdim=True).expand(-1, actual_len, -1) * 0.1
|
|
|
|
|
|
|
|
|
x = new_x
|
|
|
attention_mask = valid_mask
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
merge_mapping = {
|
|
|
'original_positions': torch.arange(seq_len, device=x.device),
|
|
|
'merged_groups': group_ids,
|
|
|
'group_sizes': None
|
|
|
}
|
|
|
|
|
|
|
|
|
merge_info.append({
|
|
|
'layer': i,
|
|
|
'original_len': seq_len,
|
|
|
'merged_len': actual_len,
|
|
|
'compression_ratio': seq_len / max(actual_len, 1),
|
|
|
'merge_threshold': layer_merge_threshold,
|
|
|
'avg_merge_prob': merge_probs.mean().item(),
|
|
|
'merge_mapping': merge_mapping
|
|
|
})
|
|
|
|
|
|
|
|
|
if i == len(self.layers) - 1:
|
|
|
boundary_pred = self.boundary_predictor(x)
|
|
|
char_type_pred = self.char_type_predictor(x)
|
|
|
boundary_predictions.append(boundary_pred)
|
|
|
char_type_predictions.append(char_type_pred)
|
|
|
|
|
|
|
|
|
if attention_mask is not None:
|
|
|
mask = attention_mask.unsqueeze(-1)
|
|
|
pooled = (x * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9)
|
|
|
else:
|
|
|
pooled = x.mean(dim=1)
|
|
|
|
|
|
return {
|
|
|
'last_hidden_state': x,
|
|
|
'pooled_output': pooled,
|
|
|
'all_hidden_states': all_hidden_states,
|
|
|
'boundary_predictions': boundary_predictions,
|
|
|
'char_type_predictions': char_type_predictions,
|
|
|
'boundary_logits': self.boundary_predictor(x),
|
|
|
'char_type_logits': self.char_type_predictor(x),
|
|
|
'merge_info': merge_info,
|
|
|
'attention_mask': attention_mask
|
|
|
}
|
|
|
|
|
|
|
|
|
class BoundaryAwareTokenizerModel(nn.Module):
|
|
|
"""
|
|
|
๋ฐ์ดํธ-๋ฌธ์ ๊ด๊ณ๋ฅผ ๋ช
์์ ์ผ๋ก ํ์ตํ๋ ํตํฉ ๋ชจ๋ธ
|
|
|
"""
|
|
|
|
|
|
def __init__(
|
|
|
self,
|
|
|
vocab_size: int = 260,
|
|
|
encoder_dims: List[int] = [512, 512, 640, 768, 768],
|
|
|
decoder_hidden: int = 768,
|
|
|
num_heads: int = 8,
|
|
|
num_decoder_layers: int = 6,
|
|
|
dropout: float = 0.1,
|
|
|
max_seq_len: int = 512
|
|
|
):
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
|
self.encoder = BoundaryAwareEncoder(
|
|
|
vocab_size, encoder_dims, num_heads, dropout, max_seq_len
|
|
|
)
|
|
|
|
|
|
|
|
|
self.decoder = TransformerDecoder(
|
|
|
vocab_size, decoder_hidden, num_heads, num_decoder_layers, dropout, max_seq_len
|
|
|
)
|
|
|
|
|
|
|
|
|
self.cross_attention = CrossAttention(encoder_dims[-1], num_heads, dropout)
|
|
|
|
|
|
def forward(
|
|
|
self,
|
|
|
input_ids: torch.Tensor,
|
|
|
attention_mask: Optional[torch.Tensor] = None,
|
|
|
boundary_labels: Optional[torch.Tensor] = None,
|
|
|
char_types: Optional[torch.Tensor] = None,
|
|
|
byte_counts: Optional[torch.Tensor] = None,
|
|
|
char_indices: Optional[torch.Tensor] = None,
|
|
|
decoder_input_ids: Optional[torch.Tensor] = None,
|
|
|
labels: Optional[torch.Tensor] = None,
|
|
|
use_cross_attention: bool = True
|
|
|
) -> Dict[str, torch.Tensor]:
|
|
|
|
|
|
|
|
|
encoder_outputs = self.encoder(
|
|
|
input_ids=input_ids,
|
|
|
boundary_labels=boundary_labels,
|
|
|
char_types=char_types,
|
|
|
byte_counts=byte_counts,
|
|
|
char_indices=char_indices,
|
|
|
attention_mask=attention_mask
|
|
|
)
|
|
|
|
|
|
encoder_hidden = encoder_outputs['last_hidden_state']
|
|
|
|
|
|
|
|
|
|
|
|
encoder_mask = encoder_outputs.get('attention_mask', attention_mask)
|
|
|
|
|
|
|
|
|
if decoder_input_ids is None and input_ids is not None:
|
|
|
decoder_input_ids = input_ids
|
|
|
|
|
|
decoder_outputs = self.decoder(
|
|
|
encoder_hidden,
|
|
|
decoder_input_ids,
|
|
|
encoder_mask
|
|
|
)
|
|
|
|
|
|
|
|
|
cross_attn_outputs = None
|
|
|
relation_logits = None
|
|
|
|
|
|
if use_cross_attention and decoder_outputs['hidden_states'] is not None:
|
|
|
decoder_hidden = decoder_outputs['hidden_states']
|
|
|
|
|
|
cross_attn_outputs = self.cross_attention(
|
|
|
query=decoder_hidden,
|
|
|
key=encoder_hidden,
|
|
|
query_mask=None,
|
|
|
key_mask=attention_mask
|
|
|
)
|
|
|
|
|
|
relation_logits = cross_attn_outputs['relation_logits']
|
|
|
|
|
|
|
|
|
enhanced_decoder = decoder_hidden + cross_attn_outputs['cross_attention']
|
|
|
decoder_outputs['logits'] = self.decoder.output_projection(enhanced_decoder)
|
|
|
|
|
|
|
|
|
total_loss = None
|
|
|
if labels is not None:
|
|
|
|
|
|
loss_fct = nn.CrossEntropyLoss(ignore_index=256)
|
|
|
recon_loss = loss_fct(
|
|
|
decoder_outputs['logits'].reshape(-1, decoder_outputs['logits'].size(-1)),
|
|
|
labels.reshape(-1)
|
|
|
)
|
|
|
|
|
|
total_loss = recon_loss
|
|
|
|
|
|
|
|
|
if boundary_labels is not None and 'boundary_logits' in encoder_outputs:
|
|
|
boundary_logits = encoder_outputs['boundary_logits']
|
|
|
|
|
|
logits_size = boundary_logits.size(0) * boundary_logits.size(1)
|
|
|
labels_size = boundary_labels.numel()
|
|
|
|
|
|
if logits_size == labels_size:
|
|
|
boundary_loss_fct = nn.CrossEntropyLoss(ignore_index=3)
|
|
|
boundary_loss = boundary_loss_fct(
|
|
|
boundary_logits.reshape(-1, 4),
|
|
|
boundary_labels.reshape(-1)
|
|
|
)
|
|
|
total_loss = total_loss + boundary_loss * 0.3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if char_types is not None and 'char_type_logits' in encoder_outputs:
|
|
|
char_type_logits = encoder_outputs['char_type_logits']
|
|
|
|
|
|
logits_size = char_type_logits.size(0) * char_type_logits.size(1)
|
|
|
labels_size = char_types.numel()
|
|
|
|
|
|
if logits_size == labels_size:
|
|
|
char_type_loss_fct = nn.CrossEntropyLoss(ignore_index=13)
|
|
|
char_type_loss = char_type_loss_fct(
|
|
|
char_type_logits.reshape(-1, 14),
|
|
|
char_types.reshape(-1)
|
|
|
)
|
|
|
total_loss = total_loss + char_type_loss * 0.2
|
|
|
|
|
|
|
|
|
|
|
|
if encoder_outputs.get('boundary_predictions') and boundary_labels is not None:
|
|
|
|
|
|
if 'boundary_loss_fct' in locals():
|
|
|
for boundary_pred in encoder_outputs['boundary_predictions']:
|
|
|
|
|
|
pred_batch_size = boundary_pred.size(0) * boundary_pred.size(1)
|
|
|
label_batch_size = boundary_labels.numel()
|
|
|
|
|
|
if pred_batch_size == label_batch_size:
|
|
|
aux_boundary_loss = boundary_loss_fct(
|
|
|
boundary_pred.reshape(-1, 4),
|
|
|
boundary_labels.reshape(-1)
|
|
|
)
|
|
|
total_loss = total_loss + aux_boundary_loss * 0.1
|
|
|
else:
|
|
|
|
|
|
continue
|
|
|
|
|
|
return {
|
|
|
'loss': total_loss,
|
|
|
'logits': decoder_outputs['logits'],
|
|
|
'encoder_hidden_states': encoder_hidden,
|
|
|
'decoder_hidden_states': decoder_outputs['hidden_states'],
|
|
|
'boundary_logits': encoder_outputs['boundary_logits'],
|
|
|
'char_type_logits': encoder_outputs['char_type_logits'],
|
|
|
'boundary_predictions': encoder_outputs.get('boundary_predictions'),
|
|
|
'relation_logits': relation_logits,
|
|
|
'cross_attention': cross_attn_outputs['cross_attention'] if cross_attn_outputs else None
|
|
|
} |