-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathword2vec.rs
246 lines (208 loc) · 7.86 KB
/
word2vec.rs
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
//! Reader and writer for the word2vec binary format.
//!
//! Embeddings in the word2vec binary format are these formats are
//! read as follows:
//!
//! ```
//! use std::fs::File;
//! use std::io::BufReader;
//!
//! use finalfusion::prelude::*;
//!
//! let mut reader = BufReader::new(File::open("testdata/similarity.bin").unwrap());
//!
//! // Read the embeddings.
//! let embeddings = Embeddings::read_word2vec_binary(&mut reader)
//! .unwrap();
//!
//! // Look up an embedding.
//! let embedding = embeddings.embedding("Berlin");
//! ```
use std::io::{BufRead, Write};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use ndarray::{Array2, Axis, CowArray};
use crate::chunks::norms::NdNorms;
use crate::chunks::storage::{NdArray, Storage, StorageViewMut};
use crate::chunks::vocab::{SimpleVocab, Vocab};
use crate::embeddings::Embeddings;
use crate::error::{Error, Result};
use crate::util::{l2_normalize_array, read_number, read_string};
/// Method to construct `Embeddings` from a word2vec binary file.
///
/// This trait defines an extension to `Embeddings` to read the word embeddings
/// from a file in word2vec binary format.
pub trait ReadWord2Vec<R>
where
Self: Sized,
R: BufRead,
{
/// Read the embeddings from the given buffered reader.
fn read_word2vec_binary(reader: &mut R) -> Result<Self>;
/// Read the embeddings from the given buffered reader.
///
/// In contrast to `read_word2vec_binary`, this constructor does
/// not fail if a token contains invalid UTF-8. Instead, it will
/// replace invalid UTF-8 characters by the replacement character.
fn read_word2vec_binary_lossy(reader: &mut R) -> Result<Self>;
}
impl<R> ReadWord2Vec<R> for Embeddings<SimpleVocab, NdArray>
where
R: BufRead,
{
fn read_word2vec_binary(reader: &mut R) -> Result<Self> {
let (_, vocab, mut storage, _) =
Embeddings::read_word2vec_binary_raw(reader, false)?.into_parts();
let norms = l2_normalize_array(storage.view_mut());
Ok(Embeddings::new(None, vocab, storage, NdNorms::new(norms)))
}
fn read_word2vec_binary_lossy(reader: &mut R) -> Result<Self> {
let (_, vocab, mut storage, _) =
Embeddings::read_word2vec_binary_raw(reader, true)?.into_parts();
let norms = l2_normalize_array(storage.view_mut());
Ok(Embeddings::new(None, vocab, storage, NdNorms::new(norms)))
}
}
/// Read raw, unnormalized embeddings.
pub(crate) trait ReadWord2VecRaw<R>
where
Self: Sized,
R: BufRead,
{
/// Read the embeddings from the given buffered reader.
fn read_word2vec_binary_raw(reader: &mut R, lossy: bool) -> Result<Self>;
}
impl<R> ReadWord2VecRaw<R> for Embeddings<SimpleVocab, NdArray>
where
R: BufRead,
{
fn read_word2vec_binary_raw(reader: &mut R, lossy: bool) -> Result<Self> {
let n_words = read_number(reader, b' ')?;
let embed_len = read_number(reader, b'\n')?;
let mut matrix = Array2::zeros((n_words, embed_len));
let mut words = Vec::with_capacity(n_words);
for idx in 0..n_words {
let word = read_string(reader, b' ', lossy)?;
let word = word.trim();
words.push(word.to_owned());
let mut embedding = matrix.index_axis_mut(Axis(0), idx);
reader
.read_f32_into::<LittleEndian>(
embedding.as_slice_mut().expect("Matrix not contiguous"),
)
.map_err(|e| Error::read_error("Cannot read word embedding", e))?;
}
Ok(Embeddings::new_with_maybe_norms(
None,
SimpleVocab::new(words),
NdArray::new(matrix),
None,
))
}
}
/// Method to write `Embeddings` to a word2vec binary file.
///
/// This trait defines an extension to `Embeddings` to write the word embeddings
/// to a file in word2vec binary format.
pub trait WriteWord2Vec<W>
where
W: Write,
{
/// Write the embeddings from the given writer.
///
/// If `unnormalize` is `true`, the norms vector is used to
/// restore the original vector magnitudes.
fn write_word2vec_binary(&self, w: &mut W, unnormalize: bool) -> Result<()>;
}
impl<W, V, S> WriteWord2Vec<W> for Embeddings<V, S>
where
W: Write,
V: Vocab,
S: Storage,
{
fn write_word2vec_binary(&self, w: &mut W, unnormalize: bool) -> Result<()>
where
W: Write,
{
writeln!(w, "{} {}", self.vocab().words_len(), self.dims())
.map_err(|e| Error::write_error("Cannot write word embedding matrix shape", e))?;
for (word, embed_norm) in self.iter_with_norms() {
write!(w, "{} ", word).map_err(|e| Error::write_error("Cannot write token", e))?;
let embed = if unnormalize {
CowArray::from(embed_norm.into_unnormalized())
} else {
embed_norm.embedding
};
for v in embed.view() {
w.write_f32::<LittleEndian>(*v)
.map_err(|e| Error::write_error("Cannot write embedding component", e))?;
}
w.write_all(&[0x0a])
.map_err(|e| Error::write_error("Cannot write embedding separator", e))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom};
use crate::chunks::storage::StorageView;
use crate::chunks::vocab::Vocab;
use crate::compat::word2vec::{ReadWord2Vec, ReadWord2VecRaw, WriteWord2Vec};
use crate::embeddings::Embeddings;
#[test]
fn fails_on_invalid_utf8() {
let f = File::open("testdata/utf8-incomplete.bin").unwrap();
let mut reader = BufReader::new(f);
assert!(Embeddings::read_word2vec_binary(&mut reader).is_err());
}
#[test]
fn read_lossy() {
let f = File::open("testdata/utf8-incomplete.bin").unwrap();
let mut reader = BufReader::new(f);
let embeds = Embeddings::read_word2vec_binary_lossy(&mut reader).unwrap();
let words = embeds.vocab().words();
assert_eq!(words, &["meren", "zee�n", "rivieren"]);
}
#[test]
fn test_read_word2vec_binary() {
let f = File::open("testdata/similarity.bin").unwrap();
let mut reader = BufReader::new(f);
let embeddings = Embeddings::read_word2vec_binary_raw(&mut reader, false).unwrap();
assert_eq!(41, embeddings.vocab().words_len());
assert_eq!(100, embeddings.dims());
}
#[test]
fn test_word2vec_binary_roundtrip() {
let mut reader = BufReader::new(File::open("testdata/similarity.bin").unwrap());
let mut check = Vec::new();
reader.read_to_end(&mut check).unwrap();
// Read embeddings.
reader.seek(SeekFrom::Start(0)).unwrap();
let embeddings = Embeddings::read_word2vec_binary_raw(&mut reader, false).unwrap();
// Write embeddings to a byte vector.
let mut output = Vec::new();
embeddings
.write_word2vec_binary(&mut output, false)
.unwrap();
assert_eq!(check, output);
}
#[test]
fn test_word2vec_binary_write_unnormalized() {
let mut reader = BufReader::new(File::open("testdata/similarity.bin").unwrap());
// Read unnormalized embeddings
let embeddings_check = Embeddings::read_word2vec_binary_raw(&mut reader, false).unwrap();
// Read normalized embeddings.
reader.seek(SeekFrom::Start(0)).unwrap();
let embeddings = Embeddings::read_word2vec_binary(&mut reader).unwrap();
// Write embeddings to a byte vector.
let mut output = Vec::new();
embeddings.write_word2vec_binary(&mut output, true).unwrap();
let embeddings =
Embeddings::read_word2vec_binary_raw(&mut Cursor::new(&output), false).unwrap();
assert!(embeddings
.storage()
.view()
.abs_diff_eq(&embeddings_check.storage().view(), 1e-6));
}
}