Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

test_utils.py 2.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the LICENSE file in
  5. # the root directory of this source tree. An additional grant of patent rights
  6. # can be found in the PATENTS file in the same directory.
  7. import unittest
  8. import torch
  9. from fairseq import utils
  10. class TestUtils(unittest.TestCase):
  11. def test_convert_padding_direction(self):
  12. pad = 1
  13. left_pad = torch.LongTensor([
  14. [2, 3, 4, 5, 6],
  15. [1, 7, 8, 9, 10],
  16. [1, 1, 1, 11, 12],
  17. ])
  18. right_pad = torch.LongTensor([
  19. [2, 3, 4, 5, 6],
  20. [7, 8, 9, 10, 1],
  21. [11, 12, 1, 1, 1],
  22. ])
  23. self.assertAlmostEqual(
  24. right_pad,
  25. utils.convert_padding_direction(
  26. left_pad,
  27. pad,
  28. left_to_right=True,
  29. ),
  30. )
  31. self.assertAlmostEqual(
  32. left_pad,
  33. utils.convert_padding_direction(
  34. right_pad,
  35. pad,
  36. right_to_left=True,
  37. ),
  38. )
  39. def test_make_positions(self):
  40. pad = 1
  41. left_pad_input = torch.LongTensor([
  42. [9, 9, 9, 9, 9],
  43. [1, 9, 9, 9, 9],
  44. [1, 1, 1, 9, 9],
  45. ])
  46. left_pad_output = torch.LongTensor([
  47. [2, 3, 4, 5, 6],
  48. [1, 2, 3, 4, 5],
  49. [1, 1, 1, 2, 3],
  50. ])
  51. right_pad_input = torch.LongTensor([
  52. [9, 9, 9, 9, 9],
  53. [9, 9, 9, 9, 1],
  54. [9, 9, 1, 1, 1],
  55. ])
  56. right_pad_output = torch.LongTensor([
  57. [2, 3, 4, 5, 6],
  58. [2, 3, 4, 5, 1],
  59. [2, 3, 1, 1, 1],
  60. ])
  61. self.assertAlmostEqual(
  62. left_pad_output,
  63. utils.make_positions(left_pad_input, pad, left_pad=True),
  64. )
  65. self.assertAlmostEqual(
  66. right_pad_output,
  67. utils.make_positions(right_pad_input, pad, left_pad=False),
  68. )
  69. def assertAlmostEqual(self, t1, t2):
  70. self.assertEqual(t1.size(), t2.size(), "size mismatch")
  71. self.assertLess(utils.item((t1 - t2).abs().max()), 1e-4)
  72. if __name__ == '__main__':
  73. unittest.main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...