/
core.jl
1751 lines (1480 loc) · 49.5 KB
/
core.jl
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
using ProtoBuf
using PyCall
using Compat
using Compat.Iterators
using MacroTools
using AutoHashEquals
import Base: setindex!, getindex, run, ==
const LIB_BASE = joinpath(dirname(@__FILE__), "..", "deps")
include("py.jl")
const LIBTF_PTR = Base.RefValue(C_NULL)
macro tfcall(sym, ret, args, vals...)
quote
tf_path = get(ENV,
"LIBTENSORFLOW",
joinpath(LIB_BASE, "usr", "bin", "libtensorflow"))
if LIBTF_PTR[] == C_NULL
LIBTF_PTR[] = Libdl.dlopen(expanduser(tf_path))
end
func = Libdl.dlsym(LIBTF_PTR[], $sym)
ccall(func, $(esc(ret)), $(esc(args)), $(esc.(vals)...))
end
end
"""
@required(keywords...)
Macro that raises an error if any of the passed-in symbols equal 'nothing'.
Useful for marking keyword arguments as required.
"""
macro required(keywords...)
blocks = []
for keyword in keywords
push!(blocks, quote
err_msg = string($(string(keyword)), " is required")
$(esc(keyword)) === nothing && error(err_msg)
end)
end
quote
$(blocks...)
end
end
mutable struct Status
ptr::Ptr{Void}
function Status()
ptr = @tfcall(:TF_NewStatus, Ptr{Void}, ())
this = new(ptr)
finalizer(this, status->begin
@tfcall(:TF_DeleteStatus, Void, (Ptr{Void},), status.ptr)
end)
this
end
end
function get_code(s::Status)
code = @tfcall(:TF_GetCode, Cint, (Ptr{Void},), s.ptr)
return TF_Code(code)
end
struct DevicePart{IndexType}
name::String
index::IndexType
end
device_index_from_zero(part::DevicePart{Int}) = "$(part.name):$(part.index-1)"
device_index_from_zero(part::DevicePart) = "$(part.name):$(part.index)"
struct Device
parts::Vector{DevicePart}
end
Device() = Device(DevicePart[])
function DevicePart(s::AbstractString)
parts = split(s, ":")
length(parts) == 2 || error("Invalid device: $s")
name = String(parts[1])
index_part = String(parts[2])
maybe_index = tryparse(Int, index_part)
if isnull(maybe_index)
index = index_part
else
index = get(maybe_index)
end
DevicePart(name, index)
end
function device_index_from_zero(device::Device)
b = IOBuffer()
for part in device.parts
print(b, "/")
print(b, device_index_from_zero(part))
end
String(take!(b))
end
Base.show(io::IO, part::DevicePart) = print(io, "$(part.name):$(part.index)")
function Device(s::AbstractString)
device = Device()
for part in split(s, "/")
isempty(part) && continue
push!(device.parts, DevicePart(part))
end
device
end
function Base.show(io::IO, device::Device)
print(io, "/")
join(io, device.parts, "/")
end
macro device_str(s)
Device(s)
end
"""
with_device(function, device)
Specifies the default device to use for ops created in `function`.
In contrast to the Python version, devices use 1-based indexing (eg, "gpu:1"
is the first GPU).
Intended to be used with `do` syntax:
```
with_device("gpu:2") do # Use the second GPU
x = constant(1.0)
end
```
"""
function with_device(f, device::Device)
g = get_def_graph()
push!(g.op_context.devices, device)
try
f()
finally
pop!(g.op_context.devices)
end
end
with_device(f, device) = with_device(f, Device(device))
struct OperationContext
control_ops::Vector{Vector{Any}} # Can't make Operation to break type cycle
names::Vector{String}
while_context::Vector{tensorflow.WhileContextDef}
devices::Vector{Device}
is_top_level::Ref{Bool}
end
@auto_hash_equals struct TensorShape
dims::Vector{Nullable{Int}}
rank_unknown::Bool
end
function TensorShape(dims::AbstractVector{<:Integer})
TensorShape([x<0 ? Nullable{Int}() : Nullable{Int}(x) for x in dims])
end
function TensorShape(dims)
TensorShape(dims, false)
end
function TensorShape(::Void)
TensorShape(Nullable{Int}[], true)
end
function TensorShape(::Vector{Union{}}) # NB: `Vector{Union{}} == typeof(collect(tuple())))`
TensorShape(Nullable{Int}[], false)
end
TensorShape(t::TensorShape) = copy(t)
function get_shape end
"""
A TensorFlow computation graph
"""
mutable struct Graph
ptr::Ptr{Void}
collections::Dict{Symbol, Any}
shapes::Dict{String, TensorShape}
name_idx::Dict{String, Int}
op_context::OperationContext
function Graph()
ptr = @tfcall(:TF_NewGraph, Ptr{Void}, ())
collections = Dict{Symbol, Any}()
collections[:Variables] = []
collections[:TrainableVariables] = []
collections[:Summaries] = []
collections[:QueueRunners] = []
collections[:while_context] = []
self = new(ptr, collections, Dict{String, TensorShape}(), Dict{String, Int}(), OperationContext(Vector{Operation}[], String[], tensorflow.WhileContextDef[], Device[], Ref(false)))
finalizer(self, self->begin
@tfcall(:TF_DeleteGraph, Void, (Ptr{Void},), self.ptr)
end)
self
end
end
function Base.show(io::IO, g::Graph)
print(io, "Graph($(g.ptr))")
end
function with_def_graph(ex)
ex = longdef(ex)
(@capture ex begin
function f_(args__; kwargs__)
body_
end
end) ||
(@capture ex begin
function f_(args__)
body_
end
end) ||
error("Improper use of with_def_graph")
(kwargs === nothing) && (kwargs = [])
new_args = args[2:end]
quote
function $f($(new_args...); $(kwargs...))
$f(TensorFlow.get_def_graph(), $(new_args...); $(kwargs...))
end
end
end
"""
@with_def_graph
Defaults the first parameter of the given function to `get_def_graph`.
"""
macro with_def_graph(ex)
new_func = with_def_graph(ex)
quote
@Base.__doc__($(esc(ex)))
$(esc(new_func))
end
end
@with_def_graph function add_to_collection(g::Graph, name, node)
if !haskey(g.collections, name)
g.collections[name] = []
end
push!(g.collections[name], node)
end
"""
get_collection(g::Graph, name)
Returns a collection attached to the graph `g` named `name`
"""
function get_collection end
@with_def_graph function get_collection(g::Graph, name)
if !haskey(g.collections, name)
return []
end
return g.collections[name]
end
const DEBUG_EXTEND_GRAPH = false
function Base.convert(::Type{tensorflow.NodeDef}, proto::Vector{UInt8})
b = IOBuffer()
write(b, proto)
seekstart(b)
node_def = tensorflow.NodeDef()
readproto(b, node_def)
node_def
end
@with_def_graph function extend_graph(graph::Graph, node_def_bytes)
new_graph = tensorflow.GraphDef()
set_field!(new_graph, :node, tensorflow.NodeDef[])
import_options = GraphImportOptions()
ph_names = Set{String}()
for node_def in convert.(tensorflow.NodeDef, node_def_bytes)
if isnull(get_node_by_name(graph, node_def.name))
# Hack to deal with imported nodes which have
# colocation dependencies on existing nodes
if has_field(node_def, :attr) && haskey(node_def.attr, "_class")
classes = node_def.attr["_class"].list.s
inds = Int[]
for (ind, val) in enumerate(classes)
m = match(r"^loc:@(.*)", String(val))
if m !== nothing
loc_name = m[1]
if !isnull(get_node_by_name(graph, loc_name))
push!(inds, ind)
end
end
end
deleteat!(classes, inds)
end
push!(new_graph.node, node_def)
for (i, input) in enumerate(node_def.input)
name, dest_port = parse_port_name(input)
is_control = name[1] == '^'
if is_control
name = name[2:end]
dest_port = 0
source_port = 0
else
source_port = 1
end
existing_node = get_node_by_name(graph, name)
if !isnull(existing_node)
local new_name
for name_id in Iterators.countfrom()
new_name = "$(name)__placeholder__$(name_id)_$dest_port"
isnull(get_node_by_name(graph, new_name)) && break
end
if is_control
input_name = string("^", new_name)
else
input_name = new_name
end
node_def.input[i] = input_name
import_options.input_mapping[(new_name, source_port)] = Tensor(get(existing_node), dest_port)
new_ph = tensorflow.NodeDef()
set_field!(new_ph, :name, new_name)
if is_control
set_field!(new_ph, :op, "NoOp")
else
set_field!(new_ph, :op, "Placeholder")
set_field!(new_ph, :attr, Dict{AbstractString, tensorflow.AttrValue}())
new_ph.attr["dtype"] = tensorflow.AttrValue()
source_type = tensorflow._DataType.DT_FLOAT
for key in ["T", "SrcT"]
if key ∈ keys(node_def.attr)
source_type = node_def.attr[key]._type
break
end
end
set_field!(new_ph.attr["dtype"], :_type, source_type)
end
if new_name ∉ ph_names
push!(new_graph.node, new_ph)
push!(ph_names, new_name)
end
end
end
end
end
import_graph_def(graph, new_graph, import_options)
end
@with_def_graph function extend_graph(graph::Graph, node_def::tensorflow.NodeDef)
extend_graph(graph, [node_def])
end
mutable struct SessionOptions
ptr::Ptr{Void}
function SessionOptions()
ptr = @tfcall(:TF_NewSessionOptions, Ptr{Void}, ())
self = new(ptr)
set_tf_finalizer(self)
self
end
end
function set_tf_finalizer(options::SessionOptions)
finalizer(options, options->begin
@tfcall(:TF_DeleteSessionOptions, Void, (Ptr{Void},), options.ptr)
end)
options
end
struct TFException <: Exception
status::Status
end
function check_status(status)
if get_code(status) ≠ TF_OK
throw(TFException(status))
end
nothing
end
const def_graph = Ref{Graph}()
const upgrade_check_needed = Ref(true)
function upgrade_check(v)
if upgrade_check_needed[]
if tf_version() < v
warn("You are using an old version version of the TensorFlow binary library. It is recommened that you upgrade with Pkg.build(\"TensorFlow\") or various
errors may be encountered.\n You have $(tf_version()) and the new version is $v.")
end
upgrade_check_needed[] = false
end
end
"""
get_def_graph()
Returns the default computation graph, an object of type `Graph`.
See also `as_default` for setting the default graph
"""
function get_def_graph()
upgrade_check(v"1.2.0") # This is here instead of in __init__ to avoid issues
# with precompilation.
has_def_graph() || (def_graph[] = Graph())
def_graph[]
end
has_def_graph() = isdefined(def_graph, :x)
"""
set_def_graph(g)
Sets the default computation graph to `g`.
See also `get_def_graph`, `as_default`
"""
function set_def_graph(g)
def_graph[] = g
end
"""
as_default(f, g::Graph)
For the duration of the function `f`
temporarily sets the default computational graph to `g`.
Suggested usage is via a do-block:
```julia
as_default(graph1) do
x = constant(5)
y = 2*x
end
```
In that example the nodes `x` and `y` were added to the Graph `graph1`.
see also See also `get_def_graph`
"""
function as_default(f, g::Graph)
old_def = get_def_graph()
set_def_graph(g)
try
f()
finally
set_def_graph(old_def)
end
end
"""
A TensorFlow session.
"""
mutable struct Session
ptr::Ptr{Void}
graph::Graph
function Session(graph, config=nothing)
set_def_graph(graph)
options = SessionOptions()
if config !== nothing
b = IOBuffer()
writeproto(b, config)
seekstart(b)
proto = read(b)
config_status = Status()
@tfcall(:TF_SetConfig, Void, (Ptr{Void}, Ptr{Void}, Csize_t, Ptr{Void}), options.ptr, proto, sizeof(proto), config_status.ptr)
check_status(config_status)
end
status = Status()
ptr = @tfcall(:TF_NewSession, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Ptr{Void}), graph.ptr, options.ptr, status.ptr)
this = new(ptr, graph)
check_status(status)
finalizer(this, self->begin
close(self)
end)
return this
end
function Session(;config=nothing, allow_growth=false, graph=get_def_graph())
if config === nothing
config = tensorflow.ConfigProto()
gpu_config = tensorflow.GPUOptions()
set_field!(gpu_config, :allow_growth, allow_growth)
set_field!(config, :gpu_options, gpu_config)
end
Session(graph, config)
end
end
"""
close(sess::Session)
Closes the TensorFlow session, freeing the associated computational resources.
"""
function Base.close(sess::Session)
if sess.ptr != C_NULL
status = Status()
@tfcall(:TF_DeleteSession, Void, (Ptr{Void}, Ptr{Void}), sess.ptr, status.ptr)
check_status(status)
sess.ptr = C_NULL
end
return nothing
end
mutable struct Buffer
ptr::Ptr{Void}
function Buffer(s::Vector{UInt8})
self = new()
self.ptr = @tfcall(:TF_NewBufferFromString, Ptr{Void}, (Ptr{Void}, Csize_t), pointer(s), sizeof(s))
set_tf_finalizer(self)
return self
end
function Buffer()
self = new()
self.ptr = @tfcall(:TF_NewBuffer, Ptr{Void}, ())
set_tf_finalizer(self)
return self
end
Buffer(ptr) = new(ptr)
end
function set_tf_finalizer(buffer::Buffer)
finalizer(buffer, buffer->begin
@tfcall(:TF_DeleteBuffer, Void, (Ptr{Void},), buffer.ptr)
end)
end
struct BufferStruct
data::Ptr{UInt8}
len::Csize_t
deallocator::Ptr{Void}
end
function getindex(b::Buffer)
@tfcall(:TF_GetBuffer, BufferStruct, (Ptr{Void},), b.ptr)
end
function Base.convert(::Type{Array}, buf::Buffer)
struct_ = buf[]
array = unsafe_wrap(Array, struct_.data, (struct_.len,))
copy(array)
end
function deallocator(data, len, arg)
end
const c_deallocator = Ref{Ptr}()
"""
convert_major_order(array)
Convert from row-major to column-major or vice-versa
"""
function convert_major_order(array)
permutedims(array, length(size(array)):-1:1)
end
struct EmptyTensorError <: Exception
end
function Base.show(io::IO, err::EmptyTensorError)
print(io, "Creating tensors from empty arrays is not allowed")
end
mutable struct RawTensor
ptr::Ptr{Void}
data::Array # To avoid underlying data being GCed
RawTensor() = new()
function RawTensor(data::Array)
isempty(data) && throw(EmptyTensorError())
dims = [size(data)...]
dt = jl_to_df_type(eltype(data))
data = convert_major_order(data)
ptr = @tfcall(:TF_NewTensor, Ptr{Void}, (Cint, Ptr{Cint}, Cint, Ptr{Void}, Csize_t, Ptr{Void}, Ptr{Void}),
Int(dt),
pointer(dims),
length(dims),
pointer(data),
sizeof(data),
c_deallocator[],
C_NULL)
self = new(ptr, data)
set_tf_finalizer(self)
return self
end
function RawTensor(data::Number)
dims = Cint[]
dt = jl_to_df_type(eltype(data))
data_boxed = [data]
ptr = @tfcall(:TF_NewTensor, Ptr{Void}, (Cint, Ptr{Void}, Cint, Ptr{Void}, Csize_t, Ptr{Void}, Ptr{Void}),
Int(dt),
pointer(dims),
length(dims),
pointer(data_boxed),
sizeof(data_boxed),
c_deallocator[],
C_NULL)
self = new(ptr, data_boxed)
set_tf_finalizer(self)
return self
end
function RawTensor(ptr::Ptr)
self = new(ptr)
set_tf_finalizer(self)
return self
end
end
function set_tf_finalizer(tensor::RawTensor)
finalizer(tensor, tensor->begin
@tfcall(:TF_DeleteTensor, Void, (Ptr{Void},), tensor.ptr)
end)
end
RawTensor(data::AbstractArray) = RawTensor(collect(data))
RawTensor(t::RawTensor) = t
function varint_encode(b::IO, n::Integer)
while n ≥ 2^7
write(b, UInt8(0b10000000 | (n & 0b1111111)))
n >>= 7
end
write(b, UInt8(n))
end
function varint_decode(b::IO)
n = 0
idx = 0
while true
x = read(b, UInt8)
if (x & 0b10000000) > 0
x = x & 0b01111111
n = n | (Int64(x) << 7idx)
else
n = n | (Int64(x) << 7idx)
break
end
idx += 1
end
return n
end
function tf_string_encode(src::Vector{UInt8})
dest_length = @tfcall(:TF_StringEncodedSize, Csize_t, (Csize_t,), length(src)) |> Int
dest = Vector{UInt8}(dest_length)
status = Status()
@tfcall(:TF_StringEncode, Csize_t,
(Ptr{Void}, Csize_t, Ptr{Void}, Csize_t, Ptr{Void}),
src, length(src), dest, length(dest), status.ptr)
check_status(status)
dest
end
tf_string_encode(src) = tf_string_encode(Vector{UInt8}(src))
function tf_string_decode(src::Vector{UInt8})
status = Status()
dst = Ref{Ptr{UInt8}}()
dst_len = Ref{Csize_t}()
@tfcall(:TF_StringDecode, Csize_t,
(Ptr{Void}, Csize_t, Ref{Ptr{UInt8}}, Ref{Csize_t}, Ptr{Void}),
src, length(src), dst, dst_len, status.ptr)
check_status(status)
copy(unsafe_wrap(Array, dst[], Int(dst_len[])))
end
tf_string_decode(src) = tf_string_decode(Vector{UInt8}(src))
tf_string_decode(T, src) = T(tf_string_decode(src))
# cf this section of c_api.h in upstream tensorflow/c_api.h
#=
// --------------------------------------------------------------------------
// TF_Tensor holds a multi-dimensional array of elements of a single data type.
// For all types other than TF_STRING, the data buffer stores elements
// in row major order. E.g. if data is treated as a vector of TF_DataType:
//
// element 0: index (0, ..., 0)
// element 1: index (0, ..., 1)
// ...
//
// The format for TF_STRING tensors is:
// start_offset: array[uint64]
// data: byte[...]
//
// The string length (as a varint), followed by the contents of the string
// is encoded at data[start_offset[i]]]. TF_StringEncode and TF_StringDecode
// facilitate this encoding.
=#
function RawTensor(data::Array{String}, is_scalar=false)
# TODO make work for multidimensional arrays
# Currently only works for vectors and scalars
t = RawTensor()
t.data = data
if is_scalar
dims = Cint[]
else
dims = [size(data)...]
end
data = convert_major_order(data)
data = map(tf_string_encode ,data)
encoded_buf = IOBuffer()
pos = 0
for str in data
write(encoded_buf, UInt64(pos))
pos += length(str)
end
for str in data
write(encoded_buf, str)
end
data_encoded = take!(encoded_buf)
dt = jl_to_df_type(String)
ptr = @tfcall(:TF_NewTensor, Ptr{Void}, (Cint, Ptr{Int64}, Cint, Ptr{Void}, Csize_t, Ptr{Void}, Ptr{Void}),
Int(dt),
dims,
length(dims),
data_encoded,
length(data_encoded),
c_deallocator[],
C_NULL)
if ptr == C_NULL
error("Error creating tensor")
end
t.ptr = ptr
return t
end
function RawTensor(data::String)
RawTensor([data], true)
end
function RawTensor(data::Array{Vector{UInt8}})
RawTensor(String.(data))
end
function Base.ndims(t::RawTensor)
@tfcall(:TF_NumDims, Cint, (Ptr{Void},), t.ptr) |> Int
end
function Base.size(t::RawTensor, dim::Integer)
n = ndims(t)
dim -= 1
@assert dim < n
@tfcall(:TF_Dim, Clonglong, (Ptr{Void}, Cint), t.ptr, dim)
end
function Base.size(t::RawTensor)
d = (size(t, x) for x in 1:ndims(t))
(d...)
end
function Base.sizeof(t::RawTensor)
@tfcall(:TF_TensorByteSize, Csize_t, (Ptr{Void},), t.ptr) |> Int
end
function set_device(node_desc, device::String)
@tfcall(:TF_SetDevice, Void,
(Ptr{Void}, Cstring),
node_desc.ptr, device)
end
set_device(node_desc, device::Device) = set_device(node_desc, device_index_from_zero(device))
mutable struct NodeDescription
ptr::Ptr{Void}
graph::Graph
function NodeDescription(graph, op_type, full_name)
desc = @tfcall(:TF_NewOperation, Ptr{Void}, (Ptr{Void}, Cstring, Cstring), graph.ptr, op_type, full_name)
self = new(desc, graph)
for control_op_set in graph.op_context.control_ops
for control_op in control_op_set
add_control_input(self, control_op)
end
end
isempty(graph.op_context.devices) || set_device(self, graph.op_context.devices[end])
self
end
end
NodeDescription(op_type, node_name) = NodeDescription(get_def_graph(), op_type, node_name)
function get_cur_node_name()
join(get_def_graph().op_context.names, "/")
end
function NodeDescription(op_type)
name = get_cur_node_name()
NodeDescription(op_type, name)
end
get_graph(desc::NodeDescription) = Nullable(desc.graph)
abstract type AbstractOperation end
"""
An operation in the computation graph.
"""
mutable struct Operation <: AbstractOperation
ptr::Ptr{Void}
graph::Nullable{Graph}
op_name::String
name::String
Operation() = new()
end
==(op1::Operation, op2::Operation) = op1.ptr == op2.ptr
Base.hash(op::Operation, h::UInt) = hash(Operation, hash(op.ptr, h))
struct Port
node_ptr::Ptr{Void}
index::Int
end
function get_num_inputs(op::Operation)
@tfcall(:TF_OperationNumInputs, Cint, (Ptr{Void},), op.ptr) |> Int
end
struct InputOutOfRangeError <: Exception
op::Operation
index::Int
end
function Base.show(io::IO, err::InputOutOfRangeError)
fillin(err.op)
num_inputs = get_num_inputs(err.op)
print(io, "Index $(err.index) is out of range. Operation '$(err.op.op_name)' only has $num_inputs inputs.")
end
function get_input(op::Operation, idx)
num_inputs = get_num_inputs(op)
if idx < 1 || idx > num_inputs
throw(InputOutOfRangeError(op, idx))
end
port = Port(op.ptr, idx-1)
in_port = @tfcall(:TF_OperationInput, Port, (Port,), port)
out_tensor = Tensor(in_port)
out_op = get_op(out_tensor)
out_op.graph = op.graph
fillin(out_op)
out_tensor
end
function get_num_control_inputs(op::Operation)
@tfcall(:TF_OperationNumControlInputs, Cint, (Ptr{Void},), op.ptr) |> Int
end
function get_control_inputs(op::Operation)
N = get_num_control_inputs(op)
ptrs = Vector{Ptr{Void}}(N)
N_out = @tfcall(:TF_OperationGetControlInputs, Cint, (Ptr{Void}, Ptr{Ptr{Void}}, Cint),
op.ptr, ptrs, N)
out = Vector{Operation}()
for n in 1:N_out
op_out = Operation(ptrs[n])
fillin(op_out)
op_out.graph = op.graph
push!(out, op_out)
end
out
end
function get_input_list_length(op::Operation, arg_name)
status = Status()
out = @tfcall(:TF_OperationInputListLength, Cint, (Ptr{Void}, Cstring, Ptr{Void}), op.ptr, arg_name, status.ptr)
check_status(status)
Int(out)
end
struct AttrMetadata
is_list::Bool
list_size::Int64
_type::Int32
total_size::Int64
end
function get_attr_metadata(op::Operation, attr)
status = Status()
out = @tfcall(:TF_OperationGetAttrMetadata, AttrMetadata, (Ptr{Void}, Cstring, Ptr{Void}), op.ptr, attr, status.ptr)
check_status(status)
out
end
function get_attr(op::Operation, attr, ::Type{Int})
out = Ref{Int}()
status = Status()
@tfcall(:TF_OperationGetAttrInt, Void, (Ptr{Void}, Cstring, Ref{Int}, Ptr{Void}), op.ptr, attr, out, status.ptr)
check_status(status)
out[]
end
function get_attr(op::Operation, attr, ::Type{Array})
out = Ref{Ptr{Void}}()
status = Status()
@tfcall(:TF_OperationGetAttrTensor, Void, (Ptr{Void}, Cstring, Ptr{Ptr{Void}}, Ptr{Void}), op.ptr, attr, out, status.ptr)
check_status(status)
Array(RawTensor(out[]))
end
function get_attr(op::Operation, attr, ::Type{Bool})
out = Ref{Bool}()
status = Status()
@tfcall(:TF_OperationGetAttrBool, Void, (Ptr{Void}, Cstring, Ref{Bool}, Ptr{Void}), op.ptr, attr, out, status.ptr)
check_status(status)
out[]
end
function get_attr(op::Operation, attr, ::Type{Vector{Int}})
meta = get_attr_metadata(op, attr)
out = Vector{Int}(meta.list_size)
status = Status()
@tfcall(:TF_OperationGetAttrIntList, Void, (Ptr{Void}, Cstring, Ptr{Int}, Cint, Ptr{Void}), op.ptr, attr, out, length(out), status.ptr)
check_status(status)
out
end
function get_attr(op::Operation, attr, ::Type{String})
meta = get_attr_metadata(op, attr)
out = Vector{UInt8}(meta.total_size)
status = Status()
@tfcall(:TF_OperationGetAttrString, Void, (Ptr{Void}, Cstring, Ptr{UInt8}, Cint, Ptr{Void}), op.ptr, attr, out, length(out), status.ptr)
check_status(status)
String(out)
end
function fillin(op::Operation)
op.name = @tfcall(:TF_OperationName, Cstring, (Ptr{Void},), op.ptr) |> unsafe_string
op.op_name = @tfcall(:TF_OperationOpType, Cstring, (Ptr{Void},), op.ptr) |> unsafe_string
end
function with_op_name(f, name, def_name="Node")
if name === nothing
name = get_name(def_name)
end
g = get_def_graph()
push!(g.op_context.names, name)
try
f()
finally
pop!(g.op_context.names)
end
end
"""
with_op_control(f, control_ops)
Any ops declared inside `f` will not execute until after all op listed in `control_ops`.
This enforces order of execution.
It is useful if the op in `f` may depend on the execution of one or more of the `control_ops` first.
see also [Python Docs](https://www.tensorflow.org/versions/r0.12/api_docs/python/framework/core_graph_data_structures#Graph.control_dependencies)
"""
function with_op_control(f, control_ops)
g = get_def_graph()
push!(g.op_context.control_ops, control_ops)
try
f()
finally
pop!(g.op_context.control_ops)
end
end
function with_top_level(f)
g = get_def_graph()
is_top_level = g.op_context.is_top_level
old_level = is_top_level[]
is_top_level[] = true
try
with_no_op_control() do
f()
end
finally
is_top_level[] = old_level
end