zcode commited on
Commit
b8b2212
1 Parent(s): 6981524

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +309 -0
README.md ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - fr
4
+ - en
5
+ ---
6
+
7
+ ---
8
+ language:
9
+ - en
10
+ - fr
11
+ ---
12
+
13
+ # Title-Paragraph Segmentation Model - ver 1.0
14
+
15
+ <!-- Provide a quick summary of what the model is/does. -->
16
+
17
+ Formal Content Segmentation Model that belongs to *first order segmentation* (FOS) model family. It performs
18
+ `title-paragraph separation` task.
19
+
20
+ Architecture:
21
+ - E5-base Cross Encoder
22
+
23
+ Dataset:
24
+ - Custom Constrative Title-Paragraph Dataset based off `wikitext`
25
+
26
+ Performance:
27
+ - 89% acc on test set
28
+
29
+
30
+ Broader context:
31
+
32
+ 1) The aim of FOS is to separate content types featured in raw instructured strings such as:
33
+ * text
34
+ * code
35
+ * tables
36
+ * list
37
+ * math formulas
38
+ * images
39
+
40
+
41
+ 2) This will enable further processings such as *second order segmentation* (SOS) that
42
+ aims at generating semantic frontiers i.e segmenting:
43
+ * plain text into knowledge units
44
+ * code into functional blocks
45
+ * math formulas blocks into equations
46
+ * objects/concepts within an image
47
+ * videos into timestamped chapters
48
+
49
+
50
+ ## Model Details
51
+
52
+ ### Direct Use
53
+
54
+ ###### Setup and Utilities
55
+
56
+ ```python
57
+ from transformers import XLMRobertaPreTrainedModel, XLMRobertaModel, AutoTokenizer
58
+ from nltk.tokenize import line_tokenize
59
+ import torch
60
+ import torch.nn as nn
61
+ import torch.nn.functional as F
62
+ from torch.utils.data import DataLoader
63
+ from datasets import Dataset
64
+
65
+
66
+ #Utility Functions
67
+
68
+
69
+ def get_default_device():
70
+ if torch.cuda.is_available():
71
+ return torch.device('cuda')
72
+ elif torch.backends.mps.is_available():
73
+ return torch.device('mps')
74
+ else:
75
+ return torch.device('cpu')
76
+
77
+ def to_device(data, device):
78
+ if isinstance(data, (list,tuple)):
79
+ return [to_device(x, device) for x in data]
80
+ elif isinstance(data, dict):
81
+ return {'input_ids':to_device(data['input_ids'],device),'attention_mask':to_device(data['attention_mask'],device)}
82
+ return data.to(device)
83
+
84
+ class DeviceDataLoader():
85
+ def __init__(self, dl, device):
86
+ self.dl = dl
87
+ self.device = device
88
+
89
+ def __iter__(self):
90
+ for b in self.dl:
91
+ yield to_device(b, self.device)
92
+
93
+ def __len__(self):
94
+ return len(self.dl)
95
+
96
+ class IsoBN(nn.Module):
97
+ def __init__(self, hidden_size):
98
+ """Init method"""
99
+ super().__init__()
100
+ self.register_parameter(name='cov', param=torch.nn.Parameter(torch.zeros(hidden_size, hidden_size)))
101
+ self.register_parameter(name='std', param=torch.nn.Parameter(torch.zeros(hidden_size)))
102
+
103
+ self.cov.requires_grad = False
104
+ self.std.requires_grad = False
105
+
106
+ def forward(self, input, momentum: float = 0.05, eps: float = 1e-3, beta: float = 0.5):
107
+ """Forward method"""
108
+ if self.training:
109
+ x = input.detach()
110
+ n = x.size(0)
111
+ mean = x.mean(dim=0)
112
+ y = x - mean.unsqueeze(0)
113
+ std = (y ** 2).mean(0) ** 0.5
114
+ cov = (y.t() @ y) / n
115
+ self.cov.data += momentum * (cov.data - self.cov.data)
116
+ self.std.data += momentum * (std.data - self.std.data)
117
+ corr = torch.clamp(self.cov / torch.ger(self.std, self.std), -1, 1)
118
+ gamma = (corr ** 2).mean(1)
119
+ denorm = (gamma * self.std)
120
+ scale = 1 / (denorm + eps) ** beta
121
+ E = torch.diag(self.cov).sum()
122
+ new_E = (torch.diag(self.cov) * (scale ** 2)).sum()
123
+ m = (E / (new_E + eps)) ** 0.5
124
+ scale *= m
125
+ return input * scale.unsqueeze(0).detach()
126
+
127
+ class e5_base_CTSEG(XLMRobertaPreTrainedModel):
128
+
129
+ def __init__(self, config):
130
+
131
+ super().__init__(config)
132
+
133
+ self.e5 = XLMRobertaModel(config).from_pretrained('intfloat/multilingual-e5-base')
134
+ self.dropout = nn.Dropout(0.5)
135
+ self.linear_1 = nn.Linear(768,256)
136
+ self.linear_2 = nn.Linear(256,128)
137
+ self.linear_3 = nn.Linear(128,2)
138
+ self.relu = nn.ReLU()
139
+ self.isobn = IsoBN(768)
140
+
141
+ def forward(self, sent):
142
+
143
+ sent['input_ids'] = sent['input_ids'].reshape(sent['input_ids'].shape[0],-1)
144
+ sent['attention_mask'] = sent['attention_mask'].reshape(sent['attention_mask'].shape[0],-1)
145
+
146
+ hs= self.e5(input_ids=sent['input_ids'], attention_mask=sent['attention_mask'])
147
+ cls_hs = hs.last_hidden_state[:, 0]
148
+ cls_hs = self.isobn(cls_hs)
149
+
150
+
151
+ out = self.linear_1(cls_hs)
152
+ out = self.relu(out)
153
+ out = self.dropout(out)
154
+ out = self.linear_2(out)
155
+ out = self.relu(out)
156
+ out = self.dropout(out)
157
+ out = self.linear_3(out)
158
+
159
+
160
+ return out
161
+
162
+
163
+ def training_step(self, sent, labels):
164
+ out = self.forward(sent)
165
+ loss = F.cross_entropy(out, labels)
166
+ return loss
167
+
168
+ def validation_step(self, sent, labels):
169
+ out = self.forward(sent)
170
+ loss = F.cross_entropy(out, labels)
171
+ acc = accuracy(out, labels)
172
+ return {'val_acc':acc,'val_loss':loss.detach()}
173
+
174
+ def validation_epoch_end(self, metrics):
175
+ batch_losses = [x['val_loss'] for x in metrics]
176
+ batch_accs = [x['val_acc'] for x in metrics]
177
+
178
+ epoch_loss = torch.stack(batch_losses).mean().item()
179
+ epoch_acc = torch.stack(batch_accs).mean().item()
180
+
181
+ return {'val_loss':epoch_loss, 'val_acc':epoch_acc}
182
+
183
+ def epoch_end(self, epoch, result):
184
+
185
+ print("Epoch [{}], train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}".format(
186
+ epoch, result['train_loss'], result['val_loss'], result['val_acc']))
187
+
188
+ def evaluate(self, val_loader):
189
+ self.eval()
190
+ metrics = [self.validation_step(sent,labels.type(torch.LongTensor).to(device, non_blocking=True)) for sent,labels in val_loader]
191
+ return self.validation_epoch_end(metrics)
192
+ def accuracy(out, labels):
193
+ return (out.argmax(dim=1) == labels).sum()/labels.numel()
194
+
195
+ ```
196
+
197
+ ```python
198
+ tokenizer = AutoTokenizer.from_pretrained('intfloat/multilingual-e5-base')
199
+ model = e5_base_CTSEG.from_pretrained('ProfessorBob/title-par-segmentation')
200
+ device = get_default_device()
201
+ to_device(model,device)
202
+ ```
203
+
204
+ ```python
205
+ def infer_block(
206
+ chunks,
207
+ batch_size: int = 8,
208
+ return_probability: bool = False,
209
+ tokenizer = tokenizer
210
+ ):
211
+ """ Bulk Infer function"""
212
+
213
+ tok_text_bulk = tokenizer(
214
+ ['query: ' + sent[0] +'[SEP]'+ sent[1] for sent in chunks],
215
+ padding='max_length',
216
+ truncation=True,
217
+ return_tensors='pt'
218
+ )
219
+ sentences = Dataset.from_dict({
220
+ 'input_ids': tok_text_bulk['input_ids'],
221
+ 'attention_mask': tok_text_bulk['attention_mask']
222
+ })
223
+ sentences.set_format(
224
+ 'torch',
225
+ columns=['input_ids','attention_mask']
226
+ )
227
+ sentences = DataLoader(
228
+ sentences,
229
+ batch_size=batch_size,
230
+ pin_memory=True
231
+ )
232
+ sentences = DeviceDataLoader(sentences, device)
233
+ preds = list()
234
+ model.eval()
235
+ with torch.no_grad():
236
+ for i, batch in enumerate(sentences):
237
+ out = model(batch)
238
+ if return_probability:
239
+ preds.extend((out.softmax(dim=1).cpu()[:, 1]).tolist())
240
+ else:
241
+ preds.extend(out.argmax(dim=1).cpu().tolist())
242
+
243
+ if device == torch.device('cuda'):
244
+ torch.cuda.empty_cache()
245
+ assert len(preds) == len(chunks)
246
+
247
+ return preds, out
248
+
249
+ def segmentation_pipeline(text):
250
+
251
+ block = line_tokenize(text)
252
+ chunks = [
253
+ (u, v) for u, v in zip(block[:-1], block[1:])
254
+ ]
255
+ preds, out = infer_block(chunks,return_probability=False)
256
+ cut_idx = [i+1 for i, value in enumerate(preds) if value == 1]
257
+ cut_idx = [0]+cut_idx+[len(block)]
258
+ seg = [block[cut_idx[i]:cut_idx[i+1]] for i in range(len(cut_idx)-1)]
259
+
260
+ return seg
261
+ ```
262
+
263
+ ###### Usage example
264
+
265
+
266
+ ```python
267
+
268
+ mixed_string = """
269
+
270
+ Ancient Foundations (3000 BCE - 600 CE)
271
+
272
+ In the dawn of human civilization, mathematics emerged as an essential tool for commerce, construction, and astronomy. Explore the mathematical innovations of ancient cultures such as the Babylonians, Egyptians, and Greeks, laying the groundwork for numerical systems, geometry, and the Pythagorean theorem.
273
+
274
+ The Golden Age of Islamic Mathematics (700 CE - 1300 CE)
275
+
276
+ Delve into the intellectual flourishing during the Islamic Golden Age, where scholars like Al-Khwarizmi and Omar Khayyam made groundbreaking contributions to algebra, trigonometry, and the development of algorithms. Discover how these advancements paved the way for the Renaissance in Europe.
277
+
278
+ """
279
+
280
+ ```
281
+
282
+ Generated Title-Paragraph Segmentation
283
+
284
+ ```console
285
+ Block 1
286
+ -----
287
+ Ancient Foundations (3000 BCE - 600 CE)
288
+
289
+ Block 2
290
+ -----
291
+ In the dawn of human civilization, mathematics emerged as an essential tool for commerce, construction, and astronomy. Explore the mathematical innovations of ancient cultures such as the Babylonians, Egyptians, and Greeks, laying the groundwork for numerical systems, geometry, and the Pythagorean theorem.
292
+
293
+ Block 3
294
+ -----
295
+ The Golden Age of Islamic Mathematics (700 CE - 1300 CE)
296
+
297
+ Block 4
298
+ -----
299
+ Delve into the intellectual flourishing during the Islamic Golden Age, where scholars like Al-Khwarizmi and Omar Khayyam made groundbreaking contributions to algebra, trigonometry, and the development of algorithms. Discover how these advancements paved the way for the Renaissance in Europe.
300
+
301
+ ...
302
+ Block 5
303
+ -----
304
+ Both of these approaches will give you a list of indices where the specified value occurs in your original list. Adjust the value you are searching for based on your specific use case.
305
+ ```
306
+
307
+
308
+
309
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->