/
nn_dsl.nim
407 lines (361 loc) · 11.2 KB
/
nn_dsl.nim
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
# Copyright (c) 2018 Mamy André-Ratsimbazafy and the Arraymancer contributors
# Distributed under the Apache v2 License (license terms are at http://www.apache.org/licenses/LICENSE-2.0).
# This file may not be copied, modified, or distributed except according to those terms.
import
macros
type
SectionInfo = object
idents: seq[NimNode]
body: NimNode
proc splitSections(config: NimNode): tuple[layers, forward: SectionInfo] =
template unknown =
error:
lineInfo(section) &
": unknown neural network configuration section \"" &
$section[0] & "\""
for section in config:
if section.kind == nnkCall or section.kind == nnkCommand:
# We have to deal with forward/init with multiple inputs like "forward x, y, z:"
# so we will handle these now.
proc getSectionInfo(nodes: seq[NimNode]): SectionInfo =
for i, node in nodes.pairs:
if node.kind == nnkIdent:
result.idents.add node
elif node.kind == nnkStmtList and i == nodes.len - 1:
result.body = node
else:
unknown()
if eqIdent(section[0], "layers"):
result.layers = section[1..^1].getSectionInfo()
elif eqIdent(section[0], "forward"):
result.forward = section[1..^1].getSectionInfo()
else:
unknown()
else:
unknown()
type
LayerInfo = object
name: NimNode
typeName: NimNode
arguments: seq[NimNode]
proc createLayerInfo(sectionInfo: SectionInfo): seq[LayerInfo] =
# sectionInfo.idents contains constains a list of identifiers that will be used
# as function parameters for the init funxtion
# sectionInfo.body contains the description of layers, e.g.:
# cv: Conv2D(mp1.outShape, 50, (5, 5))
# mp: MaxPool2D(cv2.outShape, (2,2), (0,0), (2,2))
# fl: Flatten(mp2.outShape)
# hidden: Linear(fl.outShape[0], 500)
if sectionInfo.body.kind != nnkStmtList:
error("Layer body must be a statement list: \"" & $toStrLit(sectionInfo.body) & "\"", sectionInfo.body)
for layer in sectionInfo.body:
if layer.kind != nnkCall or
layer.len != 2 or
layer[0].kind != nnkIdent or
layer[1].kind != nnkStmtList or
layer[1].len != 1 or
layer[1][0].kind != nnkCall or
layer[1][0].len < 1 or
layer[1][0][0].kind != nnkIdent:
error("Unknown configuration of layer section: \"" & $toStrLit(layer) & "\"", layer)
result.add LayerInfo(
name: layer[0],
typeName: layer[1][0][0]
)
if layer[1][0].len >= 2:
result[^1].arguments = layer[1][0][1..^1]
proc createModelType(layerInfos: seq[LayerInfo], modelName: NimNode): NimNode =
# creates the type defintion of the model, e.g.:
# type
# SomeConvNet[T] = object
# cv: Conv2D[T]
# mp: Maxpool2D[T]
# fl: Flatten[T]
let underlyingTypeSymbol = genSym(nskType, "T")
var recList = newNimNode(nnkRecList)
for layerInfo in layerInfos:
doAssert layerInfo.name.kind == nnkIdent
doAssert layerInfo.typeName.kind == nnkIdent
recList.add newIdentDefs(
layerInfo.name,
newNimNode(nnkBracketExpr).add(
layerInfo.typeName,
underlyingTypeSymbol
)
)
doAssert modelName.kind == nnkIdent
result = newNimNode(nnkTypeSection).add(
newNimNode(nnkTypeDef).add(
modelName,
newNimNode(nnkGenericParams).add(
newIdentDefs(
underlyingTypeSymbol,
newEmptyNode()
)
),
newNimNode(nnkObjectTy).add(
newEmptyNode(),
newEmptyNode(),
recList
)
)
)
proc createInitProc(layerInfos: seq[LayerInfo], sectionInfo: SectionInfo, modelName: NimNode): NimNode =
# creates init function of the model, e.g.:
# proc init[T](ctx: Context[AnyTensor[T]], modelType: typedesc[SomeConvNet[T]], h: auto; w: auto): SomeConvNet[T] =
# template cv(): auto =
# result.cv
# template mp(): auto =
# result.mp
# template fl(): auto =
# result.fl
# cv = init(ctx, Conv2D[T], @[1, h, w], 20, (5, 5))
# mp = init(ctx, Maxpool2D[T], cv1.outShape, (2, 2), (0, 0), (2, 2))
# fl = init(ctx, Flatten[T], mp.outShape)
doAssert modelName.kind == nnkIdent
var body = newNimNode(nnkStmtList)
for layerInfo in layerInfos:
body.add(
newNimNode(nnkTemplateDef).add(
layerInfo.name,
newEmptyNode(),
newEmptyNode(),
newNimNode(nnkFormalParams).add ident"auto",
newEmptyNode(),
newEmptyNode(),
newStmtList(
newDotExpr(
ident"result",
layerInfo.name
)
)
)
)
let
ctxSymbol = genSym(nskParam, "ctx")
# TODO fix this (part of workaround for https://github.com/nim-lang/Nim/issues/19542):
underlyingTypeSymbol = ident($toStrLit(genSym(nskGenericParam, "T")))
for layerInfo in layerInfos:
body.add(
newAssignment(
layerInfo.name,
newCall(
ident"init",
ctxSymbol,
newNimNode(nnkBracketExpr).add(
layerInfo.typeName,
underlyingTypeSymbol
)
).add(layerInfo.arguments)
)
)
var params = @[
newNimNode(nnkBracketExpr).add(
modelName,
underlyingTypeSymbol
),
newIdentDefs(
ctxSymbol,
newNimNode(nnkBracketExpr).add(
ident"Context",
newNimNode(nnkBracketExpr).add(
ident"AnyTensor",
copy underlyingTypeSymbol # needs to be copied for workaround for https://github.com/nim-lang/Nim/issues/19542
)
)
),
newIdentDefs(
genSym(nskParam, "modelType"),
newNimNode(nnkBracketExpr).add(
ident"typedesc",
newNimNode(nnkBracketExpr).add(
modelName,
underlyingTypeSymbol
)
)
)
]
for inputIdent in sectionInfo.idents:
params.add(
newIdentDefs(
inputIdent,
ident"auto"
)
)
result = newProc(
name = ident"init",
params = params,
body = body
)
# GenericParams
result[2] = newNimNode(nnkGenericParams).add(
newIdentDefs(
underlyingTypeSymbol,
newEmptyNode()
)
)
proc createForwardProc(layerInfos: seq[LayerInfo], forward: SectionInfo, modelName: NimNode): NimNode =
# create the forward function, e.g.:
# proc forward[T](self: SomeConvNet[T]; x: auto): auto =
# template cv1(x: varargs[untyped]): auto =
# forward(self.cv1, x)
#
# template mp1(x: varargs[untyped]): auto =
# forward(self.mp1, x)
#
# template fl(x: varargs[untyped]): auto =
# forward(self.fl, x)
#
# x.cv1.relu.mp1.cv2.relu.mp2.fl
let
selfSymbol = genSym(nskParam, "self")
underlyingTypeSymbol = genSym(nskGenericParam, "T")
var body = newNimNode(nnkStmtList)
for layerInfo in layerInfos:
let xSymbol = genSym(nskParam, "input")
body.add(
newNimNode(nnkTemplateDef).add(
layerInfo.name,
newEmptyNode(),
newEmptyNode(),
newNimNode(nnkFormalParams).add(
ident"auto",
newIdentDefs(
xSymbol,
newNimNode(nnkBracketExpr).add(
ident"varargs",
ident"untyped"
)
)
),
newEmptyNode(),
newEmptyNode(),
newStmtList(
newCall(
ident"forward",
newDotExpr(
selfSymbol,
layerInfo.name,
),
xSymbol
)
)
)
)
body.add forward.body
var params = @[
ident"auto",
newIdentDefs(
selfSymbol,
newNimNode(nnkBracketExpr).add(
modelName,
underlyingTypeSymbol
)
)
]
for inputIdent in forward.idents:
params.add(
newIdentDefs(
inputIdent,
ident"auto"
)
)
result = newProc(
name = ident"forward",
params = params,
body = body
)
# GenericParams
result[2] = newNimNode(nnkGenericParams).add(
newIdentDefs(
underlyingTypeSymbol,
newEmptyNode()
)
)
macro network*(modelName: untyped, config: untyped): untyped =
## Declare a neural network.
##
## Example usage:
##
## .. code:: nim
## network DemoNet:
## layers h, w:
## cv1: Conv2D(@[1, h, w], 20, (5, 5))
## mp1: Maxpool2D(cv1.outShape, (2,2), (0,0), (2,2))
## cv2: Conv2D(mp1.outShape, 50, (5, 5))
## mp2: MaxPool2D(cv2.outShape, (2,2), (0,0), (2,2))
## fl: Flatten(mp2.outShape)
## hidden: Linear(fl.outShape[0], 500)
## classifier: Linear(500, 10)
## forward x:
## x.cv1.relu.mp1.cv2.relu.mp2.fl.hidden.relu.classifier
##
## let
## ctx = newContext Tensor[float32]
## model = ctx.init(DemoNet, 28, 28)
##
##
## Custom layers can be created by providing a type, an init-function, and a forward-function.
## The type could look like this:
##
## .. code:: nim
## type
## MyLayer*[T] = object
## someWeights*: Variable[Tensor[T]]
## importantInfo*: seq[int]
##
## It is important that the type has exactly one generic parameter which corresponds to the
## underlying type (e.g., ``float32`` or ``int8``).
## The init-function is required to adhere to the following structure:
##
## .. code:: nim
## proc init*[T](
## ctx: Context[Tensor[T]], # could also be Context[AnyTensor[T]] for example
## layerType: typedesc[MyLayer[T]],
## myInitParam: string
## # ... here you can add all the necessary init parameters, like shapes and number of output features
## ): MyLayer[T] =
## discard # your init stuff
##
## The only requirement for the forward function is that the first parameter must be of your layer type like this:
##
## .. code:: nim
## proc forward*[T](self: MyLayer[T], myInput: SpecialInputType, doNothing: bool): Variable[Tensor[T]] =
## if not doNothing:
## result = myInput.yourComputations(self.importantInfo, self.someWeights)
##
##
## Often it is also useful to provide ``proc outShape(m: MyLayer): seq[int]`` and possibly
## ``proc inShape(m: MyLayer): seq[int]`` functions.
##
## Your custom layer can then be used for example like this:
##
## .. code:: nim
## network DemoNet2:
## layers:
## myLayer: MyLayer(myInitParam = "hello!")
## fl: Flatten(myLayer.outShape)
## hidden: Linear(fl.outShape[0], 500)
## classifier: Linear(500, 10)
## forward x:
## x.myLayer(doNothing = false).fl.hidden.relu.classifier
# TODO better doc
if modelName.kind != nnkIdent:
error("Name of model must be an identifier: \"" & $toStrLit(modelName) & "\"", modelName)
# 0. separate the configuration into layers and forward part
let sections = config.splitSections()
# 1. create layer info
let layerInfos = sections.layers.createLayerInfo()
# 2. create model type
let modelType = createModelType(layerInfos, modelName)
# 3. create init proc
let initProc = createInitProc(layerInfos, sections.layers, modelName)
# 4. create forward proc
let forwardProc = createForwardProc(layerInfos, sections.forward, modelName)
# 5. combine everything into a statement
result = newStmtList(
modelType,
initProc,
forwardProc
)
# echo toStrLit(result)