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

bleu.py 4.0 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
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
  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 ctypes
  8. import math
  9. import torch
  10. try:
  11. from fairseq import libbleu
  12. except ImportError as e:
  13. import sys
  14. sys.stderr.write('ERROR: missing libbleu.so. run `python setup.py build develop`\n')
  15. raise e
  16. C = ctypes.cdll.LoadLibrary(libbleu.__file__)
  17. class BleuStat(ctypes.Structure):
  18. _fields_ = [
  19. ('reflen', ctypes.c_size_t),
  20. ('predlen', ctypes.c_size_t),
  21. ('match1', ctypes.c_size_t),
  22. ('count1', ctypes.c_size_t),
  23. ('match2', ctypes.c_size_t),
  24. ('count2', ctypes.c_size_t),
  25. ('match3', ctypes.c_size_t),
  26. ('count3', ctypes.c_size_t),
  27. ('match4', ctypes.c_size_t),
  28. ('count4', ctypes.c_size_t),
  29. ]
  30. class SacrebleuScorer(object):
  31. def __init__(self):
  32. import sacrebleu
  33. self.sacrebleu = sacrebleu
  34. self.reset()
  35. def reset(self, one_init=False):
  36. if one_init:
  37. raise NotImplementedError
  38. self.ref = []
  39. self.sys = []
  40. def add_string(self, ref, pred):
  41. self.ref.append(ref)
  42. self.sys.append(pred)
  43. def score(self, order=4):
  44. return self.result_string(order).bleu
  45. def result_string(self, order=4):
  46. if order != 4:
  47. raise NotImplementedError
  48. return self.sacrebleu.corpus_bleu(self.sys, [self.ref])
  49. class Scorer(object):
  50. def __init__(self, pad, eos, unk):
  51. self.stat = BleuStat()
  52. self.pad = pad
  53. self.eos = eos
  54. self.unk = unk
  55. self.reset()
  56. def reset(self, one_init=False):
  57. if one_init:
  58. C.bleu_one_init(ctypes.byref(self.stat))
  59. else:
  60. C.bleu_zero_init(ctypes.byref(self.stat))
  61. def add(self, ref, pred):
  62. if not isinstance(ref, torch.IntTensor):
  63. raise TypeError('ref must be a torch.IntTensor (got {})'
  64. .format(type(ref)))
  65. if not isinstance(pred, torch.IntTensor):
  66. raise TypeError('pred must be a torch.IntTensor(got {})'
  67. .format(type(pred)))
  68. # don't match unknown words
  69. rref = ref.clone()
  70. assert not rref.lt(0).any()
  71. rref[rref.eq(self.unk)] = -999
  72. rref = rref.contiguous().view(-1)
  73. pred = pred.contiguous().view(-1)
  74. C.bleu_add(
  75. ctypes.byref(self.stat),
  76. ctypes.c_size_t(rref.size(0)),
  77. ctypes.c_void_p(rref.data_ptr()),
  78. ctypes.c_size_t(pred.size(0)),
  79. ctypes.c_void_p(pred.data_ptr()),
  80. ctypes.c_int(self.pad),
  81. ctypes.c_int(self.eos))
  82. def score(self, order=4):
  83. psum = sum(math.log(p) if p > 0 else float('-Inf')
  84. for p in self.precision()[:order])
  85. return self.brevity() * math.exp(psum / order) * 100
  86. def precision(self):
  87. def ratio(a, b):
  88. return a / b if b > 0 else 0
  89. return [
  90. ratio(self.stat.match1, self.stat.count1),
  91. ratio(self.stat.match2, self.stat.count2),
  92. ratio(self.stat.match3, self.stat.count3),
  93. ratio(self.stat.match4, self.stat.count4),
  94. ]
  95. def brevity(self):
  96. r = self.stat.reflen / self.stat.predlen
  97. return min(1, math.exp(1 - r))
  98. def result_string(self, order=4):
  99. assert order <= 4, "BLEU scores for order > 4 aren't supported"
  100. fmt = 'BLEU{} = {:2.2f}, {:2.1f}'
  101. for _ in range(1, order):
  102. fmt += '/{:2.1f}'
  103. fmt += ' (BP={:.3f}, ratio={:.3f}, syslen={}, reflen={})'
  104. bleup = [p * 100 for p in self.precision()[:order]]
  105. return fmt.format(order, self.score(order=order), *bleup,
  106. self.brevity(), self.stat.predlen/self.stat.reflen,
  107. self.stat.predlen, self.stat.reflen)
Tip!

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

Comments

Loading...