PowerMachine commited on
Commit
b714048
·
verified ·
1 Parent(s): c23c9ff

V6.5-7ds cleanup: remove legacy src/bigru_t/data/data_augmentation.py

Browse files
Files changed (1) hide show
  1. src/bigru_t/data/data_augmentation.py +0 -161
src/bigru_t/data/data_augmentation.py DELETED
@@ -1,161 +0,0 @@
1
- """data_augmentation.py — Data Augmentation para BiGRU_T_version V6.
2
-
3
- Adaptado de gru-ring-v13-9-2/source/xavante_work/flexnet/data_augmentation.py.
4
-
5
- Estratégias:
6
- 1. Synonym replacement (placeholder — usa mapeamento estático simples)
7
- 2. Random deletion (remove tokens com prob p)
8
- 3. Random swap (troca 2 tokens de posição)
9
- 4. Token dropout (substitui por PAD com prob p)
10
- 5. Back-translation simulada (aplica ruído gaussiano nos embeddings)
11
- 6. Mixup (combina 2 samples: x_mix = λ·x_1 + (1-λ)·x_2)
12
-
13
- V6 melhoria vs V13.9.2:
14
- * Vetorização total (sem loops Python sobre tokens)
15
- * Mixup com λ ~ Beta(α, α) — diferenciável
16
- * Compatível com tokens int (não altera vocab) para estratégias 1-4
17
- * Compatível com embeddings (float) para estratégias 5-6
18
- """
19
- from __future__ import annotations
20
-
21
- import torch
22
- import torch.nn.functional as F
23
- from typing import Optional
24
-
25
-
26
- def random_deletion_tokens(
27
- input_ids: torch.Tensor,
28
- pad_id: int = 0,
29
- p: float = 0.1,
30
- ) -> torch.Tensor:
31
- """Deleta tokens aleatoriamente (substitui por PAD).
32
-
33
- Args:
34
- input_ids: (batch, T) — tokens int
35
- pad_id: ID do token PAD
36
- p: probabilidade de deletar cada token
37
-
38
- Returns:
39
- (batch, T) — tokens com alguns substituídos por pad_id
40
- """
41
- if p <= 0:
42
- return input_ids
43
- mask = torch.bernoulli(torch.full_like(input_ids, p, dtype=torch.float)).bool()
44
- return input_ids.masked_fill(mask, pad_id)
45
-
46
-
47
- def random_swap_tokens(
48
- input_ids: torch.Tensor,
49
- n_swaps: int = 1,
50
- ) -> torch.Tensor:
51
- """Troca n pares de tokens de posição (por batch).
52
-
53
- Args:
54
- input_ids: (batch, T) — tokens int
55
- n_swaps: nº de trocas por sample
56
- """
57
- if n_swaps <= 0:
58
- return input_ids
59
- batch, T = input_ids.shape
60
- out = input_ids.clone()
61
- for _ in range(n_swaps):
62
- i = torch.randint(0, T, (batch,), device=input_ids.device)
63
- j = torch.randint(0, T, (batch,), device=input_ids.device)
64
- # Vectorized swap
65
- rows = torch.arange(batch, device=input_ids.device)
66
- tmp = out[rows, i].clone()
67
- out[rows, i] = out[rows, j]
68
- out[rows, j] = tmp
69
- return out
70
-
71
-
72
- def token_dropout(
73
- input_ids: torch.Tensor,
74
- pad_id: int = 0,
75
- p: float = 0.1,
76
- ) -> torch.Tensor:
77
- """Token dropout — alias para random_deletion_tokens (mesma semântica)."""
78
- return random_deletion_tokens(input_ids, pad_id=pad_id, p=p)
79
-
80
-
81
- def embedding_noise(
82
- embeddings: torch.Tensor,
83
- noise_std: float = 0.01,
84
- ) -> torch.Tensor:
85
- """Adiciona ruído gaussiano aos embeddings (back-translation simulada).
86
-
87
- Args:
88
- embeddings: (batch, T, d)
89
- noise_std: desvio padrão do ruído
90
- """
91
- if noise_std <= 0:
92
- return embeddings
93
- noise = torch.randn_like(embeddings) * noise_std
94
- return embeddings + noise
95
-
96
-
97
- def mixup(
98
- x: torch.Tensor,
99
- y: torch.Tensor,
100
- alpha: float = 0.2,
101
- num_classes: Optional[int] = None,
102
- ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, float]:
103
- """Mixup: x_mix = λ·x_1 + (1-λ)·x_2, y_mix = λ·y_1 + (1-λ)·y_2.
104
-
105
- Args:
106
- x: (batch, ...) — features (tokens ou embeddings)
107
- y: (batch,) ou (batch, C) — labels (int ou one-hot)
108
- alpha: parâmetro da Beta(α, α) para amostrar λ
109
- num_classes: nº de classes (necessário se y for int)
110
-
111
- Returns:
112
- x_mixed, y_mixed, perm, lam
113
- """
114
- if alpha <= 0:
115
- if y.dim() == 1 and num_classes is not None:
116
- y_oh = F.one_hot(y, num_classes=num_classes).float()
117
- return x, y_oh, torch.arange(x.size(0), device=x.device), 1.0
118
- return x, y.float() if y.dim() == 1 else y, torch.arange(x.size(0), device=x.device), 1.0
119
-
120
- # λ ~ Beta(α, α)
121
- lam = float(torch.distributions.Beta(alpha, alpha).sample().item())
122
- batch = x.size(0)
123
- perm = torch.randperm(batch, device=x.device)
124
- x_mixed = lam * x + (1.0 - lam) * x[perm]
125
-
126
- # y_mixed
127
- if y.dim() == 1 and num_classes is not None:
128
- y_oh = F.one_hot(y, num_classes=num_classes).float()
129
- y_perm_oh = F.one_hot(y[perm], num_classes=num_classes).float()
130
- y_mixed = lam * y_oh + (1.0 - lam) * y_perm_oh
131
- else:
132
- y_mixed = lam * y.float() + (1.0 - lam) * y[perm].float()
133
-
134
- return x_mixed, y_mixed, perm, lam
135
-
136
-
137
- def augment_batch(
138
- input_ids: torch.Tensor,
139
- pad_id: int = 0,
140
- p_delete: float = 0.1,
141
- n_swaps: int = 1,
142
- p_dropout: float = 0.05,
143
- ) -> torch.Tensor:
144
- """Pipeline de augmentação para tokens (sem mudar vocab).
145
-
146
- Aplica: random_deletion → random_swap → token_dropout (sequencialmente).
147
- """
148
- out = random_deletion_tokens(input_ids, pad_id=pad_id, p=p_delete)
149
- out = random_swap_tokens(out, n_swaps=n_swaps)
150
- out = token_dropout(out, pad_id=pad_id, p=p_dropout)
151
- return out
152
-
153
-
154
- __all__ = [
155
- "random_deletion_tokens",
156
- "random_swap_tokens",
157
- "token_dropout",
158
- "embedding_noise",
159
- "mixup",
160
- "augment_batch",
161
- ]