Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
 
import os
import shutil
import struct
import tempfile
import unittest
 
import numpy as np
from onnx import TensorProto, helper, save
 
import onnxruntime as ort
 
 
class TestSymLinkOnnxModelExternalData(unittest.TestCase):
    def test_symlink_model_and_data_under_same_directory(self):
        # The following directory structure simulates huggingface hub local cache:
        # temp_dir/         (This corresponds to .cache/huggingface/hub/model_id/)
        #   blobs/
        #     guid1
        #     guid2
        #   snapshots/version/
        #       model.onnx -> ../../blobs/guid1
        #       data.bin   -> ../../blobs/guid2
 
        self.temp_dir = tempfile.mkdtemp()
        try:
            blobs_dir = os.path.join(self.temp_dir, "blobs")
            os.makedirs(blobs_dir)
 
            snapshots_dir = os.path.join(self.temp_dir, "snapshots", "version")
            os.makedirs(snapshots_dir)
 
            # Create real files in blobs
            # We'll use the helper to create the model, but we need to control where files end up.
            # Let's manually create the data file in blobs
            data_blob_path = os.path.join(blobs_dir, "guid2")
            vals = [float(i) for i in range(10)]
            with open(data_blob_path, "wb") as f:
                f.writelines(struct.pack("f", v) for v in vals)
 
            # Create model in blobs (referencing "data.bin" as external data)
            # When loaded from snapshots/version/model.onnx, ORT looks for snapshots/version/data.bin
 
            input_ = helper.make_tensor_value_info("input", TensorProto.FLOAT, [10])
            output = helper.make_tensor_value_info("output", TensorProto.FLOAT, [10])
            tensor = helper.make_tensor("external_data", TensorProto.FLOAT, [10], vals)
            tensor.data_location = TensorProto.EXTERNAL
            tensor.ClearField("float_data")
            tensor.ClearField("raw_data")
 
            k = tensor.external_data.add()
            k.key = "location"
            k.value = "data.bin"  # Relative path
 
            offset = tensor.external_data.add()
            offset.key = "offset"
            offset.value = "0"
 
            length = tensor.external_data.add()
            length.key = "length"
            length.value = str(len(vals) * 4)
 
            const_node = helper.make_node("Constant", [], ["const_out"], value=tensor)
            add_node = helper.make_node("Add", ["input", "const_out"], ["output"])
            graph = helper.make_graph([const_node, add_node], "test_graph", [input_], [output])
            # Model is opset-agnostic (Constant + Add); pin a released opset so ONNX 1.22
            # does not default to the under-development opset 27, which fails strict
            # ALLOW_RELEASED_ONNX_OPSET_ONLY legs (ValidateOpsetForDomain throws).
            model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 22)])
 
            model_blob_path = os.path.join(blobs_dir, "guid1")
            save(model, model_blob_path)
 
            # Now create symlinks in snapshots
            model_symlink_path = os.path.join(snapshots_dir, "model.onnx")
            data_symlink_path = os.path.join(snapshots_dir, "data.bin")
 
            try:
                os.symlink(model_blob_path, model_symlink_path)
                os.symlink(data_blob_path, data_symlink_path)
            except (OSError, NotImplementedError) as e:
                self.skipTest(f"Skipping symlink test: symlink creation is not supported in this environment: {e}")
 
            sess = ort.InferenceSession(model_symlink_path, providers=["CPUExecutionProvider"])
 
            input_data = np.zeros(10, dtype=np.float32)
            res = sess.run(["output"], {"input": input_data})
            expected = np.array([float(i) for i in range(10)], dtype=np.float32)
            np.testing.assert_allclose(res[0], expected)
 
        finally:
            shutil.rmtree(self.temp_dir)
 
    def test_symlink_with_data_in_model_sub_dir(self):
        # working directory structure (data is in model sub directory):
        # temp_dir/
        #   blobs/
        #     guid1
        #     data/guid2
        #   snapshots/version/
        #       model.onnx -> ../../blobs/guid1
        #       data.bin   -> ../../blobs/data/guid2
 
        self.temp_dir = tempfile.mkdtemp()
        try:
            blobs_dir = os.path.join(self.temp_dir, "blobs")
            os.makedirs(blobs_dir)
            data_dir = os.path.join(blobs_dir, "data")
            os.makedirs(data_dir)
 
            snapshots_dir = os.path.join(self.temp_dir, "snapshots", "version")
            os.makedirs(snapshots_dir)
 
            # Create real files in blobs
            # We'll use the helper to create the model, but we need to control where files end up.
            # Let's manually create the data file in blobs
            data_blob_path = os.path.join(data_dir, "guid2")
            vals = [float(i) for i in range(10)]
            with open(data_blob_path, "wb") as f:
                f.writelines(struct.pack("f", v) for v in vals)
 
            # Create model in blobs (referencing "data.bin" as external data)
            # When loaded from snapshots/version/model.onnx, ORT looks for snapshots/version/data.bin
 
            input_ = helper.make_tensor_value_info("input", TensorProto.FLOAT, [10])
            output = helper.make_tensor_value_info("output", TensorProto.FLOAT, [10])
            tensor = helper.make_tensor("external_data", TensorProto.FLOAT, [10], vals)
            tensor.data_location = TensorProto.EXTERNAL
            tensor.ClearField("float_data")
            tensor.ClearField("raw_data")
 
            k = tensor.external_data.add()
            k.key = "location"
            k.value = "data.bin"  # Relative path
 
            offset = tensor.external_data.add()
            offset.key = "offset"
            offset.value = "0"
 
            length = tensor.external_data.add()
            length.key = "length"
            length.value = str(len(vals) * 4)
 
            const_node = helper.make_node("Constant", [], ["const_out"], value=tensor)
            add_node = helper.make_node("Add", ["input", "const_out"], ["output"])
            graph = helper.make_graph([const_node, add_node], "test_graph", [input_], [output])
            # Model is opset-agnostic (Constant + Add); pin a released opset so ONNX 1.22
            # does not default to the under-development opset 27, which fails strict
            # ALLOW_RELEASED_ONNX_OPSET_ONLY legs (ValidateOpsetForDomain throws).
            model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 22)])
 
            model_blob_path = os.path.join(blobs_dir, "guid1")
            save(model, model_blob_path)
 
            # Now create symlinks in snapshots
            model_symlink_path = os.path.join(snapshots_dir, "model.onnx")
            data_symlink_path = os.path.join(snapshots_dir, "data.bin")
 
            try:
                os.symlink(model_blob_path, model_symlink_path)
                os.symlink(data_blob_path, data_symlink_path)
            except (OSError, NotImplementedError) as e:
                self.skipTest(f"Skipping symlink test: symlink creation is not supported in this environment: {e}")
 
            sess = ort.InferenceSession(model_symlink_path, providers=["CPUExecutionProvider"])
 
            input_data = np.zeros(10, dtype=np.float32)
            res = sess.run(["output"], {"input": input_data})
            expected = np.array([float(i) for i in range(10)], dtype=np.float32)
            np.testing.assert_allclose(res[0], expected)
 
        finally:
            shutil.rmtree(self.temp_dir)
 
    def test_symlink_with_data_not_in_model_sub_dir(self):
        # working directory structure (data is not in model directory or its sub directories):
        # temp_dir/
        #   model/
        #     guid1
        #   data/
        #     guid2
        #   snapshots/version/
        #       model.onnx -> ../../model/guid1
        #       data.bin   -> ../../data/guid2
 
        self.temp_dir = tempfile.mkdtemp()
        try:
            model_dir = os.path.join(self.temp_dir, "model")
            os.makedirs(model_dir)
            data_dir = os.path.join(self.temp_dir, "data")
            os.makedirs(data_dir)
 
            snapshots_dir = os.path.join(self.temp_dir, "snapshots", "version")
            os.makedirs(snapshots_dir)
 
            # Create real files in data_dir
            # We'll use the helper to create the model, but we need to control where files end up.
            # Let's manually create the data file in data_dir
            data_blob_path = os.path.join(data_dir, "guid2")
            vals = [float(i) for i in range(10)]
            with open(data_blob_path, "wb") as f:
                f.writelines(struct.pack("f", v) for v in vals)
 
            # Create model in model_dir (referencing "data.bin" as external data)
            # When loaded from snapshots/version/model.onnx, ORT looks for snapshots/version/data.bin
 
            input_ = helper.make_tensor_value_info("input", TensorProto.FLOAT, [10])
            output = helper.make_tensor_value_info("output", TensorProto.FLOAT, [10])
            tensor = helper.make_tensor("external_data", TensorProto.FLOAT, [10], vals)
            tensor.data_location = TensorProto.EXTERNAL
            tensor.ClearField("float_data")
            tensor.ClearField("raw_data")
 
            k = tensor.external_data.add()
            k.key = "location"
            k.value = "data.bin"  # Relative path
 
            offset = tensor.external_data.add()
            offset.key = "offset"
            offset.value = "0"
 
            length = tensor.external_data.add()
            length.key = "length"
            length.value = str(len(vals) * 4)
 
            const_node = helper.make_node("Constant", [], ["const_out"], value=tensor)
            add_node = helper.make_node("Add", ["input", "const_out"], ["output"])
            graph = helper.make_graph([const_node, add_node], "test_graph", [input_], [output])
            # Model is opset-agnostic (Constant + Add); pin a released opset so ONNX 1.22
            # does not default to the under-development opset 27, which fails strict
            # ALLOW_RELEASED_ONNX_OPSET_ONLY legs (ValidateOpsetForDomain throws).
            model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 22)])
 
            model_blob_path = os.path.join(model_dir, "guid1")
            save(model, model_blob_path)
 
            # Now create symlinks in snapshots
            model_symlink_path = os.path.join(snapshots_dir, "model.onnx")
            data_symlink_path = os.path.join(snapshots_dir, "data.bin")
 
            try:
                os.symlink(model_blob_path, model_symlink_path)
                os.symlink(data_blob_path, data_symlink_path)
            except (OSError, NotImplementedError) as e:
                self.skipTest(f"Skipping symlink test: symlink creation is not supported in this environment: {e}")
 
            with self.assertRaises(Exception) as cm:
                ort.InferenceSession(model_symlink_path, providers=["CPUExecutionProvider"])
 
            # We expect an error about external data not under model directory or the real model directory.
            self.assertIn("External data path validation failed", str(cm.exception))
        finally:
            shutil.rmtree(self.temp_dir)
 
 
if __name__ == "__main__":
    unittest.main()