assassinlike commited on
Commit
487f02f
·
verified ·
1 Parent(s): 40c0335

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/ansi.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/ansitowin32.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/initialise.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/win32.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/winterm.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__init__.py +1 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/ansi_test.cpython-310.pyc +0 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc +0 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/initialise_test.cpython-310.pyc +0 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/isatty_test.cpython-310.pyc +0 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/utils.cpython-310.pyc +0 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/winterm_test.cpython-310.pyc +0 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/ansi_test.py +76 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/ansitowin32_test.py +294 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/initialise_test.py +189 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/isatty_test.py +57 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/utils.py +49 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/winterm_test.py +131 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/__init__.cpython-310.pyc +0 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/aliases.cpython-310.pyc +0 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/beam_search.cpython-310.pyc +0 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/checkpoint.cpython-310.pyc +0 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/config.cpython-310.pyc +0 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/exceptions.cpython-310.pyc +0 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/initialization.cpython-310.pyc +0 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/model.cpython-310.pyc +0 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/optim.cpython-310.pyc +0 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/safetensors_util.cpython-310.pyc +0 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/tokenizer.cpython-310.pyc +0 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/torch_util.cpython-310.pyc +0 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/train.cpython-310.pyc +0 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/util.cpython-310.pyc +0 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/version.cpython-310.pyc +0 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__init__.py +180 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/__init__.cpython-310.pyc +0 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/collator.cpython-310.pyc +0 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/custom_datasets.cpython-310.pyc +0 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/iterable_dataset.cpython-310.pyc +0 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/memmap_dataset.cpython-310.pyc +0 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/util.cpython-310.pyc +0 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/collator.py +174 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/custom_datasets.py +55 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/iterable_dataset.py +191 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/memmap_dataset.py +247 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/named_data_mixes.py +0 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/util.py +130 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/eval/__init__.py +114 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/eval/__pycache__/__init__.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (468 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/ansi.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/ansitowin32.cpython-310.pyc ADDED
Binary file (8.51 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/initialise.cpython-310.pyc ADDED
Binary file (2.25 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/win32.cpython-310.pyc ADDED
Binary file (4.46 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/__pycache__/winterm.cpython-310.pyc ADDED
Binary file (5.16 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/ansi_test.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/initialise_test.cpython-310.pyc ADDED
Binary file (6.89 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/isatty_test.cpython-310.pyc ADDED
Binary file (2.68 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.59 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/__pycache__/winterm_test.cpython-310.pyc ADDED
Binary file (3.18 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/ansi_test.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main
4
+
5
+ from ..ansi import Back, Fore, Style
6
+ from ..ansitowin32 import AnsiToWin32
7
+
8
+ stdout_orig = sys.stdout
9
+ stderr_orig = sys.stderr
10
+
11
+
12
+ class AnsiTest(TestCase):
13
+
14
+ def setUp(self):
15
+ # sanity check: stdout should be a file or StringIO object.
16
+ # It will only be AnsiToWin32 if init() has previously wrapped it
17
+ self.assertNotEqual(type(sys.stdout), AnsiToWin32)
18
+ self.assertNotEqual(type(sys.stderr), AnsiToWin32)
19
+
20
+ def tearDown(self):
21
+ sys.stdout = stdout_orig
22
+ sys.stderr = stderr_orig
23
+
24
+
25
+ def testForeAttributes(self):
26
+ self.assertEqual(Fore.BLACK, '\033[30m')
27
+ self.assertEqual(Fore.RED, '\033[31m')
28
+ self.assertEqual(Fore.GREEN, '\033[32m')
29
+ self.assertEqual(Fore.YELLOW, '\033[33m')
30
+ self.assertEqual(Fore.BLUE, '\033[34m')
31
+ self.assertEqual(Fore.MAGENTA, '\033[35m')
32
+ self.assertEqual(Fore.CYAN, '\033[36m')
33
+ self.assertEqual(Fore.WHITE, '\033[37m')
34
+ self.assertEqual(Fore.RESET, '\033[39m')
35
+
36
+ # Check the light, extended versions.
37
+ self.assertEqual(Fore.LIGHTBLACK_EX, '\033[90m')
38
+ self.assertEqual(Fore.LIGHTRED_EX, '\033[91m')
39
+ self.assertEqual(Fore.LIGHTGREEN_EX, '\033[92m')
40
+ self.assertEqual(Fore.LIGHTYELLOW_EX, '\033[93m')
41
+ self.assertEqual(Fore.LIGHTBLUE_EX, '\033[94m')
42
+ self.assertEqual(Fore.LIGHTMAGENTA_EX, '\033[95m')
43
+ self.assertEqual(Fore.LIGHTCYAN_EX, '\033[96m')
44
+ self.assertEqual(Fore.LIGHTWHITE_EX, '\033[97m')
45
+
46
+
47
+ def testBackAttributes(self):
48
+ self.assertEqual(Back.BLACK, '\033[40m')
49
+ self.assertEqual(Back.RED, '\033[41m')
50
+ self.assertEqual(Back.GREEN, '\033[42m')
51
+ self.assertEqual(Back.YELLOW, '\033[43m')
52
+ self.assertEqual(Back.BLUE, '\033[44m')
53
+ self.assertEqual(Back.MAGENTA, '\033[45m')
54
+ self.assertEqual(Back.CYAN, '\033[46m')
55
+ self.assertEqual(Back.WHITE, '\033[47m')
56
+ self.assertEqual(Back.RESET, '\033[49m')
57
+
58
+ # Check the light, extended versions.
59
+ self.assertEqual(Back.LIGHTBLACK_EX, '\033[100m')
60
+ self.assertEqual(Back.LIGHTRED_EX, '\033[101m')
61
+ self.assertEqual(Back.LIGHTGREEN_EX, '\033[102m')
62
+ self.assertEqual(Back.LIGHTYELLOW_EX, '\033[103m')
63
+ self.assertEqual(Back.LIGHTBLUE_EX, '\033[104m')
64
+ self.assertEqual(Back.LIGHTMAGENTA_EX, '\033[105m')
65
+ self.assertEqual(Back.LIGHTCYAN_EX, '\033[106m')
66
+ self.assertEqual(Back.LIGHTWHITE_EX, '\033[107m')
67
+
68
+
69
+ def testStyleAttributes(self):
70
+ self.assertEqual(Style.DIM, '\033[2m')
71
+ self.assertEqual(Style.NORMAL, '\033[22m')
72
+ self.assertEqual(Style.BRIGHT, '\033[1m')
73
+
74
+
75
+ if __name__ == '__main__':
76
+ main()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/ansitowin32_test.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ from io import StringIO, TextIOWrapper
3
+ from unittest import TestCase, main
4
+ try:
5
+ from contextlib import ExitStack
6
+ except ImportError:
7
+ # python 2
8
+ from contextlib2 import ExitStack
9
+
10
+ try:
11
+ from unittest.mock import MagicMock, Mock, patch
12
+ except ImportError:
13
+ from mock import MagicMock, Mock, patch
14
+
15
+ from ..ansitowin32 import AnsiToWin32, StreamWrapper
16
+ from ..win32 import ENABLE_VIRTUAL_TERMINAL_PROCESSING
17
+ from .utils import osname
18
+
19
+
20
+ class StreamWrapperTest(TestCase):
21
+
22
+ def testIsAProxy(self):
23
+ mockStream = Mock()
24
+ wrapper = StreamWrapper(mockStream, None)
25
+ self.assertTrue( wrapper.random_attr is mockStream.random_attr )
26
+
27
+ def testDelegatesWrite(self):
28
+ mockStream = Mock()
29
+ mockConverter = Mock()
30
+ wrapper = StreamWrapper(mockStream, mockConverter)
31
+ wrapper.write('hello')
32
+ self.assertTrue(mockConverter.write.call_args, (('hello',), {}))
33
+
34
+ def testDelegatesContext(self):
35
+ mockConverter = Mock()
36
+ s = StringIO()
37
+ with StreamWrapper(s, mockConverter) as fp:
38
+ fp.write(u'hello')
39
+ self.assertTrue(s.closed)
40
+
41
+ def testProxyNoContextManager(self):
42
+ mockStream = MagicMock()
43
+ mockStream.__enter__.side_effect = AttributeError()
44
+ mockConverter = Mock()
45
+ with self.assertRaises(AttributeError) as excinfo:
46
+ with StreamWrapper(mockStream, mockConverter) as wrapper:
47
+ wrapper.write('hello')
48
+
49
+ def test_closed_shouldnt_raise_on_closed_stream(self):
50
+ stream = StringIO()
51
+ stream.close()
52
+ wrapper = StreamWrapper(stream, None)
53
+ self.assertEqual(wrapper.closed, True)
54
+
55
+ def test_closed_shouldnt_raise_on_detached_stream(self):
56
+ stream = TextIOWrapper(StringIO())
57
+ stream.detach()
58
+ wrapper = StreamWrapper(stream, None)
59
+ self.assertEqual(wrapper.closed, True)
60
+
61
+ class AnsiToWin32Test(TestCase):
62
+
63
+ def testInit(self):
64
+ mockStdout = Mock()
65
+ auto = Mock()
66
+ stream = AnsiToWin32(mockStdout, autoreset=auto)
67
+ self.assertEqual(stream.wrapped, mockStdout)
68
+ self.assertEqual(stream.autoreset, auto)
69
+
70
+ @patch('colorama.ansitowin32.winterm', None)
71
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: True)
72
+ def testStripIsTrueOnWindows(self):
73
+ with osname('nt'):
74
+ mockStdout = Mock()
75
+ stream = AnsiToWin32(mockStdout)
76
+ self.assertTrue(stream.strip)
77
+
78
+ def testStripIsFalseOffWindows(self):
79
+ with osname('posix'):
80
+ mockStdout = Mock(closed=False)
81
+ stream = AnsiToWin32(mockStdout)
82
+ self.assertFalse(stream.strip)
83
+
84
+ def testWriteStripsAnsi(self):
85
+ mockStdout = Mock()
86
+ stream = AnsiToWin32(mockStdout)
87
+ stream.wrapped = Mock()
88
+ stream.write_and_convert = Mock()
89
+ stream.strip = True
90
+
91
+ stream.write('abc')
92
+
93
+ self.assertFalse(stream.wrapped.write.called)
94
+ self.assertEqual(stream.write_and_convert.call_args, (('abc',), {}))
95
+
96
+ def testWriteDoesNotStripAnsi(self):
97
+ mockStdout = Mock()
98
+ stream = AnsiToWin32(mockStdout)
99
+ stream.wrapped = Mock()
100
+ stream.write_and_convert = Mock()
101
+ stream.strip = False
102
+ stream.convert = False
103
+
104
+ stream.write('abc')
105
+
106
+ self.assertFalse(stream.write_and_convert.called)
107
+ self.assertEqual(stream.wrapped.write.call_args, (('abc',), {}))
108
+
109
+ def assert_autoresets(self, convert, autoreset=True):
110
+ stream = AnsiToWin32(Mock())
111
+ stream.convert = convert
112
+ stream.reset_all = Mock()
113
+ stream.autoreset = autoreset
114
+ stream.winterm = Mock()
115
+
116
+ stream.write('abc')
117
+
118
+ self.assertEqual(stream.reset_all.called, autoreset)
119
+
120
+ def testWriteAutoresets(self):
121
+ self.assert_autoresets(convert=True)
122
+ self.assert_autoresets(convert=False)
123
+ self.assert_autoresets(convert=True, autoreset=False)
124
+ self.assert_autoresets(convert=False, autoreset=False)
125
+
126
+ def testWriteAndConvertWritesPlainText(self):
127
+ stream = AnsiToWin32(Mock())
128
+ stream.write_and_convert( 'abc' )
129
+ self.assertEqual( stream.wrapped.write.call_args, (('abc',), {}) )
130
+
131
+ def testWriteAndConvertStripsAllValidAnsi(self):
132
+ stream = AnsiToWin32(Mock())
133
+ stream.call_win32 = Mock()
134
+ data = [
135
+ 'abc\033[mdef',
136
+ 'abc\033[0mdef',
137
+ 'abc\033[2mdef',
138
+ 'abc\033[02mdef',
139
+ 'abc\033[002mdef',
140
+ 'abc\033[40mdef',
141
+ 'abc\033[040mdef',
142
+ 'abc\033[0;1mdef',
143
+ 'abc\033[40;50mdef',
144
+ 'abc\033[50;30;40mdef',
145
+ 'abc\033[Adef',
146
+ 'abc\033[0Gdef',
147
+ 'abc\033[1;20;128Hdef',
148
+ ]
149
+ for datum in data:
150
+ stream.wrapped.write.reset_mock()
151
+ stream.write_and_convert( datum )
152
+ self.assertEqual(
153
+ [args[0] for args in stream.wrapped.write.call_args_list],
154
+ [ ('abc',), ('def',) ]
155
+ )
156
+
157
+ def testWriteAndConvertSkipsEmptySnippets(self):
158
+ stream = AnsiToWin32(Mock())
159
+ stream.call_win32 = Mock()
160
+ stream.write_and_convert( '\033[40m\033[41m' )
161
+ self.assertFalse( stream.wrapped.write.called )
162
+
163
+ def testWriteAndConvertCallsWin32WithParamsAndCommand(self):
164
+ stream = AnsiToWin32(Mock())
165
+ stream.convert = True
166
+ stream.call_win32 = Mock()
167
+ stream.extract_params = Mock(return_value='params')
168
+ data = {
169
+ 'abc\033[adef': ('a', 'params'),
170
+ 'abc\033[;;bdef': ('b', 'params'),
171
+ 'abc\033[0cdef': ('c', 'params'),
172
+ 'abc\033[;;0;;Gdef': ('G', 'params'),
173
+ 'abc\033[1;20;128Hdef': ('H', 'params'),
174
+ }
175
+ for datum, expected in data.items():
176
+ stream.call_win32.reset_mock()
177
+ stream.write_and_convert( datum )
178
+ self.assertEqual( stream.call_win32.call_args[0], expected )
179
+
180
+ def test_reset_all_shouldnt_raise_on_closed_orig_stdout(self):
181
+ stream = StringIO()
182
+ converter = AnsiToWin32(stream)
183
+ stream.close()
184
+
185
+ converter.reset_all()
186
+
187
+ def test_wrap_shouldnt_raise_on_closed_orig_stdout(self):
188
+ stream = StringIO()
189
+ stream.close()
190
+ with \
191
+ patch("colorama.ansitowin32.os.name", "nt"), \
192
+ patch("colorama.ansitowin32.winapi_test", lambda: True):
193
+ converter = AnsiToWin32(stream)
194
+ self.assertTrue(converter.strip)
195
+ self.assertFalse(converter.convert)
196
+
197
+ def test_wrap_shouldnt_raise_on_missing_closed_attr(self):
198
+ with \
199
+ patch("colorama.ansitowin32.os.name", "nt"), \
200
+ patch("colorama.ansitowin32.winapi_test", lambda: True):
201
+ converter = AnsiToWin32(object())
202
+ self.assertTrue(converter.strip)
203
+ self.assertFalse(converter.convert)
204
+
205
+ def testExtractParams(self):
206
+ stream = AnsiToWin32(Mock())
207
+ data = {
208
+ '': (0,),
209
+ ';;': (0,),
210
+ '2': (2,),
211
+ ';;002;;': (2,),
212
+ '0;1': (0, 1),
213
+ ';;003;;456;;': (3, 456),
214
+ '11;22;33;44;55': (11, 22, 33, 44, 55),
215
+ }
216
+ for datum, expected in data.items():
217
+ self.assertEqual(stream.extract_params('m', datum), expected)
218
+
219
+ def testCallWin32UsesLookup(self):
220
+ listener = Mock()
221
+ stream = AnsiToWin32(listener)
222
+ stream.win32_calls = {
223
+ 1: (lambda *_, **__: listener(11),),
224
+ 2: (lambda *_, **__: listener(22),),
225
+ 3: (lambda *_, **__: listener(33),),
226
+ }
227
+ stream.call_win32('m', (3, 1, 99, 2))
228
+ self.assertEqual(
229
+ [a[0][0] for a in listener.call_args_list],
230
+ [33, 11, 22] )
231
+
232
+ def test_osc_codes(self):
233
+ mockStdout = Mock()
234
+ stream = AnsiToWin32(mockStdout, convert=True)
235
+ with patch('colorama.ansitowin32.winterm') as winterm:
236
+ data = [
237
+ '\033]0\x07', # missing arguments
238
+ '\033]0;foo\x08', # wrong OSC command
239
+ '\033]0;colorama_test_title\x07', # should work
240
+ '\033]1;colorama_test_title\x07', # wrong set command
241
+ '\033]2;colorama_test_title\x07', # should work
242
+ '\033]' + ';' * 64 + '\x08', # see issue #247
243
+ ]
244
+ for code in data:
245
+ stream.write(code)
246
+ self.assertEqual(winterm.set_title.call_count, 2)
247
+
248
+ def test_native_windows_ansi(self):
249
+ with ExitStack() as stack:
250
+ def p(a, b):
251
+ stack.enter_context(patch(a, b, create=True))
252
+ # Pretend to be on Windows
253
+ p("colorama.ansitowin32.os.name", "nt")
254
+ p("colorama.ansitowin32.winapi_test", lambda: True)
255
+ p("colorama.win32.winapi_test", lambda: True)
256
+ p("colorama.winterm.win32.windll", "non-None")
257
+ p("colorama.winterm.get_osfhandle", lambda _: 1234)
258
+
259
+ # Pretend that our mock stream has native ANSI support
260
+ p(
261
+ "colorama.winterm.win32.GetConsoleMode",
262
+ lambda _: ENABLE_VIRTUAL_TERMINAL_PROCESSING,
263
+ )
264
+ SetConsoleMode = Mock()
265
+ p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
266
+
267
+ stdout = Mock()
268
+ stdout.closed = False
269
+ stdout.isatty.return_value = True
270
+ stdout.fileno.return_value = 1
271
+
272
+ # Our fake console says it has native vt support, so AnsiToWin32 should
273
+ # enable that support and do nothing else.
274
+ stream = AnsiToWin32(stdout)
275
+ SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
276
+ self.assertFalse(stream.strip)
277
+ self.assertFalse(stream.convert)
278
+ self.assertFalse(stream.should_wrap())
279
+
280
+ # Now let's pretend we're on an old Windows console, that doesn't have
281
+ # native ANSI support.
282
+ p("colorama.winterm.win32.GetConsoleMode", lambda _: 0)
283
+ SetConsoleMode = Mock()
284
+ p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode)
285
+
286
+ stream = AnsiToWin32(stdout)
287
+ SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
288
+ self.assertTrue(stream.strip)
289
+ self.assertTrue(stream.convert)
290
+ self.assertTrue(stream.should_wrap())
291
+
292
+
293
+ if __name__ == '__main__':
294
+ main()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/initialise_test.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main, skipUnless
4
+
5
+ try:
6
+ from unittest.mock import patch, Mock
7
+ except ImportError:
8
+ from mock import patch, Mock
9
+
10
+ from ..ansitowin32 import StreamWrapper
11
+ from ..initialise import init, just_fix_windows_console, _wipe_internal_state_for_tests
12
+ from .utils import osname, replace_by
13
+
14
+ orig_stdout = sys.stdout
15
+ orig_stderr = sys.stderr
16
+
17
+
18
+ class InitTest(TestCase):
19
+
20
+ @skipUnless(sys.stdout.isatty(), "sys.stdout is not a tty")
21
+ def setUp(self):
22
+ # sanity check
23
+ self.assertNotWrapped()
24
+
25
+ def tearDown(self):
26
+ _wipe_internal_state_for_tests()
27
+ sys.stdout = orig_stdout
28
+ sys.stderr = orig_stderr
29
+
30
+ def assertWrapped(self):
31
+ self.assertIsNot(sys.stdout, orig_stdout, 'stdout should be wrapped')
32
+ self.assertIsNot(sys.stderr, orig_stderr, 'stderr should be wrapped')
33
+ self.assertTrue(isinstance(sys.stdout, StreamWrapper),
34
+ 'bad stdout wrapper')
35
+ self.assertTrue(isinstance(sys.stderr, StreamWrapper),
36
+ 'bad stderr wrapper')
37
+
38
+ def assertNotWrapped(self):
39
+ self.assertIs(sys.stdout, orig_stdout, 'stdout should not be wrapped')
40
+ self.assertIs(sys.stderr, orig_stderr, 'stderr should not be wrapped')
41
+
42
+ @patch('colorama.initialise.reset_all')
43
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: True)
44
+ @patch('colorama.ansitowin32.enable_vt_processing', lambda *_: False)
45
+ def testInitWrapsOnWindows(self, _):
46
+ with osname("nt"):
47
+ init()
48
+ self.assertWrapped()
49
+
50
+ @patch('colorama.initialise.reset_all')
51
+ @patch('colorama.ansitowin32.winapi_test', lambda *_: False)
52
+ def testInitDoesntWrapOnEmulatedWindows(self, _):
53
+ with osname("nt"):
54
+ init()
55
+ self.assertNotWrapped()
56
+
57
+ def testInitDoesntWrapOnNonWindows(self):
58
+ with osname("posix"):
59
+ init()
60
+ self.assertNotWrapped()
61
+
62
+ def testInitDoesntWrapIfNone(self):
63
+ with replace_by(None):
64
+ init()
65
+ # We can't use assertNotWrapped here because replace_by(None)
66
+ # changes stdout/stderr already.
67
+ self.assertIsNone(sys.stdout)
68
+ self.assertIsNone(sys.stderr)
69
+
70
+ def testInitAutoresetOnWrapsOnAllPlatforms(self):
71
+ with osname("posix"):
72
+ init(autoreset=True)
73
+ self.assertWrapped()
74
+
75
+ def testInitWrapOffDoesntWrapOnWindows(self):
76
+ with osname("nt"):
77
+ init(wrap=False)
78
+ self.assertNotWrapped()
79
+
80
+ def testInitWrapOffIncompatibleWithAutoresetOn(self):
81
+ self.assertRaises(ValueError, lambda: init(autoreset=True, wrap=False))
82
+
83
+ @patch('colorama.win32.SetConsoleTextAttribute')
84
+ @patch('colorama.initialise.AnsiToWin32')
85
+ def testAutoResetPassedOn(self, mockATW32, _):
86
+ with osname("nt"):
87
+ init(autoreset=True)
88
+ self.assertEqual(len(mockATW32.call_args_list), 2)
89
+ self.assertEqual(mockATW32.call_args_list[1][1]['autoreset'], True)
90
+ self.assertEqual(mockATW32.call_args_list[0][1]['autoreset'], True)
91
+
92
+ @patch('colorama.initialise.AnsiToWin32')
93
+ def testAutoResetChangeable(self, mockATW32):
94
+ with osname("nt"):
95
+ init()
96
+
97
+ init(autoreset=True)
98
+ self.assertEqual(len(mockATW32.call_args_list), 4)
99
+ self.assertEqual(mockATW32.call_args_list[2][1]['autoreset'], True)
100
+ self.assertEqual(mockATW32.call_args_list[3][1]['autoreset'], True)
101
+
102
+ init()
103
+ self.assertEqual(len(mockATW32.call_args_list), 6)
104
+ self.assertEqual(
105
+ mockATW32.call_args_list[4][1]['autoreset'], False)
106
+ self.assertEqual(
107
+ mockATW32.call_args_list[5][1]['autoreset'], False)
108
+
109
+
110
+ @patch('colorama.initialise.atexit.register')
111
+ def testAtexitRegisteredOnlyOnce(self, mockRegister):
112
+ init()
113
+ self.assertTrue(mockRegister.called)
114
+ mockRegister.reset_mock()
115
+ init()
116
+ self.assertFalse(mockRegister.called)
117
+
118
+
119
+ class JustFixWindowsConsoleTest(TestCase):
120
+ def _reset(self):
121
+ _wipe_internal_state_for_tests()
122
+ sys.stdout = orig_stdout
123
+ sys.stderr = orig_stderr
124
+
125
+ def tearDown(self):
126
+ self._reset()
127
+
128
+ @patch("colorama.ansitowin32.winapi_test", lambda: True)
129
+ def testJustFixWindowsConsole(self):
130
+ if sys.platform != "win32":
131
+ # just_fix_windows_console should be a no-op
132
+ just_fix_windows_console()
133
+ self.assertIs(sys.stdout, orig_stdout)
134
+ self.assertIs(sys.stderr, orig_stderr)
135
+ else:
136
+ def fake_std():
137
+ # Emulate stdout=not a tty, stderr=tty
138
+ # to check that we handle both cases correctly
139
+ stdout = Mock()
140
+ stdout.closed = False
141
+ stdout.isatty.return_value = False
142
+ stdout.fileno.return_value = 1
143
+ sys.stdout = stdout
144
+
145
+ stderr = Mock()
146
+ stderr.closed = False
147
+ stderr.isatty.return_value = True
148
+ stderr.fileno.return_value = 2
149
+ sys.stderr = stderr
150
+
151
+ for native_ansi in [False, True]:
152
+ with patch(
153
+ 'colorama.ansitowin32.enable_vt_processing',
154
+ lambda *_: native_ansi
155
+ ):
156
+ self._reset()
157
+ fake_std()
158
+
159
+ # Regular single-call test
160
+ prev_stdout = sys.stdout
161
+ prev_stderr = sys.stderr
162
+ just_fix_windows_console()
163
+ self.assertIs(sys.stdout, prev_stdout)
164
+ if native_ansi:
165
+ self.assertIs(sys.stderr, prev_stderr)
166
+ else:
167
+ self.assertIsNot(sys.stderr, prev_stderr)
168
+
169
+ # second call without resetting is always a no-op
170
+ prev_stdout = sys.stdout
171
+ prev_stderr = sys.stderr
172
+ just_fix_windows_console()
173
+ self.assertIs(sys.stdout, prev_stdout)
174
+ self.assertIs(sys.stderr, prev_stderr)
175
+
176
+ self._reset()
177
+ fake_std()
178
+
179
+ # If init() runs first, just_fix_windows_console should be a no-op
180
+ init()
181
+ prev_stdout = sys.stdout
182
+ prev_stderr = sys.stderr
183
+ just_fix_windows_console()
184
+ self.assertIs(prev_stdout, sys.stdout)
185
+ self.assertIs(prev_stderr, sys.stderr)
186
+
187
+
188
+ if __name__ == '__main__':
189
+ main()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/isatty_test.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main
4
+
5
+ from ..ansitowin32 import StreamWrapper, AnsiToWin32
6
+ from .utils import pycharm, replace_by, replace_original_by, StreamTTY, StreamNonTTY
7
+
8
+
9
+ def is_a_tty(stream):
10
+ return StreamWrapper(stream, None).isatty()
11
+
12
+ class IsattyTest(TestCase):
13
+
14
+ def test_TTY(self):
15
+ tty = StreamTTY()
16
+ self.assertTrue(is_a_tty(tty))
17
+ with pycharm():
18
+ self.assertTrue(is_a_tty(tty))
19
+
20
+ def test_nonTTY(self):
21
+ non_tty = StreamNonTTY()
22
+ self.assertFalse(is_a_tty(non_tty))
23
+ with pycharm():
24
+ self.assertFalse(is_a_tty(non_tty))
25
+
26
+ def test_withPycharm(self):
27
+ with pycharm():
28
+ self.assertTrue(is_a_tty(sys.stderr))
29
+ self.assertTrue(is_a_tty(sys.stdout))
30
+
31
+ def test_withPycharmTTYOverride(self):
32
+ tty = StreamTTY()
33
+ with pycharm(), replace_by(tty):
34
+ self.assertTrue(is_a_tty(tty))
35
+
36
+ def test_withPycharmNonTTYOverride(self):
37
+ non_tty = StreamNonTTY()
38
+ with pycharm(), replace_by(non_tty):
39
+ self.assertFalse(is_a_tty(non_tty))
40
+
41
+ def test_withPycharmNoneOverride(self):
42
+ with pycharm():
43
+ with replace_by(None), replace_original_by(None):
44
+ self.assertFalse(is_a_tty(None))
45
+ self.assertFalse(is_a_tty(StreamNonTTY()))
46
+ self.assertTrue(is_a_tty(StreamTTY()))
47
+
48
+ def test_withPycharmStreamWrapped(self):
49
+ with pycharm():
50
+ self.assertTrue(AnsiToWin32(StreamTTY()).stream.isatty())
51
+ self.assertFalse(AnsiToWin32(StreamNonTTY()).stream.isatty())
52
+ self.assertTrue(AnsiToWin32(sys.stdout).stream.isatty())
53
+ self.assertTrue(AnsiToWin32(sys.stderr).stream.isatty())
54
+
55
+
56
+ if __name__ == '__main__':
57
+ main()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ from contextlib import contextmanager
3
+ from io import StringIO
4
+ import sys
5
+ import os
6
+
7
+
8
+ class StreamTTY(StringIO):
9
+ def isatty(self):
10
+ return True
11
+
12
+ class StreamNonTTY(StringIO):
13
+ def isatty(self):
14
+ return False
15
+
16
+ @contextmanager
17
+ def osname(name):
18
+ orig = os.name
19
+ os.name = name
20
+ yield
21
+ os.name = orig
22
+
23
+ @contextmanager
24
+ def replace_by(stream):
25
+ orig_stdout = sys.stdout
26
+ orig_stderr = sys.stderr
27
+ sys.stdout = stream
28
+ sys.stderr = stream
29
+ yield
30
+ sys.stdout = orig_stdout
31
+ sys.stderr = orig_stderr
32
+
33
+ @contextmanager
34
+ def replace_original_by(stream):
35
+ orig_stdout = sys.__stdout__
36
+ orig_stderr = sys.__stderr__
37
+ sys.__stdout__ = stream
38
+ sys.__stderr__ = stream
39
+ yield
40
+ sys.__stdout__ = orig_stdout
41
+ sys.__stderr__ = orig_stderr
42
+
43
+ @contextmanager
44
+ def pycharm():
45
+ os.environ["PYCHARM_HOSTED"] = "1"
46
+ non_tty = StreamNonTTY()
47
+ with replace_by(non_tty), replace_original_by(non_tty):
48
+ yield
49
+ del os.environ["PYCHARM_HOSTED"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/colorama/tests/winterm_test.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import sys
3
+ from unittest import TestCase, main, skipUnless
4
+
5
+ try:
6
+ from unittest.mock import Mock, patch
7
+ except ImportError:
8
+ from mock import Mock, patch
9
+
10
+ from ..winterm import WinColor, WinStyle, WinTerm
11
+
12
+
13
+ class WinTermTest(TestCase):
14
+
15
+ @patch('colorama.winterm.win32')
16
+ def testInit(self, mockWin32):
17
+ mockAttr = Mock()
18
+ mockAttr.wAttributes = 7 + 6 * 16 + 8
19
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
20
+ term = WinTerm()
21
+ self.assertEqual(term._fore, 7)
22
+ self.assertEqual(term._back, 6)
23
+ self.assertEqual(term._style, 8)
24
+
25
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
26
+ def testGetAttrs(self):
27
+ term = WinTerm()
28
+
29
+ term._fore = 0
30
+ term._back = 0
31
+ term._style = 0
32
+ self.assertEqual(term.get_attrs(), 0)
33
+
34
+ term._fore = WinColor.YELLOW
35
+ self.assertEqual(term.get_attrs(), WinColor.YELLOW)
36
+
37
+ term._back = WinColor.MAGENTA
38
+ self.assertEqual(
39
+ term.get_attrs(),
40
+ WinColor.YELLOW + WinColor.MAGENTA * 16)
41
+
42
+ term._style = WinStyle.BRIGHT
43
+ self.assertEqual(
44
+ term.get_attrs(),
45
+ WinColor.YELLOW + WinColor.MAGENTA * 16 + WinStyle.BRIGHT)
46
+
47
+ @patch('colorama.winterm.win32')
48
+ def testResetAll(self, mockWin32):
49
+ mockAttr = Mock()
50
+ mockAttr.wAttributes = 1 + 2 * 16 + 8
51
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
52
+ term = WinTerm()
53
+
54
+ term.set_console = Mock()
55
+ term._fore = -1
56
+ term._back = -1
57
+ term._style = -1
58
+
59
+ term.reset_all()
60
+
61
+ self.assertEqual(term._fore, 1)
62
+ self.assertEqual(term._back, 2)
63
+ self.assertEqual(term._style, 8)
64
+ self.assertEqual(term.set_console.called, True)
65
+
66
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
67
+ def testFore(self):
68
+ term = WinTerm()
69
+ term.set_console = Mock()
70
+ term._fore = 0
71
+
72
+ term.fore(5)
73
+
74
+ self.assertEqual(term._fore, 5)
75
+ self.assertEqual(term.set_console.called, True)
76
+
77
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
78
+ def testBack(self):
79
+ term = WinTerm()
80
+ term.set_console = Mock()
81
+ term._back = 0
82
+
83
+ term.back(5)
84
+
85
+ self.assertEqual(term._back, 5)
86
+ self.assertEqual(term.set_console.called, True)
87
+
88
+ @skipUnless(sys.platform.startswith("win"), "requires Windows")
89
+ def testStyle(self):
90
+ term = WinTerm()
91
+ term.set_console = Mock()
92
+ term._style = 0
93
+
94
+ term.style(22)
95
+
96
+ self.assertEqual(term._style, 22)
97
+ self.assertEqual(term.set_console.called, True)
98
+
99
+ @patch('colorama.winterm.win32')
100
+ def testSetConsole(self, mockWin32):
101
+ mockAttr = Mock()
102
+ mockAttr.wAttributes = 0
103
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
104
+ term = WinTerm()
105
+ term.windll = Mock()
106
+
107
+ term.set_console()
108
+
109
+ self.assertEqual(
110
+ mockWin32.SetConsoleTextAttribute.call_args,
111
+ ((mockWin32.STDOUT, term.get_attrs()), {})
112
+ )
113
+
114
+ @patch('colorama.winterm.win32')
115
+ def testSetConsoleOnStderr(self, mockWin32):
116
+ mockAttr = Mock()
117
+ mockAttr.wAttributes = 0
118
+ mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
119
+ term = WinTerm()
120
+ term.windll = Mock()
121
+
122
+ term.set_console(on_stderr=True)
123
+
124
+ self.assertEqual(
125
+ mockWin32.SetConsoleTextAttribute.call_args,
126
+ ((mockWin32.STDERR, term.get_attrs()), {})
127
+ )
128
+
129
+
130
+ if __name__ == '__main__':
131
+ main()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (584 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/aliases.cpython-310.pyc ADDED
Binary file (300 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/beam_search.cpython-310.pyc ADDED
Binary file (31.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/checkpoint.cpython-310.pyc ADDED
Binary file (57.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/config.cpython-310.pyc ADDED
Binary file (22.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (1.48 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/initialization.cpython-310.pyc ADDED
Binary file (757 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/model.cpython-310.pyc ADDED
Binary file (46.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/optim.cpython-310.pyc ADDED
Binary file (25.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/safetensors_util.cpython-310.pyc ADDED
Binary file (2.83 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/tokenizer.cpython-310.pyc ADDED
Binary file (6.71 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/torch_util.cpython-310.pyc ADDED
Binary file (6.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/train.cpython-310.pyc ADDED
Binary file (35.5 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/util.cpython-310.pyc ADDED
Binary file (28.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/__pycache__/version.cpython-310.pyc ADDED
Binary file (326 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__init__.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Optional, cast
5
+
6
+ from torch.utils.data import DataLoader, DistributedSampler
7
+
8
+ from ..aliases import PathOrStr
9
+ from ..config import DataConfig, TrainConfig
10
+ from ..exceptions import OLMoConfigurationError
11
+ from ..torch_util import barrier, get_global_rank, get_world_size
12
+ from .collator import CustomDatasetDataCollator, DataCollator
13
+ from .custom_datasets import build_custom_dataset, extract_module_and_class
14
+ from .iterable_dataset import IterableDataset
15
+ from .memmap_dataset import MemMapDataset
16
+
17
+ __all__ = ["MemMapDataset", "DataCollator", "IterableDataset", "build_eval_dataloader", "build_train_dataloader"]
18
+
19
+ LOGGER = logging.getLogger(__name__)
20
+
21
+
22
+ def build_memmap_dataset(
23
+ train_config: TrainConfig, data_config: DataConfig, include_instance_metadata: bool = True
24
+ ) -> MemMapDataset:
25
+ paths: List[str]
26
+ metadata: List[Dict[str, Any]] = []
27
+ if data_config.paths:
28
+ if data_config.datasets:
29
+ raise OLMoConfigurationError("DataConfig.paths is mutually exclusive with DataConfig.datasets")
30
+ paths = data_config.paths
31
+ for path in paths:
32
+ metadata.append({"path": str(path)})
33
+ elif data_config.datasets:
34
+ paths = []
35
+ for label in sorted(data_config.datasets.keys()):
36
+ label_paths = data_config.datasets[label]
37
+ paths.extend(label_paths)
38
+ metadata.extend([{"label": label}] * len(label_paths))
39
+ else:
40
+ raise OLMoConfigurationError("One of DataConfig.paths or DataConfig.datasets is required")
41
+ return MemMapDataset(
42
+ *paths,
43
+ chunk_size=train_config.model.max_sequence_length,
44
+ memmap_dtype=data_config.effective_memmap_dtype,
45
+ metadata=metadata,
46
+ include_instance_metadata=include_instance_metadata,
47
+ pad_token_id=train_config.model.pad_token_id,
48
+ eos_token_id=train_config.model.eos_token_id,
49
+ generate_attention_mask=data_config.generate_attention_mask,
50
+ generate_doc_lengths=data_config.generate_doc_lengths,
51
+ label_mask_paths=cast(Optional[List[PathOrStr]], data_config.label_mask_paths),
52
+ instance_filter_config=data_config.instance_filter,
53
+ )
54
+
55
+
56
+ def build_collator(train_config: TrainConfig) -> DataCollator:
57
+ """Returns a collator for the train dataloader. Either returns the default
58
+ collator or a custom collator specified in the train config.
59
+
60
+ :param train_config: OLMo train config
61
+ :raises OLMoConfigurationError: Raises an error if the collate function is not found
62
+ :return: Collator for the train dataloader
63
+ """
64
+ if train_config.data.custom_dataset:
65
+ if train_config.data.custom_dataset.collate_fn:
66
+ module, function = extract_module_and_class(train_config.data.custom_dataset.collate_fn)
67
+ if module is None:
68
+ if train_config.data.custom_dataset.module is None:
69
+ module, _ = extract_module_and_class(train_config.data.custom_dataset.name)
70
+ else:
71
+ module = train_config.data.custom_dataset.module
72
+ try:
73
+ assert module is not None
74
+ collator = getattr(importlib.import_module(module), function)
75
+ except AttributeError:
76
+ raise OLMoConfigurationError(
77
+ f"collate_fn {train_config.data.custom_dataset.collate_fn} not found in {module}. Please specify the full module path of the function."
78
+ )
79
+ return collator
80
+
81
+ return CustomDatasetDataCollator(
82
+ pad_direction=train_config.data.pad_direction,
83
+ pad_token_id=train_config.model.pad_token_id,
84
+ **train_config.data.custom_dataset.collate_config.asdict(), # type: ignore
85
+ )
86
+ else:
87
+ return DataCollator(
88
+ pad_direction=train_config.data.pad_direction, pad_token_id=train_config.model.pad_token_id
89
+ )
90
+
91
+
92
+ def build_eval_dataloader(
93
+ train_config: TrainConfig,
94
+ data_config: DataConfig,
95
+ batch_size: int,
96
+ shuffle: bool = True,
97
+ ) -> DataLoader:
98
+ dataset = build_memmap_dataset(train_config, data_config, include_instance_metadata=True)
99
+ collator = DataCollator(pad_direction=data_config.pad_direction, pad_token_id=train_config.model.pad_token_id)
100
+ if data_config.drop_last:
101
+ # Make sure batch size is small enough.
102
+ samples_per_device = len(dataset) // get_world_size()
103
+ batch_size = min(batch_size, samples_per_device)
104
+ assert batch_size > 0, f"dataset for {data_config.paths} is too small"
105
+ seed = data_config.seed if data_config.seed is not None else train_config.seed
106
+ sampler = DistributedSampler(
107
+ dataset,
108
+ drop_last=data_config.drop_last,
109
+ shuffle=shuffle,
110
+ num_replicas=get_world_size(),
111
+ rank=get_global_rank(),
112
+ seed=seed,
113
+ )
114
+ return DataLoader(
115
+ dataset,
116
+ batch_size=batch_size,
117
+ collate_fn=collator,
118
+ num_workers=data_config.num_workers,
119
+ sampler=sampler,
120
+ pin_memory=data_config.pin_memory,
121
+ prefetch_factor=None if data_config.num_workers == 0 else data_config.prefetch_factor,
122
+ persistent_workers=False if data_config.num_workers == 0 else data_config.persistent_workers,
123
+ timeout=data_config.timeout,
124
+ )
125
+
126
+
127
+ def build_train_dataloader(
128
+ train_config: TrainConfig,
129
+ *,
130
+ world_size: Optional[int] = None,
131
+ rank: Optional[int] = None,
132
+ fs_local_rank: Optional[int] = None,
133
+ include_instance_metadata: bool = False,
134
+ ) -> DataLoader:
135
+ assert train_config.device_train_batch_size is not None
136
+ seed = train_config.data.seed if train_config.data.seed is not None else train_config.seed
137
+ collator = build_collator(train_config)
138
+ if train_config.data.custom_dataset:
139
+ if train_config.data.paths is not None or train_config.data.datasets is not None:
140
+ raise OLMoConfigurationError(
141
+ "custom_dataset_class is mutually exclusive with DataConfig.paths and DataConfig.datasets"
142
+ )
143
+ dataset = build_custom_dataset(train_config)
144
+ else:
145
+ dataset = build_memmap_dataset(
146
+ train_config, train_config.data, include_instance_metadata=include_instance_metadata
147
+ )
148
+ work_dir = Path(train_config.save_folder) / "train_data"
149
+ if get_global_rank() == 0:
150
+ if work_dir.is_dir() and not train_config.save_overwrite:
151
+ raise OLMoConfigurationError(
152
+ "train data working directory already exists, use --save_overwrite to overwrite"
153
+ )
154
+ else:
155
+ work_dir.mkdir(exist_ok=True, parents=True)
156
+ dataset = IterableDataset(
157
+ dataset, # type: ignore
158
+ train_config.global_train_batch_size,
159
+ seed=seed,
160
+ epoch=train_config.epoch or 0,
161
+ shuffle=True,
162
+ drop_last=train_config.data.drop_last,
163
+ world_size=world_size,
164
+ rank=rank,
165
+ fs_local_rank=fs_local_rank,
166
+ work_dir=work_dir,
167
+ )
168
+ barrier()
169
+ out = DataLoader(
170
+ dataset,
171
+ batch_size=train_config.device_train_batch_size,
172
+ drop_last=train_config.data.drop_last,
173
+ collate_fn=collator,
174
+ num_workers=train_config.data.num_workers,
175
+ pin_memory=train_config.data.pin_memory,
176
+ prefetch_factor=None if train_config.data.num_workers == 0 else train_config.data.prefetch_factor,
177
+ persistent_workers=False if train_config.data.num_workers == 0 else train_config.data.persistent_workers,
178
+ timeout=train_config.data.timeout,
179
+ )
180
+ return out
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.05 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/collator.cpython-310.pyc ADDED
Binary file (4.86 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/custom_datasets.cpython-310.pyc ADDED
Binary file (2.39 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/iterable_dataset.cpython-310.pyc ADDED
Binary file (5.73 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/memmap_dataset.cpython-310.pyc ADDED
Binary file (8.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/__pycache__/util.cpython-310.pyc ADDED
Binary file (4.13 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/collator.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional, Union
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ from ..config import PaddingDirection, TrainConfig
10
+
11
+ __all__ = ["DataCollator"]
12
+
13
+
14
+ @dataclass
15
+ class DataCollator:
16
+ pad_direction: PaddingDirection
17
+ pad_token_id: int
18
+
19
+ @classmethod
20
+ def from_train_config(cls, config: TrainConfig) -> DataCollator:
21
+ return cls(pad_direction=config.data.pad_direction, pad_token_id=config.model.pad_token_id)
22
+
23
+ def __call__(self, items: Union[List[Dict[str, Any]], List[torch.Tensor]]) -> Dict[str, Any]:
24
+ assert items
25
+ max_len = max((len(x["input_ids"] if isinstance(x, dict) else x) for x in items))
26
+ all_input_ids = []
27
+ all_attention_mask = []
28
+ all_attention_bias = []
29
+ all_label_mask = []
30
+ all_indices = []
31
+ all_metadata = []
32
+ all_instance_mask = []
33
+ all_doc_lens = []
34
+ all_max_doc_lens = []
35
+ max_docs = max((len(x["doc_lens"]) if isinstance(x, dict) and "doc_lens" in x else 0 for x in items))
36
+
37
+ for x in items:
38
+ input_ids = x["input_ids"] if isinstance(x, dict) else x
39
+ if not isinstance(input_ids, torch.Tensor):
40
+ input_ids = torch.tensor(input_ids)
41
+
42
+ pad_shape = (
43
+ (max_len - len(input_ids), 0)
44
+ if self.pad_direction == PaddingDirection.left
45
+ else (0, max_len - len(input_ids))
46
+ )
47
+
48
+ # Pad input IDs.
49
+ all_input_ids.append(
50
+ F.pad(
51
+ input_ids.to(dtype=torch.long),
52
+ pad_shape,
53
+ value=self.pad_token_id,
54
+ )
55
+ )
56
+
57
+ # Pad attention mask.
58
+ attention_mask = x.get("attention_mask") if isinstance(x, dict) else None
59
+ if attention_mask is not None:
60
+ if not isinstance(attention_mask, torch.Tensor):
61
+ attention_mask = torch.tensor(attention_mask)
62
+ all_attention_mask.append(
63
+ F.pad(
64
+ attention_mask.to(dtype=torch.float),
65
+ pad_shape,
66
+ value=0.0,
67
+ )
68
+ )
69
+
70
+ # Pad attention bias.
71
+ attention_bias = x.get("attention_bias") if isinstance(x, dict) else None
72
+ if attention_bias is not None:
73
+ if not isinstance(attention_bias, torch.Tensor):
74
+ attention_bias = torch.tensor(attention_bias)
75
+ # Reshape to `(1, seq_len, seq_len)`
76
+ while len(attention_bias.shape) < 3:
77
+ attention_bias = attention_bias.unsqueeze(0)
78
+ pad_value = False if attention_bias.dtype == torch.bool else float("-inf")
79
+ all_attention_bias.append(
80
+ F.pad(
81
+ attention_bias,
82
+ pad_shape + pad_shape,
83
+ value=pad_value,
84
+ )
85
+ )
86
+
87
+ # Pad label mask.
88
+ label_mask = x.get("label_mask") if isinstance(x, dict) else None
89
+ if label_mask is not None:
90
+ if not isinstance(label_mask, torch.Tensor):
91
+ label_mask = torch.tensor(label_mask)
92
+ all_label_mask.append(
93
+ F.pad(
94
+ label_mask.to(dtype=torch.bool),
95
+ pad_shape,
96
+ value=False,
97
+ )
98
+ )
99
+
100
+ # Indices.
101
+ index = x.get("index") if isinstance(x, dict) else None
102
+ if index is not None:
103
+ all_indices.append(torch.tensor(index))
104
+
105
+ # Instance mask.
106
+ instance_mask = x.get("instance_mask") if isinstance(x, dict) else None
107
+ if instance_mask is not None:
108
+ all_instance_mask.append(torch.tensor(instance_mask))
109
+
110
+ # Document lengths.
111
+ doc_lens = x.get("doc_lens") if isinstance(x, dict) else None
112
+ if doc_lens is not None:
113
+ doc_pad_shape = (0, max_docs - len(doc_lens))
114
+ all_doc_lens.append(F.pad(doc_lens, doc_pad_shape, value=0))
115
+ all_max_doc_lens.append(int(doc_lens.max()))
116
+
117
+ # Metadata.
118
+ metadata = x.get("metadata") if isinstance(x, dict) else None
119
+ if metadata is not None:
120
+ all_metadata.append(metadata)
121
+
122
+ out: Dict[str, Any] = {"input_ids": torch.stack(all_input_ids)}
123
+ if all_attention_mask:
124
+ out["attention_mask"] = torch.stack(all_attention_mask)
125
+ if all_attention_bias:
126
+ out["attention_bias"] = torch.stack(all_attention_bias)
127
+ if all_label_mask:
128
+ out["label_mask"] = torch.stack(all_label_mask)
129
+ if all_indices:
130
+ out["index"] = torch.stack(all_indices)
131
+ if all_instance_mask:
132
+ out["instance_mask"] = torch.stack(all_instance_mask)
133
+ if all_doc_lens:
134
+ out["doc_lens"] = torch.stack(all_doc_lens)
135
+ if all_max_doc_lens:
136
+ out["max_doc_lens"] = all_max_doc_lens
137
+ if all_metadata:
138
+ out["metadata"] = all_metadata
139
+
140
+ return out
141
+
142
+
143
+ @dataclass
144
+ class CustomDatasetDataCollator(DataCollator):
145
+ input_id_field: str = "input_ids"
146
+ attention_mask_field: Optional[str] = None
147
+ attention_bias_field: Optional[str] = None
148
+ label_mask_field: Optional[str] = None
149
+ index_field: Optional[str] = None
150
+ instance_mask_field: Optional[str] = None
151
+ doc_lens_field: Optional[str] = None
152
+ metadata_field: Optional[str] = None
153
+
154
+ def _relabel_fields(self, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
155
+ return [self._relabel_item(x) for x in items]
156
+
157
+ def _relabel_item(self, item: Dict[str, Any]) -> Dict[str, Any]:
158
+ out = {
159
+ "input_ids": item[self.input_id_field],
160
+ "attention_mask": item[self.attention_mask_field] if self.attention_mask_field else None,
161
+ "attention_bias": item[self.attention_bias_field] if self.attention_bias_field else None,
162
+ "label_mask": item[self.label_mask_field] if self.label_mask_field else None,
163
+ "index": item[self.index_field] if self.index_field else None,
164
+ "instance_mask": item[self.instance_mask_field] if self.instance_mask_field else None,
165
+ "metadata": item[self.metadata_field] if self.metadata_field else None,
166
+ }
167
+ if self.doc_lens_field:
168
+ out["doc_lens"] = item.__getitem__(self.doc_lens_field)
169
+ return out
170
+
171
+ def __call__(self, items: Union[List[Dict[str, Any]], List[torch.Tensor]]) -> Dict[str, Any]:
172
+ if not isinstance(items[0], torch.Tensor):
173
+ items = self._relabel_fields(items)
174
+ return super().__call__(items)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/custom_datasets.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import logging
3
+ from typing import Optional, Tuple
4
+
5
+ from torch.utils.data import Dataset
6
+
7
+ from ..config import TrainConfig
8
+ from ..exceptions import OLMoConfigurationError
9
+
10
+ __all__ = ["build_custom_dataset"]
11
+
12
+ LOGGER = logging.getLogger(__name__)
13
+
14
+
15
+ def build_custom_dataset(train_config: TrainConfig) -> Dataset:
16
+ """Returns an instance custom dataset class from the specified custom module and class name in the train config.
17
+ Assumes that the returned class implements the Pytorch Dataset interface. Responsibility
18
+ for ensuring that the class implements the interface is left to the user.
19
+
20
+ Instantiates the class with the arguments specified in the train config.
21
+
22
+ :param train_config: OLMo train config
23
+ :raises OLMoConfigurationError: if the custom dataset class is not specified or the module cannot be determined
24
+ :return: Instantiated custom dataset class
25
+ """
26
+ assert train_config.data.custom_dataset is not None
27
+ if not train_config.data.custom_dataset.name:
28
+ raise OLMoConfigurationError("custom_dataset_class is required when using a custom dataset")
29
+ LOGGER.warning("Using custom dataset class, deterministic training is not guaranteed")
30
+ LOGGER.info(
31
+ f"Loading custom dataset {train_config.data.custom_dataset.name} from module {train_config.data.custom_dataset.module}"
32
+ )
33
+ dataset_class = train_config.data.custom_dataset.name
34
+ dataset_module = train_config.data.custom_dataset.module
35
+ if not dataset_module:
36
+ dataset_module, dataset_class = extract_module_and_class(dataset_class)
37
+ if dataset_module is None:
38
+ raise OLMoConfigurationError(
39
+ "when using custom_dataset_class, use the full module path of the class or specify custom_dataset_module"
40
+ )
41
+ module = importlib.import_module(dataset_module)
42
+ dataset_class = getattr(module, dataset_class)
43
+ return dataset_class(**train_config.data.custom_dataset.args) # type: ignore
44
+
45
+
46
+ def extract_module_and_class(name: str) -> Tuple[Optional[str], str]:
47
+ """Extracts the module and class name from a full name. Returns None for the module if the name does not contain a dot.
48
+
49
+ :param name: Full name of a class or function, e.g. "foo.bar.Baz"
50
+ :return: Tuple of module and class name, e.g. ("foo.bar", "Baz") if name is "foo.bar.Baz"
51
+ """
52
+ class_module = name.split(".")
53
+ if len(class_module) < 2:
54
+ return None, class_module[0]
55
+ return ".".join(class_module[:-1]), class_module[-1]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/iterable_dataset.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import logging
3
+ import math
4
+ from pathlib import Path
5
+ from typing import Any, Dict, Iterator, List, Optional, Sequence, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.utils.data
10
+
11
+ from ..aliases import PathOrStr
12
+ from ..torch_util import barrier, get_fs_local_rank, get_global_rank, get_world_size
13
+ from ..util import roundrobin, threaded_generator
14
+
15
+ __all__ = ["IterableDataset"]
16
+
17
+ log = logging.getLogger(__name__)
18
+
19
+
20
+ class IterableDataset(torch.utils.data.IterableDataset[Dict[str, Any]]):
21
+ """
22
+ Adapted from PyTorch's DistributedSampler, this wraps a Dataset or arbitrary sequence
23
+ as an IterableDataset that can be deterministically restarted at any point by setting `start_index`,
24
+ which should be a multiple of your global batch size.
25
+ Similarly `max_examples`, if set, should be a multiple of global batch size.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ dataset: Union[Sequence[List[int]], Sequence[torch.Tensor], Sequence[Dict[str, Any]]],
31
+ global_batch_size: int,
32
+ *,
33
+ seed: int = 0,
34
+ epoch: int = 0,
35
+ start_index: int = 0,
36
+ max_examples: Optional[int] = None,
37
+ shuffle: bool = True,
38
+ drop_last: bool = False,
39
+ world_size: Optional[int] = None,
40
+ rank: Optional[int] = None,
41
+ fs_local_rank: Optional[int] = None,
42
+ work_dir: Optional[PathOrStr] = None,
43
+ num_threads: Optional[int] = None,
44
+ ):
45
+ self.dataset = dataset
46
+ self.seed = seed
47
+ self.epoch = epoch
48
+ self.start_index = start_index
49
+ self.max_examples = max_examples
50
+ self.shuffle = shuffle
51
+ self.drop_last = drop_last
52
+ self.rank = rank if rank is not None else get_global_rank()
53
+ self.fs_local_rank = fs_local_rank if fs_local_rank is not None else get_fs_local_rank()
54
+ self.world_size = world_size if world_size is not None else get_world_size()
55
+ # If the dataset length is evenly divisible by # of replicas, then there
56
+ # is no need to drop any data, since the dataset will be split equally.
57
+ if self.drop_last and len(self.dataset) % self.world_size != 0: # type: ignore[arg-type]
58
+ # Split to nearest available length that is evenly divisible by world size.
59
+ # This is to ensure each rank receives the same amount of data.
60
+ num_samples = math.ceil(
61
+ (len(self.dataset) - self.world_size) / self.world_size # type: ignore[arg-type]
62
+ )
63
+ else:
64
+ num_samples = math.ceil(len(self.dataset) / self.world_size) # type: ignore[arg-type]
65
+ self.total_size = num_samples * self.world_size
66
+ self.num_threads = num_threads
67
+ assert global_batch_size % self.world_size == 0
68
+ self.device_batch_size = global_batch_size // self.world_size
69
+ self.global_indices_file: Optional[Path] = None
70
+ self.work_dir = work_dir
71
+
72
+ if work_dir is not None:
73
+ self._build_and_save_global_indices()
74
+
75
+ def _build_and_save_global_indices(self):
76
+ assert self.work_dir is not None
77
+ self.global_indices_file = Path(self.work_dir) / "global_indices.npy"
78
+ if self.fs_local_rank == 0:
79
+ log.info("Saving global data order indices...")
80
+ self.global_indices_file.parent.mkdir(parents=True, exist_ok=True)
81
+ global_indices = self._build_global_indices()
82
+ global_indices_mmap = np.memmap(
83
+ self.global_indices_file, dtype=np.uint32, mode="w+", shape=(len(global_indices),)
84
+ )
85
+ global_indices_mmap[:] = global_indices
86
+ global_indices_mmap.flush()
87
+ del global_indices_mmap
88
+ log.info("Global data order indices saved to '%s'", self.global_indices_file)
89
+ barrier()
90
+
91
+ def _build_global_indices(self) -> np.ndarray:
92
+ assert len(self.dataset) < np.iinfo(np.uint32).max
93
+ indices = np.arange(len(self.dataset), dtype=np.uint32)
94
+ if self.shuffle:
95
+ # Deterministically shuffle based on epoch and seed
96
+ # Torch built-in randomness is not very random, so we use numpy.
97
+ rng = np.random.Generator(np.random.PCG64(seed=self.seed + self.epoch))
98
+ rng.shuffle(indices)
99
+
100
+ if not self.drop_last:
101
+ # Add extra samples to make it evenly divisible
102
+ padding_size = self.total_size - len(indices)
103
+ arrays_to_concatenate = [indices]
104
+ while padding_size > 0:
105
+ array_to_concatenate = indices[: min(padding_size, len(indices))]
106
+ arrays_to_concatenate.append(array_to_concatenate)
107
+ padding_size -= len(array_to_concatenate)
108
+ del array_to_concatenate
109
+ indices = np.concatenate(arrays_to_concatenate)
110
+ else:
111
+ # Remove tail of data to make it evenly divisible.
112
+ indices = indices[: self.total_size]
113
+ assert len(indices) == self.total_size
114
+ return indices
115
+
116
+ def get_global_indices(self) -> np.ndarray:
117
+ if self.global_indices_file is not None:
118
+ return np.memmap(self.global_indices_file, mode="r", dtype=np.uint32) # type: ignore
119
+ else:
120
+ return self._build_global_indices()
121
+
122
+ def reshuffle(self, epoch: int):
123
+ self.epoch = epoch
124
+ if self.work_dir is not None:
125
+ self._build_and_save_global_indices()
126
+
127
+ def __iter__(self) -> Iterator[Dict[str, Any]]:
128
+ indices = self.get_global_indices()
129
+
130
+ # Truncate to max_examples.
131
+ if self.max_examples is not None:
132
+ assert self.max_examples % self.world_size == 0
133
+ indices = indices[: self.max_examples]
134
+
135
+ # Start at the specified index.
136
+ if self.start_index > 0:
137
+ # assert self.start_index % self.world_size == 0
138
+ indices = indices[self.start_index :]
139
+
140
+ # Slice indices by rank to avoid duplicates.
141
+ indices = indices[self.rank : self.total_size : self.world_size]
142
+
143
+ # Separate from data loading workers (which use multiprocessing), we also have the option
144
+ # to use multi-threading (within workers).
145
+ num_threads = self.num_threads
146
+
147
+ # Slice the indices by data loader worker rank to avoid duplicates.
148
+ worker_info = torch.utils.data.get_worker_info()
149
+ if worker_info is not None:
150
+ # Note that each data loading worker gathers a whole batch at a time, and the workers
151
+ # are called round-robin by rank. So to slice these up in a way that preserves order, regardless
152
+ # of the number of workers, we should give worker 0 the first chunk of `device_batch_size` indices,
153
+ # worker 1 the 2nd chunk of `device_train_batch_size` indices, etc...
154
+ truncated_size = self.device_batch_size * (len(indices) // self.device_batch_size)
155
+ left_overs = indices[truncated_size + worker_info.id :: worker_info.num_workers]
156
+ indices = (
157
+ indices[:truncated_size]
158
+ .reshape((-1, self.device_batch_size))[worker_info.id :: worker_info.num_workers] # type: ignore
159
+ .reshape((-1,))
160
+ )
161
+ indices = np.concatenate([indices, left_overs])
162
+ elif num_threads is None:
163
+ # If `num_threads` hasn't been specified and we're not using multiprocessing we'll try to guess
164
+ # a good number of threads.
165
+ num_threads = 4
166
+
167
+ # Finally, potentially slice by threads.
168
+ if num_threads:
169
+ # In order to stay ahead of training the total queue size (sum across all threads)
170
+ # should be bigger than the batch size.
171
+ queue_size = math.ceil(self.device_batch_size * 2 / num_threads)
172
+
173
+ thread_generators = []
174
+ for i in range(num_threads):
175
+ generator = (self._get_dataset_item(int(idx)) for idx in indices[i::num_threads])
176
+ thread_generators.append(
177
+ threaded_generator(generator, maxsize=queue_size, thread_name=f"data thread {i}")
178
+ )
179
+
180
+ return (x for x in roundrobin(*thread_generators))
181
+ else:
182
+ return (self._get_dataset_item(int(idx)) for idx in indices)
183
+
184
+ def _get_dataset_item(self, idx: int) -> Dict[str, Any]:
185
+ item = self.dataset[idx]
186
+ if isinstance(item, dict):
187
+ return dict(**item, index=idx)
188
+ elif dataclasses.is_dataclass(item):
189
+ return dict(**dataclasses.asdict(item), index=idx) # type: ignore
190
+ else:
191
+ return {"input_ids": item, "index": idx}
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/memmap_dataset.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from copy import deepcopy
4
+ from typing import Any, Dict, List, Optional, Tuple, Type, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ from torch.utils.data import Dataset
9
+
10
+ from olmo.exceptions import OLMoEnvironmentError
11
+
12
+ from ..aliases import PathOrStr
13
+ from ..config import InstanceFilterConfig
14
+ from ..util import _get_s3_client, file_size, get_bytes_range
15
+ from .util import find_periodic_sequences, get_document_lengths
16
+
17
+ __all__ = ["MemMapDataset"]
18
+
19
+
20
+ class MemMapDataset(Dataset[Dict[str, Any]]):
21
+ """
22
+ A PyTorch :class:`~torch.utils.data.Dataset` backed by one or more numpy memory-mapped arrays
23
+ of token IDs. Token IDs are chunked together into contiguous blocks of ``chunk_size``
24
+ to create instances.
25
+
26
+ If the length of a memory-mapped array is not a multiple of ``chunk_size`` the
27
+ remainder of the tokens will be ignored.
28
+
29
+ No special tokens are added to the input IDs so it's assumed that if you want
30
+ EOS tokens between documents, for example, those will already be in the memory-mapped array.
31
+
32
+ :param paths: Paths to memory-mapped token arrays.
33
+ :param chunk_size: The number of tokens to chunk together into a single instance.
34
+ Generally this should correspond to your model's maximum input length.
35
+ :param memmap_dtype: The numpy datatype of the memory-mapped array.
36
+ :param metadata: Metadata to add to each item. This should be a dictionary or a list of dictionaries
37
+ with the same number of items as there are paths.
38
+ :param include_instance_metadata: If ``True`` (the default), each instance returned from `__getitem__` will
39
+ include the metadata from its source.
40
+ :param generate_attention_mask: If ``True``, each instance returned from ``__getitem__`` will include an
41
+ attention mask generated by masking each padding token.
42
+ :param pad_token_id: The ID of the padding token. Required if ``generate_attention_mask`` is ``True``.
43
+ :param label_mask_paths: Optional paths to ``np.bool_`` memory-mapped arrays of label masks.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ *paths: PathOrStr,
49
+ chunk_size: int = 1024,
50
+ memmap_dtype: Union[Type[np.uint8], Type[np.uint16], Type[np.uint32], Type[np.uint64]] = np.uint16,
51
+ metadata: Optional[Union[List[Dict[str, Any]], Dict[str, Any]]] = None,
52
+ include_instance_metadata: bool = True,
53
+ generate_attention_mask: bool = False,
54
+ generate_doc_lengths: bool = False,
55
+ pad_token_id: Optional[int] = None,
56
+ eos_token_id: Optional[int] = None,
57
+ label_mask_paths: Optional[List[PathOrStr]] = None,
58
+ instance_filter_config: Optional[InstanceFilterConfig] = None,
59
+ ):
60
+ if not paths:
61
+ raise ValueError("At least one path is required")
62
+
63
+ if generate_attention_mask and pad_token_id is None:
64
+ raise ValueError("'pad_token_id' is required for 'generate_attention_mask'")
65
+
66
+ if generate_doc_lengths and eos_token_id is None:
67
+ raise ValueError("'eos_token_id' is required for 'generate_cu_doc_lengths'")
68
+
69
+ if label_mask_paths and len(label_mask_paths) != len(paths):
70
+ raise ValueError("There must be the same number of 'label_mask_paths' as there are 'paths'")
71
+
72
+ if isinstance(metadata, list):
73
+ if len(metadata) != len(paths):
74
+ raise ValueError("'metadata' should have the same length as the number of file paths")
75
+ else:
76
+ metadata = [metadata or {}] * len(paths)
77
+
78
+ self._memmap_paths = paths
79
+ self._metadata = metadata
80
+ self._label_mask_paths = label_mask_paths
81
+ self._chunk_size = chunk_size
82
+ self._mmap_offsets: Optional[List[Tuple[int, int]]] = None
83
+ self._num_instances: Optional[int] = None
84
+ self.dtype = memmap_dtype
85
+ self._include_instance_metadata = include_instance_metadata
86
+ self._generate_attention_mask = generate_attention_mask
87
+ self._generate_doc_lengths = generate_doc_lengths
88
+ self._pad_token_id = pad_token_id
89
+ self._eos_token_id = eos_token_id
90
+ self.instance_filter_config = instance_filter_config
91
+
92
+ @property
93
+ def chunk_size(self) -> int:
94
+ return self._chunk_size
95
+
96
+ @property
97
+ def max_seq_len(self) -> int:
98
+ # For compatibility with composer's SpeedMonitor callback.
99
+ return self.chunk_size
100
+
101
+ @property
102
+ def offsets(self) -> List[Tuple[int, int]]:
103
+ # Create the global S3 client up front to work around a threading issue in boto.
104
+ _get_s3_client("s3")
105
+ try:
106
+ _get_s3_client("r2")
107
+ except OLMoEnvironmentError:
108
+ # R2 might not be needed, so ignore this error. We will get an error
109
+ # later if R2 is needed.
110
+ pass
111
+ try:
112
+ _get_s3_client("weka")
113
+ except OLMoEnvironmentError:
114
+ # Weka might not be needed, so ignore this error. We will get an error
115
+ # later if Weka is needed.
116
+ pass
117
+
118
+ if self._mmap_offsets is None:
119
+ import concurrent.futures
120
+
121
+ self._mmap_offsets = []
122
+
123
+ path_to_length: Dict[PathOrStr, int] = {}
124
+ path_to_mask_path: Dict[PathOrStr, PathOrStr] = {}
125
+ mask_path_to_length: Dict[PathOrStr, int] = {}
126
+
127
+ with concurrent.futures.ThreadPoolExecutor() as executor:
128
+ path_futures = []
129
+ mask_path_futures = []
130
+ for i, path in enumerate(self._memmap_paths):
131
+ path_futures.append(executor.submit(self._get_file_length, path))
132
+ if self._label_mask_paths is not None:
133
+ mask_path = self._label_mask_paths[i]
134
+ path_to_mask_path[path] = mask_path
135
+ mask_path_futures.append(executor.submit(self._get_file_length, mask_path, np.bool_))
136
+
137
+ for future in concurrent.futures.as_completed(path_futures):
138
+ path, length = future.result()
139
+ path_to_length[path] = length
140
+
141
+ for future in concurrent.futures.as_completed(mask_path_futures):
142
+ path, length = future.result()
143
+ mask_path_to_length[path] = length
144
+
145
+ start_offset = 0
146
+ for path in self._memmap_paths:
147
+ length = path_to_length[path]
148
+ if mask_path_to_length:
149
+ mask_path = path_to_mask_path[path]
150
+ if length != mask_path_to_length[mask_path]:
151
+ raise ValueError(f"masking file '{mask_path}' should be the same size as '{path}'")
152
+ end_offset = start_offset + length
153
+ self._mmap_offsets.append((start_offset, end_offset))
154
+ start_offset += length
155
+ return self._mmap_offsets
156
+
157
+ def _read_chunk_from_memmap(self, path: PathOrStr, index: int, dtype=None) -> torch.Tensor:
158
+ dtype = dtype or self.dtype
159
+ item_size = dtype(0).itemsize
160
+ bytes_start = index * item_size * self._chunk_size
161
+ num_bytes = item_size * self._chunk_size
162
+ buffer = get_bytes_range(path, bytes_start, num_bytes)
163
+ array = np.frombuffer(buffer, dtype=dtype)
164
+ if dtype == np.bool_:
165
+ return torch.tensor(array)
166
+ else:
167
+ return torch.tensor(array.astype(np.int_), dtype=torch.long)
168
+
169
+ def _get_file_length(self, path, dtype=None) -> Tuple[PathOrStr, int]:
170
+ dtype = dtype or self.dtype
171
+ item_size = dtype(0).itemsize
172
+ return path, file_size(path) // (item_size * self._chunk_size)
173
+
174
+ def __len__(self) -> int:
175
+ if self._num_instances is None:
176
+ self._num_instances = self.offsets[-1][1]
177
+ return self._num_instances
178
+
179
+ def __getitem__(self, index: int) -> Dict[str, Any]:
180
+ index = int(index) # in case this is a numpy int type.
181
+ pos_index = index if index >= 0 else len(self) + index
182
+
183
+ # The index of the memmap array within 'self.memmaps'
184
+ memmap_index: Optional[int] = None
185
+ # The 'index' relative to the corresponding memmap array.
186
+ memmap_local_index: Optional[int] = None
187
+ for i, (offset_start, offset_end) in enumerate(self.offsets):
188
+ if offset_start <= pos_index < offset_end:
189
+ memmap_index = i
190
+ memmap_local_index = pos_index - offset_start
191
+
192
+ if memmap_index is None or memmap_local_index is None:
193
+ raise IndexError(f"{index} is out of bounds for dataset of size {len(self)}")
194
+
195
+ # Read the data from file.
196
+ input_ids = self._read_chunk_from_memmap(self._memmap_paths[memmap_index], memmap_local_index)
197
+ out: Dict[str, Any] = {"input_ids": input_ids}
198
+ if self.instance_filter_config is not None:
199
+ out["instance_mask"] = self._validate_instance(input_ids)
200
+
201
+ if self._label_mask_paths is not None:
202
+ label_mask = self._read_chunk_from_memmap(
203
+ self._label_mask_paths[memmap_index], memmap_local_index, dtype=np.bool_
204
+ )
205
+ out["label_mask"] = label_mask
206
+
207
+ if self._include_instance_metadata:
208
+ metadata = self._metadata[memmap_index]
209
+ out["metadata"] = deepcopy(metadata)
210
+
211
+ if self._generate_attention_mask:
212
+ assert self._pad_token_id is not None
213
+ attn_mask = torch.ones_like(input_ids)
214
+ attn_mask.masked_fill_(input_ids == self._pad_token_id, 0)
215
+ out["attention_mask"] = attn_mask
216
+
217
+ if self._generate_doc_lengths:
218
+ assert self._eos_token_id is not None
219
+ out["doc_lens"] = get_document_lengths(input_ids, self._eos_token_id)
220
+
221
+ return out
222
+
223
+ def __add__(self, other: MemMapDataset) -> MemMapDataset:
224
+ """
225
+ Concatenate one :class:`MemMapDataset` with another.
226
+ """
227
+ if not isinstance(other, MemMapDataset):
228
+ raise NotImplementedError(f"Expected another MemMapDataset but got {type(other)}")
229
+ return MemMapDataset(
230
+ *(self._memmap_paths + other._memmap_paths),
231
+ chunk_size=self._chunk_size,
232
+ memmap_dtype=self.dtype,
233
+ metadata=self._metadata + other._metadata,
234
+ )
235
+
236
+ def _validate_instance(self, input_ids: torch.Tensor) -> bool:
237
+ # Check for too many repeated ngrams.
238
+ # TODO: update `max_period` per Luca's suggestion.
239
+ if self.instance_filter_config is not None:
240
+ for m in find_periodic_sequences(
241
+ input_ids.numpy(),
242
+ max_period=self.instance_filter_config.repetition_max_period,
243
+ min_period=self.instance_filter_config.repetition_min_period,
244
+ ):
245
+ if m.times >= self.instance_filter_config.repetition_max_count:
246
+ return False
247
+ return True
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/named_data_mixes.py ADDED
The diff for this file is too large to render. See raw diff
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/data/util.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Generator, List, NamedTuple
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+
7
+ def find_end_first_consecutive_true(arr: np.ndarray) -> int:
8
+ """Function to find the end position of the first consecutive sequence of True in an array."""
9
+ if not arr[0]:
10
+ return 0
11
+
12
+ prog = np.cumsum(arr)
13
+ if prog[-1] == len(arr):
14
+ return len(arr)
15
+
16
+ true_locs = np.where(prog[:-1:] == prog[1::])[0]
17
+
18
+ return true_locs[0] + 1
19
+
20
+
21
+ def find_start_last_consecutive_true(arr: np.ndarray) -> int:
22
+ """Function to find the start position of the last consecutive sequence of True in an array."""
23
+ reverse = find_end_first_consecutive_true(arr[::-1])
24
+ return len(arr) - reverse if reverse > 0 else -1
25
+
26
+
27
+ def group_consecutive_values(arr: np.ndarray, stepsize: int = 1) -> List[np.ndarray]:
28
+ """Function to group consecutive values in an array."""
29
+ return np.split(arr, np.where(np.diff(arr) != stepsize)[0] + 1)
30
+
31
+
32
+ class RepetitionTuple(NamedTuple):
33
+ """Tuple to store information about a periodic sequence."""
34
+
35
+ start: int
36
+ end: int
37
+ period: int
38
+ times: int
39
+
40
+
41
+ def find_periodic_sequences(
42
+ arr: np.ndarray, max_period: int, min_period: int = 1, mask_value: int = -1
43
+ ) -> Generator[RepetitionTuple, None, None]:
44
+ """Function to find periodic sequences in an array.
45
+
46
+ This function sweeps through the array and checks for sequences of length
47
+ [min_period, max_period] that repeat at least 3 times. To do so, it
48
+ reshape the array into a matrix with `period` columns and checks if each
49
+ row is equal to the previous row. Blocks of repeating rows indicates repeating
50
+ sequences.
51
+
52
+ Because there's no guarantee that the sequences start at the beginning of each
53
+ row, it can only detect sequences that repeat at least 3 times. To account
54
+ for the fact that sequences may not start at the beginning of each row (or
55
+ end at the end of each row), we check the end of the previous row and the
56
+ start of the next row to determine the actual start and end positions of the
57
+ sequence.
58
+
59
+ Args:
60
+ arr (np.ndarray): The array to search for periodic sequences.
61
+ max_period (int): The maximum period to check for.
62
+ min_period (int, optional): The minimum period to check for. Defaults to 1.
63
+ mask_value (int, optional): The value to use to pad the array. Defaults to -1.
64
+ """
65
+ # make sure the mask_value is not in the array
66
+ if (arr == mask_value).sum() > 0:
67
+ raise ValueError("`mask_value` is in the array")
68
+
69
+ # no since we can only detect sequences that repeat at least 3 times,
70
+ # there is no point in checking for periods greater than 1/3 of the length
71
+ max_period = min(max_period, len(arr) // 3)
72
+
73
+ for period in range(min_period, max_period + 1):
74
+ # pad the array so that it can be reshaped into a matrix matching the period
75
+ padded_arr = np.pad(arr, (0, period - (len(arr) % period)), constant_values=mask_value)
76
+ shaped_arr = padded_arr.reshape(-1, period)
77
+
78
+ # find rows that are equal to the previous row; these are the possibly-periodic sequences
79
+ is_equal_to_prev_row = shaped_arr == np.roll(shaped_arr, shift=1, axis=0)
80
+ rows_with_period, *_ = np.where(is_equal_to_prev_row.all(axis=1))
81
+
82
+ # no sequences found with this period
83
+ if len(rows_with_period) == 0:
84
+ continue
85
+
86
+ # this finds the start and end positions of the sequences with period `period`
87
+ where_true_consecutive = group_consecutive_values(rows_with_period)
88
+
89
+ for sequence in where_true_consecutive:
90
+ start_row = sequence[0]
91
+ end_row = sequence[-1]
92
+
93
+ # we check if any value at the end of the previous row is True, e.g.:
94
+ # [[False, False, True, True]
95
+ # [True, True, True, True]]
96
+ # (in the case above, start offset is 2). If so, we subtract that from the
97
+ # period to get the actual start offset.
98
+ start_offset = find_start_last_consecutive_true(is_equal_to_prev_row[start_row - 1])
99
+ start_offset = period - start_offset if start_offset > 0 else 0
100
+
101
+ # same idea as above, we want to compute offset. Only difference is that
102
+ # `find_end_first_consecutive_true` already returns the offset, so we don't
103
+ # need to subtract from the period.
104
+ end_offset = find_end_first_consecutive_true(is_equal_to_prev_row[end_row + 1])
105
+
106
+ # because we are always comparing with preceding row in
107
+ # `is_equal_to_prev_row`, we need to subtract 1 from the row number
108
+ start_pos = (start_row - 1) * period - start_offset
109
+
110
+ # note that the end position is exclusive
111
+ end_pos = ((end_row + 1) * period) + end_offset
112
+
113
+ out = RepetitionTuple(
114
+ start=start_pos, end=end_pos, period=period, times=(end_pos - start_pos) // period
115
+ )
116
+ if out.times > 2:
117
+ # cannot accurately determine the period of a sequence that repeats
118
+ # less than 3 times with this algorithm
119
+ yield out
120
+
121
+
122
+ def get_document_lengths(input_ids: torch.Tensor, eos_token_id: int) -> torch.Tensor:
123
+ doc_boundaries = torch.cat(
124
+ [
125
+ torch.tensor([-1], dtype=torch.int32),
126
+ (input_ids == eos_token_id).nonzero(as_tuple=True)[0].to(dtype=torch.int32),
127
+ torch.tensor([] if input_ids[-1] == eos_token_id else [input_ids.shape[0] - 1], dtype=torch.int32),
128
+ ]
129
+ )
130
+ return doc_boundaries[1:] - doc_boundaries[:-1]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/eval/__init__.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Union
2
+
3
+ import torch
4
+ from torch.utils.data import DataLoader, DistributedSampler
5
+ from torchmetrics import MeanMetric, Metric
6
+
7
+ from ..config import EvaluatorConfig, EvaluatorType, TrainConfig
8
+ from ..exceptions import OLMoConfigurationError
9
+ from ..tokenizer import Tokenizer
10
+ from ..torch_util import get_global_rank, get_world_size
11
+ from .downstream import ICLMetric, label_to_task_map
12
+ from .evaluator import Evaluator
13
+
14
+ __all__ = [
15
+ "Evaluator",
16
+ "ICLMetric",
17
+ "label_to_task_map",
18
+ "build_downstream_evaluator",
19
+ "build_evaluator",
20
+ "build_evaluators",
21
+ ]
22
+
23
+
24
+ def build_downstream_evaluator(
25
+ train_config: TrainConfig,
26
+ eval_cfg: EvaluatorConfig,
27
+ tokenizer: Tokenizer,
28
+ device: torch.device,
29
+ is_unit_test=False,
30
+ ) -> Evaluator:
31
+ task_kwargs = {}
32
+ task_class = label_to_task_map[eval_cfg.label]
33
+ if isinstance(task_class, tuple):
34
+ task_class, task_kwargs = task_class
35
+ ds_eval_dataset = task_class(tokenizer=tokenizer, **task_kwargs) # type: ignore
36
+ data_config = eval_cfg.data
37
+ if is_unit_test:
38
+ ds_eval_sampler = None
39
+ else:
40
+ ds_eval_sampler = DistributedSampler(
41
+ ds_eval_dataset,
42
+ drop_last=data_config.drop_last,
43
+ shuffle=False,
44
+ num_replicas=get_world_size(),
45
+ rank=get_global_rank(),
46
+ seed=train_config.seed,
47
+ )
48
+ ds_eval_dataloader = DataLoader(
49
+ ds_eval_dataset,
50
+ batch_size=eval_cfg.device_eval_batch_size or train_config.device_eval_batch_size,
51
+ collate_fn=ds_eval_dataset.collate_fn,
52
+ num_workers=data_config.num_workers,
53
+ sampler=ds_eval_sampler,
54
+ pin_memory=data_config.pin_memory,
55
+ prefetch_factor=data_config.prefetch_factor,
56
+ persistent_workers=data_config.persistent_workers,
57
+ timeout=data_config.timeout,
58
+ )
59
+ metric = ICLMetric(metric_type=ds_eval_dataset.metric_type)
60
+
61
+ evaluator = Evaluator(
62
+ label=eval_cfg.label,
63
+ type=eval_cfg.type,
64
+ eval_loader=ds_eval_dataloader,
65
+ eval_metric=metric.to(device),
66
+ subset_num_batches=eval_cfg.subset_num_batches,
67
+ )
68
+ return evaluator
69
+
70
+
71
+ def build_evaluator(
72
+ train_config: TrainConfig, eval_config: EvaluatorConfig, tokenizer: Tokenizer, device: torch.device
73
+ ) -> Evaluator:
74
+ from ..data import build_eval_dataloader
75
+
76
+ if eval_config.type == EvaluatorType.downstream:
77
+ # Downstream evaluation.
78
+ return build_downstream_evaluator(train_config, eval_config, tokenizer, device)
79
+ elif eval_config.type == EvaluatorType.lm:
80
+ # Language modeling evaluation.
81
+ eval_loader = build_eval_dataloader(
82
+ train_config,
83
+ eval_config.data,
84
+ eval_config.device_eval_batch_size or train_config.device_eval_batch_size,
85
+ )
86
+
87
+ def make_metric():
88
+ return MeanMetric(nan_strategy="error").to(device)
89
+
90
+ eval_metric: Union[Metric, Dict[str, Metric]]
91
+ if eval_config.data.paths:
92
+ eval_metric = make_metric()
93
+ elif eval_config.data.datasets:
94
+ eval_metric = {label: make_metric() for label in eval_config.data.datasets.keys()}
95
+ else:
96
+ raise OLMoConfigurationError("One of DataConfig.paths or DataConfig.datasets is required")
97
+
98
+ return Evaluator(
99
+ label=eval_config.label,
100
+ type=eval_config.type,
101
+ eval_loader=eval_loader,
102
+ eval_metric=eval_metric,
103
+ subset_num_batches=eval_config.subset_num_batches,
104
+ )
105
+ else:
106
+ raise ValueError(f"Unexpected evaluator type '{eval_config.type}'")
107
+
108
+
109
+ def build_evaluators(cfg: TrainConfig, device: torch.device) -> List[Evaluator]:
110
+ evaluators = []
111
+ tokenizer = Tokenizer.from_train_config(cfg)
112
+ for eval_cfg in cfg.evaluators:
113
+ evaluators.append(build_evaluator(cfg, eval_cfg, tokenizer, device))
114
+ return evaluators
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/olmo/eval/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.08 kB). View file