-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpy_ml_libs_SUITE.erl
More file actions
265 lines (244 loc) · 9.31 KB
/
Copy pathpy_ml_libs_SUITE.erl
File metadata and controls
265 lines (244 loc) · 9.31 KB
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
260
261
262
263
264
265
%%% @doc Regression contract for context thread affinity with real
%%% ML libraries.
%%%
%%% v3.0 fixed numpy / torch / tensorflow segfaults caused by the
%%% executor pool moving calls across OS threads. The fix is per-context
%%% worker pthreads with stable thread affinity. `py_thread_affinity_SUITE'
%%% checks the threading.get_native_id invariants in isolation;
%%% this suite drives actual numpy and tensorflow operations through
%%% exec / eval / call paths to confirm the libraries' thread-local
%%% state survives the round-trip.
%%%
%%% Skip-on-missing for both libraries: cases that need an unavailable
%%% module return {skip, ...} from init_per_testcase. TensorFlow is
%%% always skipped on CI (too heavy to install). Owngil cases additionally
%%% skip on Python <3.14.
-module(py_ml_libs_SUITE).
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2
]).
-export([
numpy_basic_ops/1,
numpy_call_thread_affinity/1,
numpy_parallel_processes/1,
numpy_owngil_basic/1,
tensorflow_basic_ops/1,
tensorflow_call_thread_affinity/1
]).
all() ->
[
numpy_basic_ops,
numpy_call_thread_affinity,
numpy_parallel_processes,
numpy_owngil_basic,
tensorflow_basic_ops,
tensorflow_call_thread_affinity
].
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(erlang_python),
%% Suppress TensorFlow's chatty C++ logging at import time.
%% Must be set before TF is imported in any context.
os:putenv("TF_CPP_MIN_LOG_LEVEL", "3"),
Config.
end_per_suite(_Config) ->
ok = application:stop(erlang_python),
ok.
init_per_testcase(TC, Config) ->
Mode = case TC of
numpy_owngil_basic -> owngil;
_ -> worker
end,
case Mode of
owngil ->
case py_nif:owngil_supported() of
false ->
{skip, "owngil mode requires Python 3.14+"};
true ->
setup_case(TC, Mode, Config)
end;
worker ->
setup_case(TC, Mode, Config)
end.
end_per_testcase(_TC, Config) ->
case proplists:get_value(ctx, Config) of
undefined -> ok;
Ctx -> py_context:stop(Ctx)
end.
%%% ---------------------------------------------------------------------------
%%% Helpers
%%% ---------------------------------------------------------------------------
setup_case(TC, Mode, Config) ->
case py_context:new(#{mode => Mode}) of
{ok, Ctx} ->
case require_module(Ctx, required_module(TC)) of
ok ->
[{ctx, Ctx} | Config];
{skip, _} = Skip ->
py_context:stop(Ctx),
Skip
end;
{error, Reason} ->
ct:fail({context_create_failed, Mode, Reason})
end.
required_module(numpy_basic_ops) -> "numpy";
required_module(numpy_call_thread_affinity) -> "numpy";
required_module(numpy_parallel_processes) -> "numpy";
required_module(numpy_owngil_basic) -> "numpy";
required_module(tensorflow_basic_ops) -> "tensorflow";
required_module(tensorflow_call_thread_affinity) -> "tensorflow".
%% Reflect the import status into a Python variable so we can
%% distinguish "module not installed" (skip) from any other error
%% (let it bubble up). A native-extension crash that surfaces as a
%% non-ImportError must not silently turn into a skip.
require_module(Ctx, Mod) ->
Code = iolist_to_binary([
"try:\n",
" import ", Mod, "\n",
" _import_status = 'ok'\n",
"except ImportError:\n",
" _import_status = 'not_found'\n"
]),
ok = py_context:exec(Ctx, Code),
{ok, Status} = py_context:eval(Ctx, <<"_import_status">>, #{}),
case Status of
<<"ok">> ->
ok;
<<"not_found">> ->
{skip, "Python module " ++ Mod ++ " not available"}
end.
native_id(Ctx) ->
{ok, Tid} = py_context:eval(Ctx,
<<"__import__('threading').get_native_id()">>, #{}),
Tid.
%%% ---------------------------------------------------------------------------
%%% numpy cases
%%% ---------------------------------------------------------------------------
numpy_basic_ops(Config) ->
Ctx = ?config(ctx, Config),
%% Define a numpy-backed function and exercise both call and eval
%% paths so a thread-state regression in either direction crashes.
ok = py_context:exec(Ctx, <<
"import numpy as np\n"
"def vec_dot_self(xs):\n"
" v = np.array(xs, dtype=np.float64)\n"
" return float(np.dot(v, v))\n"
>>),
{ok, 30.0} = py_context:call(Ctx, '__main__', vec_dot_self,
[[1.0, 2.0, 3.0, 4.0]]),
ok = py_context:exec(Ctx,
<<"_w = vec_dot_self([10.0, 0.0, 0.0])">>),
{ok, 100.0} = py_context:eval(Ctx, <<"_w">>, #{}),
ok.
numpy_call_thread_affinity(Config) ->
Ctx = ?config(ctx, Config),
ok = py_context:exec(Ctx, <<
"import numpy as np\n"
"import threading\n"
"def numpy_with_tid(xs):\n"
" v = np.array(xs, dtype=np.float64)\n"
" return (threading.get_native_id(), float(np.sum(v)))\n"
>>),
Results = [py_context:call(Ctx, '__main__', numpy_with_tid,
[[float(I), float(I + 1), float(I + 2)]])
|| I <- lists:seq(1, 50)],
Tids = [Tid || {ok, {Tid, _Sum}} <- Results],
Sums = [Sum || {ok, {_Tid, Sum}} <- Results],
50 = length(Tids),
[SingleTid] = lists:usort(Tids),
true = is_integer(SingleTid),
%% Spot-check a few sums.
Expected = [3.0 * I + 3.0 || I <- lists:seq(1, 50)],
Expected = Sums,
ok.
numpy_parallel_processes(Config) ->
Ctx = ?config(ctx, Config),
ok = py_context:exec(Ctx, <<
"import numpy as np\n"
"import threading\n"
"def numpy_dot_with_tid(xs, ys):\n"
" a = np.array(xs, dtype=np.float64)\n"
" b = np.array(ys, dtype=np.float64)\n"
" return (threading.get_native_id(), float(np.dot(a, b)))\n"
>>),
Parent = self(),
N = 8,
Pids = [spawn_link(fun() ->
Xs = [float(K * J) || J <- lists:seq(1, 4)],
Ys = [float(K + J) || J <- lists:seq(1, 4)],
R = py_context:call(Ctx, '__main__', numpy_dot_with_tid,
[Xs, Ys]),
Parent ! {result, K, R}
end) || K <- lists:seq(1, N)],
Results = [receive {result, K, R} -> {K, R} after 5000 -> ct:fail(timeout) end
|| _ <- Pids],
%% All calls converged on one thread.
Tids = [Tid || {_K, {ok, {Tid, _Sum}}} <- Results],
N = length(Tids),
[SingleTid] = lists:usort(Tids),
true = is_integer(SingleTid),
%% Each result matches the expected dot product.
lists:foreach(fun({K, {ok, {_Tid, Got}}}) ->
Xs = [float(K * J) || J <- lists:seq(1, 4)],
Ys = [float(K + J) || J <- lists:seq(1, 4)],
Expected = lists:sum([X * Y || {X, Y} <- lists:zip(Xs, Ys)]),
true = abs(Got - Expected) < 1.0e-9
end, Results),
%% Drain time + mailbox sanity (no orphan results).
timer:sleep(50),
{messages, []} = erlang:process_info(self(), messages),
ok.
numpy_owngil_basic(Config) ->
Ctx = ?config(ctx, Config),
%% Same shape as numpy_basic_ops but inside an OWN_GIL subinterpreter.
%% Numpy in OWN_GIL was the original v3.0 motivator on Python 3.14.
ok = py_context:exec(Ctx, <<
"import numpy as np\n"
"def vec_dot_self(xs):\n"
" v = np.array(xs, dtype=np.float64)\n"
" return float(np.dot(v, v))\n"
>>),
{ok, 30.0} = py_context:call(Ctx, '__main__', vec_dot_self,
[[1.0, 2.0, 3.0, 4.0]]),
{ok, 25.0} = py_context:call(Ctx, '__main__', vec_dot_self, [[5.0]]),
%% Confirm the thread is stable across owngil calls.
Tid1 = native_id(Ctx),
Tid2 = native_id(Ctx),
Tid1 = Tid2,
ok.
%%% ---------------------------------------------------------------------------
%%% tensorflow cases
%%% ---------------------------------------------------------------------------
tensorflow_basic_ops(Config) ->
Ctx = ?config(ctx, Config),
ok = py_context:exec(Ctx, <<
"import tensorflow as tf\n"
"def matmul_22():\n"
" a = tf.constant([[1.0, 2.0], [3.0, 4.0]])\n"
" return tf.linalg.matmul(a, a).numpy().tolist()\n"
>>),
{ok, [[7.0, 10.0], [15.0, 22.0]]} =
py_context:call(Ctx, '__main__', matmul_22, []),
ok.
tensorflow_call_thread_affinity(Config) ->
Ctx = ?config(ctx, Config),
ok = py_context:exec(Ctx, <<
"import tensorflow as tf\n"
"import threading\n"
"def tf_sum_with_tid(xs):\n"
" t = tf.constant(xs, dtype=tf.float64)\n"
" return (threading.get_native_id(),\n"
" float(tf.math.reduce_sum(t).numpy()))\n"
>>),
Results = [py_context:call(Ctx, '__main__', tf_sum_with_tid,
[[float(I), float(I + 1)]])
|| I <- lists:seq(1, 20)],
Tids = [Tid || {ok, {Tid, _Sum}} <- Results],
20 = length(Tids),
[SingleTid] = lists:usort(Tids),
true = is_integer(SingleTid),
ok.