Scope-driven mechanism for building nets, loops and conditional blocks. Args: name: NetBuilder's name initial_scope: list of blobs that are available for reading/writing Example: from caffe2.python.net_builder import NetBuilder, ops with NetBuilder() as nb:
| 11 | |
| 12 | |
| 13 | class NetBuilder(context.Managed): |
| 14 | """ |
| 15 | Scope-driven mechanism for building nets, loops and conditional blocks. |
| 16 | Args: |
| 17 | name: NetBuilder's name |
| 18 | initial_scope: list of blobs that are available for reading/writing |
| 19 | Example: |
| 20 | from caffe2.python.net_builder import NetBuilder, ops |
| 21 | with NetBuilder() as nb: |
| 22 | c = ops.Const(5) |
| 23 | d = ops.Const(0) |
| 24 | with ops.loop(): |
| 25 | ops.stop_if(ops.LE([c, ops.Const(0)])) |
| 26 | ops.Add([c, ops.Const(-1)], [c]) |
| 27 | with ops.If(ops.GE([c, ops.Const(3)])): |
| 28 | ops.Add([d, ops.Const(10)], [d]) |
| 29 | ops.Print(c, []) |
| 30 | ops.Print(d, []) |
| 31 | step = core.to_execution_step(nb) |
| 32 | """ |
| 33 | def __init__(self, name=None, initial_scope=None, _stop_blob_required=False, |
| 34 | _stop_blob=None, _fullname=None, _use_control_ops=False): |
| 35 | parent = NetBuilder.current(required=False) |
| 36 | assert not _fullname or not name, 'Cannot set both _fullname and name' |
| 37 | assert not _use_control_ops or \ |
| 38 | (not _stop_blob_required and not _stop_blob), \ |
| 39 | 'Stop blobs are not used with control operators' |
| 40 | self.name = _fullname or '/'.join( |
| 41 | n for n in (parent.name if parent else None, name) if n |
| 42 | ) |
| 43 | self._frozen = False |
| 44 | self._current_net = None |
| 45 | self._children = [] |
| 46 | if parent: |
| 47 | # make sure parent has an up to date lexical scope computed |
| 48 | parent._update_lexical_scope() |
| 49 | self._init_lexical_scope = set(parent._lexical_scope) if parent else set() |
| 50 | if initial_scope: |
| 51 | self._init_lexical_scope |= set([str(b) for b in initial_scope]) |
| 52 | self._lexical_scope = set(self._init_lexical_scope) |
| 53 | self._stop_blob = _stop_blob |
| 54 | self._stop_blob_required = _stop_blob_required |
| 55 | self._use_control_ops = _use_control_ops |
| 56 | |
| 57 | def stop_blob(self): |
| 58 | """ |
| 59 | Returns the BlobReference to the stop_blob of this NetBuilder. |
| 60 | If one is not yet available, creates one. |
| 61 | This function assumes that the stop_blob() will be used immediatelly |
| 62 | in the current net, so it doesn't initialize it if the current net is |
| 63 | the first of the builder. |
| 64 | """ |
| 65 | assert not self._use_control_ops, \ |
| 66 | 'Stop blobs are not used with control operators' |
| 67 | if self._stop_blob is None: |
| 68 | net = self.current_net() |
| 69 | self._stop_blob = core.BlobReference( |
| 70 | net.NextName('stop_blob'), net=net) |
no outgoing calls
searching dependent graphs…