-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_crf_libraries.py
More file actions
188 lines (146 loc) · 5.72 KB
/
test_crf_libraries.py
File metadata and controls
188 lines (146 loc) · 5.72 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""
CRFライブラリ比較・テストスクリプト
利用可能なCRFライブラリ:
1. pytorch-crf (kmkurn/pytorch-crf)
2. TorchCRF (s14t/TorchCRF)
それぞれの特徴と使用方法を比較
"""
import torch
import torch.nn as nn
import numpy as np
print("🔍 CRF Libraries Comparison")
print("=" * 50)
# 1. pytorch-crf
try:
from pytorch_crf import CRF as PyTorchCRF
print("✅ pytorch-crf (0.7.2) - Available")
# Basic usage example
vocab_size = 10
num_tags = 5
seq_length = 20
batch_size = 2
# Create a simple CRF layer
crf_pytorch = PyTorchCRF(num_tags, batch_first=True)
# Sample emissions (batch_size, seq_length, num_tags)
emissions = torch.randn(batch_size, seq_length, num_tags)
# Sample tags (batch_size, seq_length)
tags = torch.randint(0, num_tags, (batch_size, seq_length))
# Sample mask (batch_size, seq_length)
mask = torch.ones(batch_size, seq_length, dtype=torch.bool)
# Calculate log-likelihood
log_likelihood = crf_pytorch(emissions, tags, mask=mask)
print(f" - Log likelihood: {log_likelihood.item():.4f}")
# Decode (Viterbi)
decoded = crf_pytorch.decode(emissions, mask=mask)
print(f" - Decoded sequence length: {len(decoded[0])}")
print(" 📋 pytorch-crf Features:")
print(" - Batch-first support ✅")
print(" - Mask support ✅")
print(" - Viterbi decoding ✅")
print(" - Well documented ✅")
print(" - AllenNLP compatible ✅")
except ImportError as e:
print(f"❌ pytorch-crf not available: {e}")
print()
# 2. TorchCRF
try:
from TorchCRF import CRF as TorchCRF
print("✅ TorchCRF (1.1.0) - Available")
# Create a TorchCRF layer
crf_torch = TorchCRF(num_tags)
# Sample data (TorchCRF uses seq_len, batch_size format by default)
emissions_torch = torch.randn(seq_length, batch_size, num_tags)
tags_torch = torch.randint(0, num_tags, (seq_length, batch_size))
# Calculate negative log-likelihood
loss = crf_torch(emissions_torch, tags_torch)
print(f" - Loss (negative log-likelihood): {loss.item():.4f}")
# Decode (Viterbi)
decoded_torch = crf_torch.decode(emissions_torch)
print(f" - Decoded sequence length: {len(decoded_torch[0])}")
print(" 📋 TorchCRF Features:")
print(" - Simple API ✅")
print(" - Sequence-first by default ✅")
print(" - Viterbi decoding ✅")
print(" - Lightweight ✅")
except ImportError as e:
print(f"❌ TorchCRF not available: {e}")
print()
# 3. Additional CRF options to consider
print("🔧 Additional CRF Implementation Options:")
print("=" * 50)
print("3. 📦 AllenNLP CRF:")
print(" - pip install allennlp")
print(" - from allennlp.modules import ConditionalRandomField")
print(" - Enterprise-grade, well-tested")
print(" - More heavyweight dependency")
print()
print("4. 🛠️ Custom CRF Implementation:")
print(" - Implement from scratch using PyTorch")
print(" - Full control over implementation")
print(" - Educational value")
print()
print("5. 📚 Flair CRF:")
print(" - pip install flair")
print(" - from flair.models import SequenceTagger")
print(" - NLP-focused, ready-to-use models")
print()
# Recommendation
print("💡 Recommendations for v0.3 Implementation:")
print("=" * 50)
print("🥇 1st Choice: pytorch-crf")
print(" - ✅ Most popular and well-maintained")
print(" - ✅ AllenNLP heritage (proven in research)")
print(" - ✅ Batch-first support (matches our data flow)")
print(" - ✅ Comprehensive mask support")
print(" - ✅ Clear documentation and examples")
print(" - ✅ Compatible with transformers workflow")
print()
print("🥈 2nd Choice: TorchCRF")
print(" - ✅ Simpler, more lightweight")
print(" - ✅ Good for quick prototyping")
print(" - ❌ Less documentation")
print(" - ❌ Sequence-first (requires data reshaping)")
print()
print("🥉 3rd Choice: Custom Implementation")
print(" - ✅ Full control and customization")
print(" - ✅ No external dependencies")
print(" - ❌ Time-consuming to implement correctly")
print(" - ❌ Potential bugs and edge cases")
print()
# Integration example for v0.3
print("🔧 Integration Code Example (pytorch-crf):")
print("=" * 50)
integration_code = '''
# v0.3 Enhanced Model with pytorch-crf
from pytorch_crf import CRF
class BiLSTMCRFHead(nn.Module):
def __init__(self, hidden_size=768, lstm_hidden=256, num_labels=3):
super().__init__()
# BiLSTM
self.bilstm = nn.LSTM(hidden_size, lstm_hidden,
batch_first=True, bidirectional=True)
# CRF emission layer
self.emission = nn.Linear(lstm_hidden * 2, num_labels)
# CRF layer (pytorch-crf)
self.crf = CRF(num_labels, batch_first=True)
def forward(self, sequence_output, attention_mask, labels=None):
# BiLSTM processing
lstm_out, _ = self.bilstm(sequence_output)
# CRF emissions
emissions = self.emission(lstm_out)
if labels is not None:
# Training: compute loss
return -self.crf(emissions, labels, mask=attention_mask)
else:
# Inference: decode best path
return self.crf.decode(emissions, mask=attention_mask)
'''
print(integration_code)
print("🎯 Next Steps for v0.3 Implementation:")
print("=" * 50)
print("1. ✅ Install pytorch-crf (completed)")
print("2. 🔄 Update fine_tuning_v3.py to use pytorch-crf")
print("3. 🔄 Create BIO label generation for training data")
print("4. 🔄 Integrate CRF loss with weighted position loss")
print("5. 🔄 Test CRF-enhanced model training")
print("6. 📊 Evaluate End Position accuracy improvement")