Repository navigation
Expand file tree
/
Copy pathdraft_head.py
More file actions
109 lines (83 loc) · 2.11 KB
/
Copy pathdraft_head.py
File metadata and controls
109 lines (83 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# draft_head.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class DraftHead(nn.Module):
def __init__(
self,
hidden_size: int,
num_drafts: int = 4,
):
super().__init__()
self.hidden_size = hidden_size
self.num_drafts = num_drafts
# Draft generators
self.drafts = nn.ModuleList(
[
nn.Linear(hidden_size, hidden_size)
for _ in range(num_drafts)
]
)
# Confidence predictors
self.confidence_heads = nn.ModuleList(
[
nn.Linear(hidden_size, 1)
for _ in range(num_drafts)
]
)
# Final projection
self.output_proj = nn.Linear(
hidden_size,
hidden_size,
)
def forward(self, x):
"""
Args:
x: [batch, seq, hidden]
Returns:
output: [batch, seq, hidden]
confidences: [batch, seq, num_drafts]
"""
draft_outputs = []
confidence_scores = []
for draft_layer, conf_layer in zip(
self.drafts,
self.confidence_heads,
):
draft = draft_layer(x)
confidence = conf_layer(draft)
draft_outputs.append(draft)
confidence_scores.append(confidence)
drafts = torch.stack(
draft_outputs,
dim=2,
)
confidences = torch.cat(
confidence_scores,
dim=-1,
)
# Normalize confidence scores
confidences = F.softmax(
confidences,
dim=-1,
)
weighted_drafts = (
drafts
* confidences.unsqueeze(-1)
)
fused = weighted_drafts.sum(dim=2)
output = self.output_proj(fused)
return output, confidences
# Demo
x = torch.randn(
2, # batch
16, # sequence length
128, # hidden size
)
layer = DraftHead(
hidden_size=128,
num_drafts=4,
)
output, confidence = layer(x)
print(output.shape)
print(confidence.shape)