|
| 1 | +import sys |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +from finalfusion.scripts.util import Format |
| 6 | +from finalfusion.vocab.subword import FastTextVocab, SubwordVocab |
| 7 | + |
| 8 | + |
| 9 | +def test(inp, input_format, output, output_format): |
| 10 | + e1 = Format(input_format).load(inp) |
| 11 | + e2 = Format(output_format).load(output) |
| 12 | + if isinstance(e1.vocab, FastTextVocab) and \ |
| 13 | + output_format in ["finalfusion", "fasttext"]: |
| 14 | + exit(cmp_subword_embeds(e1, e2)) |
| 15 | + |
| 16 | + if isinstance(e1.vocab, SubwordVocab) and \ |
| 17 | + input_format in ["fasttext", "finalfusion"] and \ |
| 18 | + output_format in ["word2vec", "text", "textdims"]: |
| 19 | + exit(cmp_subword_embeds_to_simple(e1, e2)) |
| 20 | + |
| 21 | + if input_format in ["finalfusion", "word2vec", "text", "textdims"]: |
| 22 | + exit(cmp_simple_embeds(e1, e2)) |
| 23 | + print( |
| 24 | + f"missing testcase for {input_format} to {output_format} ({inp} to {output})", |
| 25 | + file=sys.stderr) |
| 26 | + exit(1) |
| 27 | + |
| 28 | + |
| 29 | +def cmp_simple_embeds(e1, e2): |
| 30 | + assert e1.vocab == e2.vocab |
| 31 | + assert np.allclose(e1.storage, e2.storage, atol=1e-5) |
| 32 | + assert np.allclose(e1.norms, e2.norms, atol=1e-5) |
| 33 | + return 0 |
| 34 | + |
| 35 | + |
| 36 | +def cmp_subword_embeds_to_simple(e1, e2): |
| 37 | + assert e1.vocab.words == e2.vocab.words |
| 38 | + assert e1.vocab.word_index == e2.vocab.word_index |
| 39 | + assert np.allclose(e1.storage[:len(e1.vocab)], e2.storage, atol=1e-5) |
| 40 | + if e1.norms is not None: |
| 41 | + assert np.allclose(e1.norms, e2.norms, atol=1e-5) |
| 42 | + return 0 |
| 43 | + |
| 44 | + |
| 45 | +def cmp_subword_embeds(e1, e2): |
| 46 | + assert e1.vocab == e2.vocab |
| 47 | + assert np.allclose(e1.storage, e2.storage, atol=1e-5) |
| 48 | + if e1.norms is not None: |
| 49 | + assert np.allclose(e1.norms, e2.norms, atol=1e-5) |
| 50 | + return 0 |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + test(*sys.argv[1:]) |
0 commit comments