-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathav-w-siamese-sbert.html
More file actions
542 lines (504 loc) · 19.3 KB
/
av-w-siamese-sbert.html
File metadata and controls
542 lines (504 loc) · 19.3 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Transformer-Based Authorship Verification Research</title>
<!-- Import Mermaid -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.9.0/mermaid.min.js"></script>
<!-- Import MathJax -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script
id="MathJax-script"
async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"
></script>
<!-- Prism CSS -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css"
rel="stylesheet"
/>
<!-- loading overlay styles -->
<link
rel="stylesheet"
type="text/css"
href="stylesheets/loading-overlay.css"
/>
<!-- Optional: Choose a different theme like prism-okaidia -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-okaidia.min.css"
rel="stylesheet"
/>
<script>
document.addEventListener("DOMContentLoaded", () => {
mermaid.initialize({
startOnLoad: true,
theme: "default",
// Adjust these settings for your diagram
flowchart: {
useMaxWidth: true,
htmlLabels: true,
curve: "cardinal",
},
});
});
</script>
<link
rel="stylesheet"
type="text/css"
href="stylesheets/av-w-siamese-sbert.css"
/>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script
async
src="https://www.googletagmanager.com/gtag/js?id=G-BYFQ413ZGH"
></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-BYFQ413ZGH");
</script>
</head>
<body>
<!-- Loading overlay -->
<div class="loading-overlay"></div>
<!-- extremely minimal back to home navbar -->
<!-- sticky and with project name -->
<!-- dark color -->
<nav class="navbar">
<a href="/" title="ZacBolton.io">
<img src="assets/home_icon.svg" alt="Home" width="100" />
</a>
<!-- project name -->
<h1 class="navbar-title">Siamese SBERT AV</h1>
</nav>
<div class="hero">
<img
class="hero-image"
src="assets/figures/full_run_all_train_losses.png"
/>
</div>
<main class="main">
<h1>Transformer-Based Authorship Verification Research</h1>
<div class="abstract">
<strong>Overview:</strong> In this research, I implemented
<a href="https://api.semanticscholar.org/CorpusID:264441704"
>Ibrahim et al.'s (2023)</a
>
state-of-the-art Siamese SBERT architecture for historical document
verification. I achieved near-perfect metrics across multiple distorted
views while handling genre/topic bias through novel dataset construction
and text distortion techniques from
<a href="https://aclanthology.org/E17-1107">Stamatatos (2017)</a>.
</div>
<div class="video-section">
<h3>Executive Summary Video</h3>
<div class="video-container">
<iframe
src="https://www.youtube.com/embed/nMFS9qXkniA?si=K2rJYFKs7zt6OZ8z"
title="Transformer-Based Authorship Verification - Executive Summary"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
></iframe>
</div>
<div class="video-caption">
A comprehensive overview of the Siamese SBERT architecture implementation for authorship verification,
including key findings from the analysis of the Pickett love letters.
</div>
</div>
<div class="context-box">
<h3>Historical Context</h3>
<p>
This research tackles a
<a href="https://www.jstor.org/stable/27740463"
>longstanding historical question</a
>
concerning love letters attributed to Confederate General George E.
Pickett, published posthumously by his wife LaSalle Corbell Pickett.
As a prolific author with no other verified works by the General
available, the letters' authenticity has been debated by historians.
This presents an ideal case for authorship verification (AV) -
determining if two texts share the same author.
</p>
</div>
<h2>Architecture & Implementation</h2>
<div class="figure">
<pre class="mermaid">
flowchart TD
subgraph "<strong>(B)</strong> SBERT Training"
lilat["LILA<sub>train</sub>"] --> batch1
batch1["
$$B = \{(c_{\text{a}}, c_{\text{o}})_i\}_{i=1}^{\text{batch\_size}}$$
"] --> ca1["$$C_{\text{a},i}$$"]
batch1 --> ca2["$$C_{\text{o},i}$$"]
ca1 --> bert1[SBERT]
ca2 --> bert2[SBERT]
bert1 --> pool1[Mean Pooling]
bert2 --> pool2[Mean Pooling]
pool1 --> ea1["$$E_{\text{a},i}$$"]
pool2 --> eo1["$$E_{\text{o},i}$$"]
ea1 --> contrastive[Contrastive Loss]
eo1 --> contrastive
end
subgraph "<strong>(A)</strong> SBERT at Inference"
lilai["LILA<sub>infer</sub>"] --> batch2
batch2["
$$B = \{(c_{\text{a}}, c_{\text{o}})_i\}_{i=1}^{\text{batch\_size}}$$
"] --> ca3["$$C_{\text{a},i}$$"]
batch2 --> ca4["$$C_{\text{o},i}$$"]
ca3 --> bert3[SBERT]
ca4 --> bert4[SBERT]
bert3 --> pool3[Mean Pooling]
bert4 --> pool4[Mean Pooling]
pool3 --> ea2["$$E_{\text{a},i}$$"]
pool4 --> eo2["$$E_{\text{o},i}$$"]
ea2 --> cos["Cosine Similarity"]
eo2 --> cos
cos --> rescale["Rescaling"]
rescale --> sim["Similarity Score [0, 1]"]
end
style contrastive fill:#9999ff
style contrastive color:#000000
style cos fill:#ff9999
style cos color:#000000
style rescale fill:#ff9999
style rescale color:#000000
style sim fill:#ff9999
style sim color:#000000
style lilat fill:#999999
style lilat color:#000000
style lilai fill:#999999
style lilai color:#000000
</pre>
<div class="figure-caption">
<strong>Figure 1:</strong> Model architecture showing (A) inference
time configuration with cosine similarity output and (B) training time
configuration with contrastive loss. Both utilize identical BERT
encoders and mean pooling layers.
</div>
</div>
<div class="implementation-note">
<strong>Key Technical Innovation:</strong> Discovered and resolved a
contradiction in Ibrahim et al.'s architecture where the stated
contrastive loss function was incompatible with their output layer
configuration. Successfully implemented a modified architecture
maintaining SOTA performance while ensuring theoretical soundness.
</div>
<h2>Modified Contrastive Loss Implementation</h2>
<p>
Building on
<a href="https://doi.org/10.1109/CVPR.2006.100"
>Hadsell, Chopra, and LeCun's foundational work (2006)</a
>, implemented a modified contrastive loss function that allows for more
nuanced control over embedding space distances. The implementation uses
separate margin parameters for same-author and different-author pairs,
enabling finer control over the model's discriminative behavior.
</p>
<div style="margin: 20px 0; text-align: center">
For same-author pairs: \[y_{same} = y \cdot F_{relu}(\text{margin}_s -
x)^2\] For different-author pairs: \[y_{diff} = (1-y) \cdot F_{relu}(x -
\text{margin}_d)^2\] Final loss: \[L = 0.5(y_{same} + y_{diff})\] Where
\(x\) is the cosine similarity scaled to [0,1], \(y\) is the ground
truth (1 for same-author, 0 for different-author), \(F_{relu}\) is the
rectified linear unit function, and \(\text{margin}_s\) and
\(\text{margin}_d\) control the boundaries of the loss-accruing regions
in the embedding space for same-author and different-author pairs
respectively.
</div>
<div class="implementation-note">
<strong>Implementation Note:</strong> While traditional modified
contrastive loss implementations typically work with a similarity range
of [-2, 0], I maintained a [0, 1] range through cosine similarity
rescaling. This preserves the relative embedding distances crucial for
contrastive learning while allowing for seamless integration with the
broader architecture. This modification demonstrates the flexibility of
contrastive learning approaches, as relative distances, not absolute
scales, drive the learning dynamics.
</div>
<div class="code-block">
<pre><code class="language-python">class ModifiedContrastiveLoss(nn.Module):
def forward(self, anchor, other, labels):
# Calculate cosine similarity and rescale to [0,1]
similarities = (F.cosine_similarity(anchor, other) + 1) / 2
# Modified loss with separate margins for same/different pairs
same_author_loss = labels.float() * \
F.relu(self.margin_s - similarities).pow(2)
diff_author_loss = (1 - labels).float() * \
F.relu(similarities - self.margin_d).pow(2)
# Balance contribution of positive and negative pairs
losses = 0.5 * (same_author_loss + diff_author_loss)
return losses.mean()</code></pre>
</div>
<div class="implementation-note">
<strong>Enhancement:</strong> This modified implementation allows for
flexible tuning of both the "push" and "pull" forces in the embedding
space, leading to more stable training and better generalization.
</div>
<h2>Dataset Construction & Preprocessing</h2>
<p>
Developed LILA (Love letters, Imposters, LaSalle Augmented), a carefully
balanced dataset with:
</p>
<ul>
<li>278,917 words of known authorial work</li>
<li>627,937 words of stylistically matched "imposters"</li>
<li>Rigorous genre balancing within 10% target ratios</li>
<li>Four distorted views using Stamatatos' text distortion</li>
</ul>
<div class="figure">
<pre class="mermaid">
flowchart LR
subgraph Disk["On-Disk Preprocessing"]
style Disk fill:#e6f3ff,stroke:#333
%% A -> B (subgraph) -> C
A[("Raw Text Files")] --> B
%% Turn B into a subgraph named "Text Normalization"
subgraph B["Text Normalization"]
D[Lowercase] --> E[Collapse Whitespace] --> F[Strip Special Characters]
end
B --> C{"Distorted View Generation"}
C --> |"$$k_{view} = len(W_{LILA})$$"|G1[("Undistorted View")]
C --> |"$$k_{view} = 20000$$"|G2[("Lightly Distorted")]
C --> |"$$k_{view} = 3000$$"|G3[("Moderately Distorted")]
C --> |"$$k_{view} = 300$$"|G4[("Heavily Distorted")]
end
subgraph LILA["LILADataset"]
style LILA fill:#ffe6e6,stroke:#333
G1 & G2 & G3 & G4 --> H[["Tokenization"]]
H --> I[["Fixed-Length Chunking"]]
I --> t["Generate K-Fold Train/Val Pairs"]
I --> i["Generate Inference Pairs"]
end
classDef storage fill:#ff9,stroke:#333
classDef process fill:#fff,stroke:#333
classDef decision fill:#9cf,stroke:#333
class A,G1,G2,G3,G4 storage
class B,D,E,F process
class C decision
</pre>
<div class="figure-caption">
<strong>Figure 2:</strong> LILA data processing pipeline showing
on-disk preprocessing and LILADataset construction.
</div>
</div>
<div class="code-block">
<h3>Text Distortion Implementation</h3>
<pre><code class="language-python">def dv_ma(text, W_k):
"""
Replace words not in W_k (k most frequent words) with
asterisk strings of equal length.
"""
words = text.split()
for i, word in enumerate(words):
if (word.lower() in W_k):
continue
else:
words[i] = re.sub(r'[^\d]', '*', word)
words[i] = re.sub(r'[\d]', '#', words[i])
return ' '.join(words)</code></pre>
</div>
<h2>Results & Analysis</h2>
<div class="figure">
<img src="assets/figures/full_run_all_train_losses.png" />
<div class="figure-caption">
<strong>Figure 3:</strong> Loss plots for all five folds across four
views, showing clear convergent behavior with stability increasing as
distortion level increases.
</div>
</div>
<div class="table-container">
<table>
<thead>
<tr>
<th>View</th>
<th>AUC</th>
<th>C@1</th>
<th>F1</th>
<th>F0.5u</th>
</tr>
</thead>
<tbody>
<tr>
<td>Undistorted</td>
<td>1.000 ± 0.000</td>
<td>0.998 ± 0.003</td>
<td>0.998 ± 0.003</td>
<td>0.996 ± 0.005</td>
</tr>
<tr>
<td>k=20,000</td>
<td>1.000 ± 0.000</td>
<td>0.996 ± 0.007</td>
<td>0.996 ± 0.006</td>
<td>0.992 ± 0.012</td>
</tr>
<tr>
<td>k=3,000</td>
<td>1.000 ± 0.000</td>
<td>0.994 ± 0.003</td>
<td>0.994 ± 0.003</td>
<td>0.990 ± 0.006</td>
</tr>
<tr>
<td>k=300</td>
<td>0.991 ± 0.001</td>
<td>0.964 ± 0.008</td>
<td>0.966 ± 0.007</td>
<td>0.943 ± 0.010</td>
</tr>
</tbody>
</table>
</div>
<h2>External Validation on VALLA Dataset</h2>
<p>
To validate the model's generalizability, I evaluated performance on the
PAN20 sub-split of the
<a href="https://arxiv.org/abs/2209.06869">VALLA benchmark</a>, a
comprehensive AV benchmark introduced by Tyo et al. (2022). My
implementation achieved competitive results against
<a href="https://ceur-ws.org/Vol-2936/paper-147.pdf">PAN 2020</a> shared
task participants:
</p>
<!-- VALLA Benchmark Table -->
<div class="table-container">
<table>
<thead>
<tr>
<th>Model</th>
<th>Overall Score</th>
<th>Training Data</th>
</tr>
</thead>
<tbody>
<tr>
<td>PAN20 Winner (Boenninghoff et al.)</td>
<td>0.897</td>
<td>PAN20-small</td>
</tr>
<tr>
<td>Our Implementation (30 epochs)</td>
<td>0.801</td>
<td>VALLA (more challenging)</td>
</tr>
<tr>
<td>PAN20 Baseline</td>
<td>0.747</td>
<td>PAN20-large</td>
</tr>
</tbody>
</table>
</div>
<div class="implementation-note">
<strong>Note:</strong> Despite using VALLA's more challenging
formulation which removes genre/topic/class-balance bias, my
implementation achieved the equivalent of a 5th place team in PAN 2020
models using the same raw data, demonstrating strong generalization
capability.
</div>
<h2>Inference Results on the Love Letters</h2>
<p>
The model's analysis of the letters shows a consistent and strong
pattern of attribution to LaSalle's authorship across all distortion
views:
</p>
<!-- Love Letters Analysis Table -->
<div class="table-container">
<table>
<thead>
<tr>
<th>Distorted View</th>
<th>Mean Similarity</th>
<th>Same-Author</th>
<th>Different-Author</th>
<th>Undecided</th>
</tr>
</thead>
<tbody>
<tr>
<td>Undistorted</td>
<td>0.709 ± 0.298</td>
<td>74.4%</td>
<td>24.8%</td>
<td>0.9%</td>
</tr>
<tr>
<td>k=20,000</td>
<td>0.661 ± 0.296</td>
<td>68.2%</td>
<td>27.6%</td>
<td>4.2%</td>
</tr>
<tr>
<td>k=3,000</td>
<td>0.598 ± 0.334</td>
<td>60.1%</td>
<td>34.7%</td>
<td>5.1%</td>
</tr>
<tr>
<td>k=300</td>
<td>0.564 ± 0.272</td>
<td>57.8%</td>
<td>37.5%</td>
<td>4.7%</td>
</tr>
</tbody>
</table>
</div>
<div class="figure">
<img
src="assets/figures/love_letters_inference_dist_of_similarity_scores_over_views.png"
/>
<div class="figure-caption">
<strong>Figure 4:</strong> Distribution of similarity scores across
different distortion views for the love letters. Decision thresholds
p1 and p2 shown as dashed lines.
</div>
</div>
<div class="implementation-note">
<strong>Key Finding:</strong> The model demonstrates strong attribution
to LaSalle's authorship, with 74.4% same-author predictions in the
undistorted view. This signal persists even under heavy distortion
(k=300), where topic and content-specific features are largely masked,
indicating deep stylistic similarities between the letters and LaSalle's
known works. Notably, the highest-similarity passages contain
anachronistic references
<a href="https://www.jstor.org/stable/4248894"
>independently identified</a
>
by historians as problematic, providing computational support for
historical observations about the letters' authenticity.
</div>
<h2>Technical Infrastructure</h2>
<ul>
<li>
AWS EC2 g5.xlarge deployment (4 vCPUs, 16GB RAM, NVIDIA A10G GPU)
</li>
<li>PyTorch with HuggingFace Transformers</li>
<li>Custom dataset class handling 10M+ words</li>
<li>Gradient accumulation for memory efficiency</li>
<li>K-Folds cross-validation with balanced splits</li>
</ul>
<div class="figure">
<img src="assets/figures/full_run_fold_0_eval_cm_true.png" />
<div class="figure-caption">
<strong>Figure 5:</strong> Confusion matrices across distortion views
showing consistent discriminative ability even with heavy distortion
(k=300).
</div>
</div>
</main>
<!-- Prism JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<!-- Language support -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-css.min.js"></script>
<!-- Loading script -->
<script type="text/javascript" src="scripts/loading-overlay.js"></script>
</body>
</html>