/
serving.ex
1109 lines (887 loc) · 36.8 KB
/
serving.ex
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Nx.Serving do
@moduledoc """
Serving encapsulates client and server work to perform batched requests.
Servings can be executed on the fly, without starting a server, but most
often they are used to run servers that batch requests until a given size
or timeout is reached.
More specifically, servings are a mechanism to apply a computation on a
`Nx.Batch`, with hooks for preprocessing input from and postprocessing
output for the client. Thus we can think of an instance of `Nx.Serving.t()`
(a serving) as something that encapsulates batches of Nx computations.
## Inline/serverless workflow
First, let's define a simple numerical definition function:
defmodule MyDefn do
import Nx.Defn
defnp print_and_multiply(x) do
print_value({:debug, x})
x * 2
end
end
The function prints the given tensor and doubles its contents.
We can use `new/1` to create a serving that will return a JIT
or AOT compiled function to execute on batches of tensors:
iex> serving = Nx.Serving.new(fn opts -> Nx.Defn.jit(&print_and_multiply/1, opts) end)
iex> batch = Nx.Batch.stack([Nx.tensor([1, 2, 3])])
iex> Nx.Serving.run(serving, batch)
{:debug, #Nx.Tensor<
s64[1][3]
[
[1, 2, 3]
]
>}
#Nx.Tensor<
s64[1][3]
[
[2, 4, 6]
]
>
We started the serving by passing a function that receives
compiler options and returns a JIT or AOT compiled function.
We called `Nx.Defn.jit/2` passing the options received as
argument, which will customize the JIT/AOT compilation.
You should see two values printed. The former is the result of
`Nx.Defn.Kernel.print_value/1`, which shows the tensor that was
actually part of the computation and how it was batched.
The latter is the result of the computation.
When defining a `Nx.Serving`, we can also customize how the data is
batched by using the `client_preprocessing` as well as the result by
using `client_postprocessing` hooks. Let's give it another try:
iex> serving = (
...> Nx.Serving.new(fn opts -> Nx.Defn.jit(&print_and_multiply/1, opts) end)
...> |> Nx.Serving.client_preprocessing(fn input -> {Nx.Batch.stack(input), :client_info} end)
...> |> Nx.Serving.client_postprocessing(&{&1, &2, &3})
...> )
iex> Nx.Serving.run(serving, [Nx.tensor([1, 2]), Nx.tensor([3, 4])])
{:debug, #Nx.Tensor<
s64[2][2]
[
[1, 2],
[3, 4]
]
>}
{#Nx.Tensor<
s64[2][2]
[
[2, 4],
[6, 8]
]
>,
:server_info,
:client_info}
You can see the results are a bit different now. First of all, notice that
we were able to run the serving passing a list of tensors. Our custom
`client_preprocessing` function stacks those tensors into a batch of two
entries and returns a tuple with a `Nx.Batch` struct and additional client
information which we represent as the atom `:client_info`. The default
client preprocessing simply enforces a batch was given and returns no client
information.
Then the result is a triplet tuple, returned by the client
postprocessing function, containing the result, the server information
(which we will later learn how to customize), and the client information.
From this, we can infer the default implementation of `client_postprocessing`
simply returns the result, discarding the server and client information.
So far, `Nx.Serving` has not given us much. It has simply encapsulated the
execution of a function. Its full power comes when we start running our own
`Nx.Serving` process. That's when we will also learn why we have a `client_`
prefix in some of the function names.
## Stateful/process workflow
`Nx.Serving` allows us to define an Elixir process to handle requests.
This process provides several features, such as batching up to a given
size or time, partitioning, and distribution over a group of nodes.
To do so, we need to start a `Nx.Serving` process with a serving inside
a supervision tree:
children = [
{Nx.Serving,
serving: Nx.Serving.new(Nx.Defn.jit(&print_and_multiply/1)),
name: MyServing,
batch_size: 10,
batch_timeout: 100}
]
Supervisor.start_child(children, strategy: :one_for_one)
> Note: in your actual application, you want to make sure
> `Nx.Serving` comes early in your supervision tree, for example
> before your web application endpoint or your data processing
> pipelines, as those processes may end-up hitting Nx.Serving.
Now you can send batched runs to said process:
iex> batch = Nx.Batch.stack([Nx.tensor([1, 2, 3]), Nx.tensor([4, 5, 6])])
iex> Nx.Serving.batched_run(MyServing, batch)
{:debug, #Nx.Tensor<
s64[2][3]
[
[1, 2, 3],
[4, 5, 6]
]
>}
#Nx.Tensor<
s64[2][3]
[
[2, 4, 6],
[8, 10, 12]
]
>
In the example, we pushed a batch of 2 and eventually got a reply.
The process will wait for requests from other processes, for up to
100 milliseconds or until it gets 10 entries. Then it merges all
batches together and once the result is computed, it slices and
distributes those responses to each caller.
If there is any `client_preprocessing` function, it will be executed
before the batch is sent to the server. If there is any `client_postprocessing`
function, it will be executed after getting the response from the
server.
### Partitioning
You can start several partitions under th same serving by passing
`partitions: true` when starting the serving. The number of partitions
will be determined according your compiler and for which host it is
compiling.
For example, when creating the serving, you may pass the following
`defn_options`:
Nx.Serving.new(computation, compiler: EXLA, client: :cuda)
Now when booting up the serving:
children = [
{Nx.Serving,
serving: serving,
name: MyServing,
batch_size: 10,
batch_timeout: 100,
partitions: true}
]
If you have two GPUs, `batched_run/3` will now gather batches and send
them to the GPUs as they become available to process requests.
### Distribution
All `Nx.Serving`s are distributed by default. If the current machine
does not have an instance of `Nx.Serving` running, `batched_run/3` will
automatically look for one in the cluster. The nodes do not need to run
the same code and applications. It is only required that they run the
same `Nx` version.
The load balancing between servings is done randomly, however, the number
of partitions are considered if the `partitioned: true` option is also given.
For example, if you have a node with 2 GPUs and another with 4, the latter
will receive the double of requests compared to the former.
`batched_run/3` receives an optional `distributed_preprocessing` callback as
third argument for preprocessing the input for distributed requests. When
using libraries like EXLA or Torchx, the tensor is often allocated in memory
inside a third-party library so it is necessary to either transfer or copy
the tensor to the binary backend before sending it to another node.
This can be done by passing either `Nx.backend_transfer/1` or `Nx.backend_copy/1`
as third argument:
Nx.Serving.batched_run(MyDistributedServing, input, &Nx.backend_copy/1)
Use `backend_transfer/1` if you know the input will no longer be used.
Similarly, the serving has a `distributed_postprocessing` callback which can do
equivalent before sending the reply to the caller.
The servings are dispatched using Erlang Distribution. You can use
`Node.connect/1` to manually connect nodes. In a production setup, this is
often done with the help of libraries like [`libcluster`](https://github.com/bitwalker/libcluster).
## Advanced notes
### Module-based serving
In the examples so far, we have been using the default version of
`Nx.Serving`, which executes the given function for each batch.
However, we can also use `new/2` to start a module-based version of
`Nx.Serving` which gives us more control over both inline and process
workflows. A simple module implementation of a `Nx.Serving` could look
like this:
defmodule MyServing do
@behaviour Nx.Serving
defnp print_and_multiply(x) do
print_value({:debug, x})
x * 2
end
@impl true
def init(_inline_or_process, :unused_arg, [defn_options]) do
{:ok, Nx.Defn.jit(&print_and_multiply/1, defn_options)}
end
@impl true
def handle_batch(batch, 0, function) do
{:execute, fn -> {function.(batch), :server_info} end, function}
end
end
It has two functions. The first, `c:init/3`, receives the type of serving
(`:inline` or `:process`) and the serving argument. In this step,
we capture `print_and_multiply/1`as a jitted function.
The second function is called `handle_batch/3`. This function
receives a `Nx.Batch` and returns a function to execute.
The function itself must return a two element-tuple: the batched
results and some server information. The server information can
be any value and we set it to the atom `:server_info`.
Now let's give it a try by defining a serving with our module and
then running it on a batch:
iex> serving = Nx.Serving.new(MyServing, :unused_arg)
iex> batch = Nx.Batch.stack([Nx.tensor([1, 2, 3])])
iex> Nx.Serving.run(serving, batch)
{:debug, #Nx.Tensor<
s64[1][3]
[
[1, 2, 3]
]
>}
#Nx.Tensor<
s64[1][3]
[
[2, 4, 6]
]
>
From here on, you use `start_link/1` to start this serving in your
supervision and even customize `client_preprocessing/1` and
`client_postprocessing/1` callbacks to this serving, as seen in the
previous sections.
Note in our implementation above assumes it won't run partitioned.
In partitioned mode, `c:init/3` may receive multiple `defn_options`
as the third argument and `handle_batch/3` may receive another partition
besides 0.
"""
@doc false
@enforce_keys [:module, :arg]
defstruct [
:module,
:arg,
:client_preprocessing,
:client_postprocessing,
distributed_postprocessing: &Function.identity/1,
process_options: [],
defn_options: []
]
@type metadata() :: term()
@type client_info() :: term()
@type client_preprocessing() :: (term() -> {Nx.Batch.t(), client_info()})
@type client_postprocessing() :: (Nx.Container.t(), metadata(), client_info() -> term())
@type distributed_preprocessing() :: (term() -> term())
@type distributed_postprocessing() :: (term() -> term())
@type t :: %__MODULE__{
module: atom(),
arg: term(),
client_preprocessing: client_preprocessing(),
client_postprocessing: client_postprocessing(),
distributed_postprocessing: distributed_postprocessing(),
process_options: keyword(),
defn_options: keyword()
}
@axis 0
@doc """
The callback used to initialize the serving.
The first argument reveals if the serving is executed inline,
such as by calling `run/2`, by started with the process.
The second argument is the serving argument given to `new/2`.
The third argument option is a list of compiler options to be
used to compile each partition the serving will run.
It must return `{:ok, state}`, where the `state` can be any term.
"""
@callback init(type :: :inline | :process, arg :: term(), [defn_options :: keyword]) ::
{:ok, state :: term()}
@doc """
Receives a batch, a partition, and returns a function to execute the batch.
In case of serving processes, the function is executed is an
separate process.
"""
@callback handle_batch(Nx.Batch.t(), partition :: non_neg_integer(), state) ::
{:execute, (() -> {Nx.Container.t(), metadata()}), state}
when state: term()
@doc """
Creates a new function serving.
It expects a function that receives the compiler options and
returns a JIT (via `Nx.Defn.jit/2`) or AOT compiled (via
`Nx.Defn.compile/3`) one-arity function as argument.
The function will be called with the arguments returned by the
`client_preprocessing` callback.
"""
def new(function, defn_options \\ [])
def new(function, defn_options)
when is_function(function, 1) and is_list(defn_options) do
new(Nx.Serving.Default, function, defn_options)
end
def new(function, process_options)
when is_function(function, 0) and is_list(process_options) do
IO.warn(
"passing a zero-arity function to Nx.Serving.new is deprecated, " <>
"please pass a single arity function that will receive the compiler options"
)
new(Nx.Serving.Default, fn _ -> function.() end, [])
|> process_options(process_options)
end
def new(module, arg) when is_atom(module) do
new(module, arg, [])
end
@doc """
Creates a new module-based serving.
It expects a module and an argument that is given to its `init`
callback.
A third optional argument called `defn_options` are additional
compiler options which will be given to the module. Those options
will be merged into `Nx.Defn.default_options/0`.
"""
def new(module, arg, defn_options) when is_atom(module) and is_list(defn_options) do
defn_options = Keyword.merge(Nx.Defn.default_options(), defn_options)
%Nx.Serving{module: module, arg: arg, defn_options: defn_options}
end
@doc """
Sets the client preprocessing function.
The default implementation creates a single element batch
with the given argument and is equivalent to `&Nx.Batch.stack([&1])`.
"""
def client_preprocessing(%Nx.Serving{} = serving, function)
when is_function(function, 1) or is_nil(function) do
%{serving | client_preprocessing: function}
end
@doc """
Sets the client postprocessing function.
The default implementation returns the first element given
to the function.
"""
def client_postprocessing(%Nx.Serving{} = serving, function)
when is_function(function, 3) or is_nil(function) do
%{serving | client_postprocessing: function}
end
@doc """
Sets the distributed postprocessing function.
The default implementation is `Function.identity/1`.
"""
def distributed_postprocessing(%Nx.Serving{} = serving, function)
when is_function(function, 1) do
%{serving | distributed_postprocessing: function}
end
@doc """
Sets the process options of this serving.
These are the same options as supported on `start_link/1`,
except `:name` and `:serving` itself.
"""
def process_options(%Nx.Serving{} = serving, process_options) when is_list(process_options) do
%{serving | process_options: process_options}
end
@doc """
Sets the defn options of this serving.
These are the options supported by `Nx.Defn.default_options/1`.
"""
def defn_options(%Nx.Serving{} = serving, defn_options) when is_list(defn_options) do
%{serving | defn_options: defn_options}
end
@doc """
Runs `serving` with the given `input` inline with the current process.
"""
def run(%Nx.Serving{} = serving, input) do
%{
module: module,
arg: arg,
client_preprocessing: preprocessing,
client_postprocessing: postprocessing,
defn_options: defn_options
} = serving
{:ok, state} = handle_init(module, :inline, arg, [defn_options])
{%{size: size} = batch, info} = handle_preprocessing(preprocessing, input)
{:execute, function, _} = handle_batch(module, batch, 0, state)
{output, metadata} =
:telemetry.span([:nx, :serving, :execute], %{module: module}, fn ->
{output, metadata} = handle_executed(module, function.())
{{output, metadata}, %{metadata: metadata, module: module}}
end)
output = Nx.Defn.Composite.traverse(output, &Nx.slice_along_axis(&1, 0, size, axis: @axis))
handle_postprocessing(postprocessing, output, metadata, info)
end
## Process API
@doc false
def child_spec(opts) when is_list(opts) do
name = opts[:name]
if name == nil or not is_atom(name) do
raise ArgumentError, ":name option is expected when starting Nx.Serving and must be an atom"
end
opts[:serving] ||
raise ArgumentError, ":serving option is expected when starting Nx.Serving"
%{
id: name,
start: {__MODULE__, :start_link, [opts]},
type: :supervisor
}
end
@doc """
Starts a `Nx.Serving` process to batch requests to a given serving.
## Options
* `:name` - an atom with the name of the process
* `:serving` - a `Nx.Serving` struct with the serving configuration
* `:batch_size` - the maximum batch size. A value is first read
from the `Nx.Serving` struct and then it falls back to this option
(which defaults to `1`)
* `:batch_timeout` - the maximum time to wait, in milliseconds,
before executing the batch. A value is first read from the `Nx.Serving`
struct and then it falls back to this option (which defaults to `100`ms)
* `:partitions` - when `true`, starts several partitions under this serving.
The number of partitions will be determined according to your compiler
and for which host it is compiling. See the module docs for more information
* `:shutdown` - the maximum time for the serving to shutdown. This will
block until the existing computation finishes (defaults to `30_000`ms)
* `:hibernate_after` and `:spawn_opt` - configure the underlying serving
workers (see `GenServer.start_link/3`)
"""
def start_link(opts) do
name = Keyword.fetch!(opts, :name)
{%Nx.Serving{process_options: process_options} = serving, opts} = Keyword.pop!(opts, :serving)
opts =
Keyword.merge(process_options, opts, fn
k, v1, v2 when k == :batch_size and v1 != v2 ->
raise ArgumentError,
"#{inspect(k)} has been set when starting an Nx.Serving process (#{inspect(v2)}) " <>
"but a conflicting value was already set on the Nx.Serving struct (#{inspect(v1)}). " <>
"Please remove the option given to the Nx.Serving process"
_k, _v1, v2 ->
v2
end)
{shutdown, opts} = Keyword.pop(opts, :shutdown, 30_000)
{partitions, opts} = Keyword.pop(opts, :partitions, false)
{batch_size, opts} = Keyword.pop(opts, :batch_size, 1)
{batch_timeout, opts} = Keyword.pop(opts, :batch_timeout, 100)
supervisor = Module.concat(name, "Supervisor")
task_supervisor = Module.concat(name, "TaskSupervisor")
arg = {name, serving, partitions, batch_size, batch_timeout, task_supervisor}
children = [
{Task.Supervisor, name: task_supervisor},
%{
id: __MODULE__,
start: {GenServer, :start_link, [__MODULE__, arg, opts]},
shutdown: shutdown
}
]
Supervisor.start_link(children, strategy: :one_for_all, max_restarts: 0, name: supervisor)
end
@doc """
Runs the given `input` on the serving process given by `name`.
`name` is either an atom representing a local or distributed
serving process. First it will attempt to dispatch locally, then it
falls back to the distributed serving. You may specify
`{:local, name}` to force a local lookup or `{:distributed, name}`
to force a distributed one.
The `client_preprocessing` callback will be invoked on the `input`
which is then sent to the server. The server will batch requests
and send a response either when the batch is full or on timeout.
Then `client_postprocessing` is invoked on the response. See the
module documentation for more information. In the distributed case,
the callbacks are invoked in the distributed node, but still outside of
the serving process.
Note that you cannot batch an `input` larger than the configured
`:batch_size` in the server.
## Distributed mode
To run in distributed mode, the nodes do not need to run the same
code and applications. It is only required that they run the
same `Nx` version.
If the current node is running a serving given by `name` locally
and `{:distributed, name}` is used, the request will use the same
distribution mechanisms instead of being handled locally, which
is useful for testing locally without a need to spawn nodes.
This function receives an optional `distributed_preprocessing` callback as
third argument for preprocessing the input for distributed requests. When
using libraries like EXLA or Torchx, the tensor is often allocated in memory
inside a third-party library so it is necessary to either transfer or copy
the tensor to the binary backend before sending it to another node.
This can be done by passing either `Nx.backend_transfer/1` or `Nx.backend_copy/1`
as third argument:
Nx.Serving.batched_run(MyDistributedServing, input, &Nx.backend_copy/1)
Use `backend_transfer/1` if you know the input will no longer be used.
Similarly, the serving has a `distributed_postprocessing` callback which can do
equivalent before sending the reply to the caller.
"""
def batched_run(name, input, distributed_preprocessing \\ &Function.identity/1)
def batched_run(name, input, distributed_preprocessing) when is_atom(name) do
if pid = Process.whereis(name) do
local_batched_run!(pid, name, input)
else
distributed_batched_run!(name, input, distributed_preprocessing)
end
end
def batched_run({:local, name}, input, _distributed_preprocessing) when is_atom(name) do
pid =
Process.whereis(name) || exit({:noproc, {__MODULE__, :local_batched_run, [name, input]}})
local_batched_run!(pid, name, input)
end
def batched_run({:distributed, name}, input, distributed_preprocessing) when is_atom(name) do
distributed_batched_run!(name, input, distributed_preprocessing)
end
defp local_batched_run!(pid, name, input) do
case local_batched_run(pid, name, input) do
{:ok, result} -> result
{:DOWN, reason} -> exit({reason, {__MODULE__, :local_batched_run, [name, input]}})
end
end
defp local_batched_run(pid, name, input) do
%{
preprocessing: preprocessing,
postprocessing: postprocessing,
limit: limit
} =
:persistent_term.get(persistent_key(name), nil) ||
raise(
ArgumentError,
"could not find Nx.Serving with name #{inspect(name)}. " <>
"Make sure your Nx.Serving is running and/or started as part of your supervision tree"
)
{batch, info} = handle_preprocessing(preprocessing, input)
if batch.size > limit do
raise ArgumentError,
"batch size (#{batch.size}) cannot exceed Nx.Serving server batch size of #{limit}"
end
# Use Process.monitor/2 on Elixir v1.15+
ref = :erlang.monitor(:process, pid, alias: :demonitor)
Process.send(pid, {__MODULE__, :batched_run, ref, batch}, [:noconnect])
case receive_batched(batch.size, ref, [], nil, name, input) do
{:ok, tensor, metadata} ->
{:ok, handle_postprocessing(postprocessing, tensor, metadata, info)}
{:DOWN, reason} ->
{:DOWN, reason}
end
end
defp receive_batched(0, ref, acc, {template, metadata}, _name, _input) do
Process.demonitor(ref, [:flush])
tensors =
acc
|> Enum.reverse()
|> Enum.zip_with(&Nx.concatenate(&1, axis: @axis))
{output, []} =
Nx.Defn.Composite.traverse(template, tensors, fn _template, [tensor | tensors] ->
{tensor, tensors}
end)
{:ok, output, metadata}
end
defp receive_batched(total_size, ref, acc, _template_metadata, name, input) do
receive do
{^ref, {start, size, output, metadata}} ->
# If we have a single response, slice and return immediately.
# Otherwise we collect their contents and build the concatenated result later.
if acc == [] and size == total_size do
Process.demonitor(ref, [:flush])
output =
Nx.Defn.Composite.traverse(output, &Nx.slice_along_axis(&1, start, size, axis: @axis))
{:ok, output, metadata}
else
funs =
output
|> Nx.Defn.Composite.reduce(
[],
&[Nx.slice_along_axis(&1, start, size, axis: @axis) | &2]
)
|> Enum.reverse()
receive_batched(total_size - size, ref, [funs | acc], {output, metadata}, name, input)
end
{:DOWN, ^ref, _, _, reason} ->
# We fake monitor messages, so still demonitor and flush.
Process.demonitor(ref, [:flush])
{:DOWN, reason}
end
end
defp distributed_batched_run!(name, input, distributed_callback) do
distributed_batched_run_with_retries!(name, distributed_callback.(input), 3)
end
defp distributed_batched_run_with_retries!(name, input, 0) do
exit({:noproc, {__MODULE__, :distributed_batched_run, [name, input, [retries: 0]]}})
end
defp distributed_batched_run_with_retries!(name, input, retries) do
case :pg.get_members(Nx.Serving.PG, __MODULE__) do
[] ->
exit({:noproc, {__MODULE__, :distributed_batched_run, [name, input, [retries: retries]]}})
entries ->
pid = Enum.random(entries)
ref = make_ref()
args = [ref, name, input]
{_, monitor_ref} =
Node.spawn_monitor(node(pid), __MODULE__, :__distributed_batched_run__, args)
receive do
{:DOWN, ^monitor_ref, _, _, {^ref, result}} ->
result
{:DOWN, _, _, _, :noproc} ->
distributed_batched_run_with_retries!(name, input, retries - 1)
{:DOWN, _, _, _, reason} ->
exit(
{reason, {__MODULE__, :distributed_batched_run, [name, input, [retries: retries]]}}
)
end
end
end
@doc false
def __distributed_batched_run__(ref, name, input) do
pid = Process.whereis(name) || exit(:noproc)
case local_batched_run(pid, name, input) do
{:ok, result} ->
result = :persistent_term.get(persistent_key(name)).distributed_postprocessing.(result)
exit({ref, result})
{:DOWN, reason} ->
exit(reason)
end
end
## Process callbacks
require Logger
@behaviour GenServer
@empty_stack {[], 0}
@empty_queue :queue.new()
@timeout_message {__MODULE__, :timeout}
@impl true
def init({name, serving, partitions, batch_size, batch_timeout, task_supervisor}) do
Process.flag(:trap_exit, true)
partitions = serving_partitions(serving, partitions)
partitions_count = length(partitions)
{:ok, module_state} = handle_init(serving.module, :process, serving.arg, partitions)
:persistent_term.put(
persistent_key(name),
%{
limit: batch_size,
preprocessing: serving.client_preprocessing,
postprocessing: serving.client_postprocessing,
distributed_postprocessing: serving.distributed_postprocessing
}
)
:pg.join(Nx.Serving.PG, __MODULE__, List.duplicate(self(), partitions_count))
# We keep batches in a stack. Once the stack is full
# or it times out, we either execute or enqueue it.
state = %{
module: serving.module,
module_state: module_state,
stack: @empty_stack,
limit: batch_size,
timeout: batch_timeout,
timer: :none,
in_queue: @empty_queue,
out_queue: Enum.reduce(0..(partitions_count - 1), :queue.new(), &:queue.in/2),
tasks: [],
task_supervisor: task_supervisor
}
{:ok, state}
end
defp serving_partitions(%Nx.Serving{defn_options: defn_options}, true) do
compiler = Keyword.get(defn_options, :compiler, Nx.Defn.Evaluator)
compiler.__partitions_options__(defn_options)
end
defp serving_partitions(%Nx.Serving{defn_options: defn_options}, false) do
[defn_options]
end
@impl true
def handle_info({__MODULE__, :batched_run, ref, %Nx.Batch{} = batch}, state) do
%{limit: limit, stack: {_, count}} = state
state =
cond do
# Single entry takes the whole batch.
# Execute what we have (if any) and execute a new one.
batch.size == limit ->
state
|> server_execute()
|> server_stack(ref, batch)
|> server_execute()
# First entry in batch.
count == 0 ->
state
|> server_timer()
|> server_stack(ref, batch)
# We don't exceed the limit.
batch.size + count < limit ->
server_stack(state, ref, batch)
# We go over the limit.
batch.size + count > limit ->
{current, next} = Nx.Batch.split(batch, limit - count)
state
|> server_stack(ref, current)
|> server_execute()
|> server_timer()
|> server_stack(ref, next)
# Exact match.
true ->
state
|> server_stack(ref, batch)
|> server_execute()
end
{:noreply, state}
end
def handle_info(@timeout_message, state) do
{:noreply, server_timeout(state)}
end
def handle_info({ref, :done}, %{tasks: tasks} = state) do
case Enum.split_with(tasks, &(elem(&1, 0).ref == ref)) do
{[{_task, partition, _ref_sizes}], tasks} ->
Process.demonitor(ref, [:flush])
{:noreply, server_task_done(state, tasks, partition)}
_ ->
{:noreply, state}
end
end
def handle_info({:DOWN, ref, :process, _process, reason}, %{tasks: tasks} = state) do
case Enum.split_with(tasks, &(elem(&1, 0).ref == ref)) do
{[{_task, partition, ref_sizes}], tasks} ->
server_reply_down(reason, ref_sizes)
{:noreply, server_task_done(state, tasks, partition)}
_ ->
{:noreply, state}
end
end
def handle_info(msg, state) do
Logger.warning("Unknown message in Nx.Serving: #{inspect(msg)}")
{:noreply, state}
end
@impl true
def terminate(_reason, %{tasks: tasks, in_queue: in_queue, stack: {stack, _}}) do
# Emulate the process is gone for entries in the queue
for {_batch, ref_sizes} <- :queue.to_list(in_queue) do
server_reply_down(:noproc, ref_sizes)
end
# As well as for entries in the stack
for {ref, _batch} <- stack do
send(ref, {:DOWN, ref, :process, self(), :noproc})
end
# And wait until all current tasks are processed
for {%Task{ref: ref}, _partition, ref_sizes} <- tasks do
receive do
{^ref, :done} -> Process.demonitor(ref, [:flush])
{:DOWN, ^ref, :process, _, reason} -> server_reply_down(reason, ref_sizes)
end
end
:ok
end
defp server_reply_down(reason, ref_sizes) do
for {ref, _start, _size} <- ref_sizes do
send(ref, {:DOWN, ref, :process, self(), reason})
end
end
defp server_stack(%{stack: {stack, count}, limit: limit} = state, ref, batch)
when batch.size + count <= limit do
%{state | stack: {[{ref, batch} | stack], count + batch.size}}
end
defp server_timer(%{timeout: timeout, timer: :none} = state),
do: %{state | timer: Process.send_after(self(), @timeout_message, timeout)}
defp server_execute(%{stack: @empty_stack} = state), do: state
defp server_execute(state) do
%{stack: {stack, count}, timer: timer} = state
if is_reference(timer) do
Process.cancel_timer(timer)
receive do
@timeout_message -> :ok
after
0 -> :ok
end
end
{ref_sizes, batches, _} =
Enum.reduce(stack, {[], [], count}, fn {ref, batch}, {ref_sizes, batches, ending} ->
size = batch.size
{[{ref, ending - size, size} | ref_sizes], [batch | batches], ending - size}
end)
state = %{state | timer: :none, stack: @empty_stack}
server_task_or_enqueue(state, Nx.Batch.merge(batches), ref_sizes)
end
defp server_task_or_enqueue(%{out_queue: out_queue} = state, batch, ref_sizes) do
case :queue.out(out_queue) do
{:empty, _out_queue} ->
%{state | in_queue: :queue.in({batch, ref_sizes}, state.in_queue)}
{{:value, partition}, out_queue} ->
%{module: module, module_state: module_state} = state
{:execute, function, module_state} = handle_batch(module, batch, partition, module_state)
wrapped_function = fn ->
:telemetry.span([:nx, :serving, :execute], %{module: module}, fn ->
{output, metadata} = function.()
for {ref, start, size} <- ref_sizes do
send(ref, {ref, {start, size, output, metadata}})
end
{:done, %{metadata: metadata, module: module}}
end)
end
task = Task.Supervisor.async_nolink(state.task_supervisor, wrapped_function)
tasks = [{task, partition, ref_sizes} | state.tasks]
%{state | module_state: module_state, tasks: tasks, out_queue: out_queue}
end
end
defp server_task_done(%{in_queue: in_queue, out_queue: out_queue} = state, tasks, partition) do
out_queue = :queue.in(partition, out_queue)
case :queue.out(in_queue) do
# The timer expired while the task was processing, so execute the current batch.
{:empty, _in_queue} when state.timer == :done ->
server_execute(%{state | tasks: tasks, out_queue: out_queue})
# Nothing to do.
{:empty, _in_queue} ->
%{state | tasks: tasks, out_queue: out_queue}
# Execute the next one in queue.
{{:value, {batch, ref_sizes}}, in_queue} ->
state = %{state | tasks: tasks, out_queue: out_queue, in_queue: in_queue}
server_task_or_enqueue(state, batch, ref_sizes)
end
end
# It timed out, the in queue is empty and out queue is not empty, execute it now.
defp server_timeout(%{out_queue: out_queue, in_queue: @empty_queue} = state)
when out_queue != @empty_queue,
do: server_execute(%{state | timer: :done})
# Otherwise continue batching until the queue is empty or it is full.
defp server_timeout(state),
do: %{state | timer: :done}