desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
':param factory: Stream-based factory to be wrapped. :type factory: A subclass of ``twisted.internet.protocol.Factory`` :param url: WebSocket URL of the server this client factory will connect to. :type url: unicode'
def __init__(self, factory, url, reactor=None, enableCompression=True, autoFragmentSize=0, subprotocol=None):
self._factory = factory self._subprotocols = [u'binary', u'base64'] if subprotocol: self._subprotocols.append(subprotocol) WebSocketClientFactory.__init__(self, url=url, reactor=reactor, protocols=self._subprotocols) self.setProtocolOptions(autoFragmentSize=autoFragmentSize) self.setProt...
':param factory: A callable that produces instances that implement :class:`autobahn.wamp.interfaces.ITransportHandler` :type factory: callable :param serializers: A list of WAMP serializers to use (or ``None`` for all available serializers). :type serializers: list of objects implementing :class:`autobahn.wamp.interfac...
def __init__(self, factory, *args, **kwargs):
serializers = kwargs.pop('serializers', None) websocket.WampWebSocketServerFactory.__init__(self, factory, serializers) kwargs['protocols'] = self._protocols WebSocketServerFactory.__init__(self, *args, **kwargs)
':param factory: A callable that produces instances that implement :class:`autobahn.wamp.interfaces.ITransportHandler` :type factory: callable :param serializer: The WAMP serializer to use (or ``None`` for "best" serializer, chosen as the first serializer available from this list: CBOR, MessagePack, UBJSON, JSON). :typ...
def __init__(self, factory, *args, **kwargs):
serializers = kwargs.pop('serializers', None) websocket.WampWebSocketClientFactory.__init__(self, factory, serializers) kwargs['protocols'] = self._protocols WebSocketClientFactory.__init__(self, *args, **kwargs)
':param url: The WebSocket URL of the WAMP router to connect to (e.g. `ws://somehost.com:8090/somepath`) :type url: str :param realm: The WAMP realm to join the application session to. :type realm: str :param extra: Optional extra configuration to forward to the application component. :type extra: dict :param serialize...
def __init__(self, url, realm=None, extra=None, serializers=None, ssl=None, proxy=None, headers=None):
assert (type(url) == six.text_type) assert ((realm is None) or (type(realm) == six.text_type)) assert ((extra is None) or (type(extra) == dict)) assert ((headers is None) or (type(headers) == dict)) assert ((proxy is None) or (type(proxy) == dict)) self.url = url self.realm = realm self....
'Stop reconnecting, if auto-reconnecting was enabled.'
@public def stop(self):
self.log.debug('{klass}.stop()', klass=self.__class__.__name__) if self._client_service: return self._client_service.stopService() else: return succeed(None)
'Run the application component. :param make: A factory that produces instances of :class:`autobahn.twisted.wamp.ApplicationSession` when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`. :type make: callable :param start_reactor: When ``True`` (the default) this method starts the Twisted reactor ...
@public def run(self, make, start_reactor=True, auto_reconnect=False, log_level='info'):
if start_reactor: from twisted.internet import reactor txaio.use_twisted() txaio.config.loop = reactor txaio.start_logging(level=log_level) if callable(make): def create(): cfg = ComponentConfig(self.realm, self.extra) try: session ...
':param config: The component configuration. :type config: Instance of :class:`autobahn.wamp.types.ComponentConfig` :param app: The application this session is for. :type app: Instance of :class:`autobahn.twisted.wamp.Application`.'
def __init__(self, config, app):
ApplicationSession.__init__(self, config) self.app = app
'Implements :func:`autobahn.wamp.interfaces.ISession.onConnect`'
@inlineCallbacks def onConnect(self):
(yield self.app._fire_signal('onconnect')) self.join(self.config.realm)
'Implements :func:`autobahn.wamp.interfaces.ISession.onJoin`'
@inlineCallbacks def onJoin(self, details):
for (uri, proc) in self.app._procs: (yield self.register(proc, uri)) for (uri, handler) in self.app._handlers: (yield self.subscribe(handler, uri)) (yield self.app._fire_signal('onjoined'))
'Implements :func:`autobahn.wamp.interfaces.ISession.onLeave`'
@inlineCallbacks def onLeave(self, details):
(yield self.app._fire_signal('onleave')) self.disconnect()
'Implements :func:`autobahn.wamp.interfaces.ISession.onDisconnect`'
@inlineCallbacks def onDisconnect(self):
(yield self.app._fire_signal('ondisconnect'))
':param prefix: The application URI prefix to use for procedures and topics, e.g. ``"com.example.myapp"``. :type prefix: unicode'
def __init__(self, prefix=None):
self._prefix = prefix self._procs = [] self._handlers = [] self._signals = {} self.session = None
'Factory creating a WAMP application session for the application. :param config: Component configuration. :type config: Instance of :class:`autobahn.wamp.types.ComponentConfig` :returns: obj -- An object that derives of :class:`autobahn.twisted.wamp.ApplicationSession`'
def __call__(self, config):
assert (self.session is None) self.session = _ApplicationSession(config, self) return self.session
'Run the application. :param url: The URL of the WAMP router to connect to. :type url: unicode :param realm: The realm on the WAMP router to join. :type realm: unicode'
def run(self, url=u'ws://localhost:8080/ws', realm=u'realm1', start_reactor=True):
runner = ApplicationRunner(url, realm) return runner.run(self.__call__, start_reactor)
'Decorator exposing a function as a remote callable procedure. The first argument of the decorator should be the URI of the procedure to register under. :Example: .. code-block:: python @app.register(\'com.myapp.add2\') def add2(a, b): return a + b Above function can then be called remotely over WAMP using the URI `com...
def register(self, uri=None):
def decorator(func): if uri: _uri = uri else: assert (self._prefix is not None) _uri = '{0}.{1}'.format(self._prefix, func.__name__) if inspect.isgeneratorfunction(func): func = inlineCallbacks(func) self._procs.append((_uri, func)) ...
'Decorator attaching a function as an event handler. The first argument of the decorator should be the URI of the topic to subscribe to. If no URI is given, the URI is constructed from the application URI prefix and the Python function name. If the function yield, it will be assumed that it\'s an asynchronous process a...
def subscribe(self, uri=None):
def decorator(func): if uri: _uri = uri else: assert (self._prefix is not None) _uri = '{0}.{1}'.format(self._prefix, func.__name__) if inspect.isgeneratorfunction(func): func = inlineCallbacks(func) self._handlers.append((_uri, func)) ...
'Decorator attaching a function as handler for application signals. Signals are local events triggered internally and exposed to the developer to be able to react to the application lifecycle. If the function yield, it will be assumed that it\'s an asynchronous coroutine and inlineCallbacks will be applied to it. Curre...
def signal(self, name):
def decorator(func): if inspect.isgeneratorfunction(func): func = inlineCallbacks(func) self._signals.setdefault(name, []).append(func) return func return decorator
'Utility method to call all signal handlers for a given signal. :param name: The signal name. :type name: str'
@inlineCallbacks def _fire_signal(self, name, *args, **kwargs):
for handler in self._signals.get(name, []): try: (yield handler(*args, **kwargs)) except Exception as e: self.log.info('Warning: exception in signal handler swallowed: {err}', err=e)
'Patch ``name`` so that Twisted will grab a fake reactor instead of a real one.'
def patch_reactor(self, name, new_reactor):
if hasattr(twisted.internet, name): self.patch(twisted.internet, name, new_reactor) else: def _cleanup(): delattr(twisted.internet, name) setattr(twisted.internet, name, new_reactor)
'Patch ``sys.modules`` so that Twisted believes there is no installed reactor.'
def patch_modules(self):
old_modules = dict(sys.modules) new_modules = dict(sys.modules) del new_modules['twisted.internet.reactor'] def _cleanup(): sys.modules = old_modules self.addCleanup(_cleanup) sys.modules = new_modules
'``install_optimal_reactor`` will use the default reactor if it is unable to detect the platform it is running on.'
def test_unknown(self):
reactor_mock = Mock() self.patch_reactor('default', reactor_mock) self.patch(sys, 'platform', 'unknown') self.patch_modules() choosereactor.install_optimal_reactor() reactor_mock.install.assert_called_once_with()
'``install_optimal_reactor`` will install KQueueReactor on Darwin (OS X).'
def test_mac(self):
reactor_mock = Mock() self.patch_reactor('kqreactor', reactor_mock) self.patch(sys, 'platform', 'darwin') self.patch_modules() choosereactor.install_optimal_reactor() reactor_mock.install.assert_called_once_with()
'``install_optimal_reactor`` will install EPollReactor on Linux.'
def test_linux(self):
reactor_mock = Mock() self.patch_reactor('epollreactor', reactor_mock) self.patch(sys, 'platform', 'linux') self.patch_modules() choosereactor.install_optimal_reactor() reactor_mock.install.assert_called_once_with()
'A handshake from a client only supporting Hixie-76 will fail.'
def test_handshake_fails(self):
t = FakeTransport() f = WebSocketServerFactory() p = WebSocketServerProtocol() p.factory = f p.transport = t http_request = 'GET /demo HTTP/1.1\r\nHost: example.com\r\nConnection: Upgrade\r\nSec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\nSec-WebSocket-Protocol: sample...
'Test the examples from the docs'
def test_match_origin_documentation_example(self):
self.factory.setProtocolOptions(allowedOrigins=['*://*.example.com:*']) self.factory.isSecure = True self.factory.port = 443 self.proto.data = '\r\n'.join(['GET /ws HTTP/1.1', 'Host: www.example.com', 'Sec-WebSocket-Version: 13', 'Origin: http://www.example.com', 'Sec-WebSocket-Extensions...
'All the example origins from RFC6454 (3.2.1)'
def test_match_origin_examples(self):
from autobahn.websocket.protocol import _is_same_origin, _url_to_origin policy = wildcards2patterns(['*example.com:*']) for url in ['http://example.com/', 'http://example.com:80/', 'http://example.com/path/file', 'http://example.com/;semi=true', '//example.com/', 'http://@example.com']: self.assertT...
'All the example \'not-same\' origins from RFC6454 (3.2.1)'
def test_match_origin_counter_examples(self):
from autobahn.websocket.protocol import _is_same_origin, _url_to_origin policy = wildcards2patterns(['example.com']) for url in ['http://ietf.org/', 'http://example.org/', 'https://example.com/', 'http://example.com:8080/', 'http://www.example.com/']: self.assertFalse(_is_same_origin(_url_to_origin(...
'A client can connect to a server.'
def test_handshake_succeeds(self):
session_mock = Mock() t = FakeTransport() f = WampRawSocketClientFactory((lambda : session_mock)) p = WampRawSocketClientProtocol() p.transport = t p.factory = f server_session_mock = Mock() st = FakeTransport() sf = WampRawSocketServerFactory((lambda : server_session_mock)) sp =...
':param wsgiResource: The WSGI to serve as root resource. :type wsgiResource: Instance of `twisted.web.wsgi.WSGIResource <http://twistedmatrix.com/documents/current/api/twisted.web.wsgi.WSGIResource.html>`_. :param children: A dictionary with string keys constituting URL subpaths, and Twisted Web resources as values. :...
def __init__(self, wsgiResource, children):
Resource.__init__(self) self._wsgiResource = wsgiResource self.children = children
':param factory: An instance of :class:`autobahn.twisted.websocket.WebSocketServerFactory`. :type factory: obj'
def __init__(self, factory):
self._factory = factory
'This resource cannot have children, hence this will always fail.'
def getChildWithDefault(self, name, request):
return NoResource('No such child resource.')
'Render the resource. This will takeover the transport underlying the request, create a :class:`autobahn.twisted.websocket.WebSocketServerProtocol` and let that do any subsequent communication.'
def render(self, request):
protocol = self._factory.buildProtocol(request.transport.getPeer()) if (not protocol): request.setResponseCode(500) return '' (transport, request.channel.transport) = (request.channel.transport, None) if isinstance(transport, ProtocolWrapper): transport.wrappedProtocol = protocol...
'Create and connect a WAMP-over-XXX transport.'
def _connect_transport(self, loop, transport, session_factory):
factory = _create_transport_factory(loop, transport, session_factory) if (transport.endpoint[u'type'] == u'tcp'): version = transport.endpoint.get(u'version', 4) if (version not in [4, 6]): raise ValueError('invalid IP version {} in client endpoint configuration'...
'This starts the Component, which means it will start connecting (and re-connecting) to its configured transports. A Component runs until it is "done", which means one of: - There was a "main" function defined, and it completed successfully; - Something called ``.leave()`` on our session, and we left successfully; - ``...
def start(self, loop=None):
if (loop is None): self.log.warn('Using default loop') loop = asyncio.get_default_loop() done_f = txaio.create_future() transport_gen = itertools.cycle(self._transports) f0 = self.fire('start', loop, self) reconnect = [True] def one_reconnect_loop(_): self.log.debug...
'Implements :func:`autobahn.wamp.interfaces.ITransport.send`'
def send(self, msg):
if self.isOpen(): self.log.debug('WampRawSocketProtocol: TX WAMP message: {msg}', msg=msg) try: (payload, _) = self._serializer.serialize(msg) except Exception as e: raise SerializationError('WampRawSocketProtocol: unable to serialize WAMP a...
'Implements :func:`autobahn.wamp.interfaces.ITransport.isOpen`'
def isOpen(self):
return (hasattr(self, '_session') and (self._session is not None))
'Implements :func:`autobahn.wamp.interfaces.ITransport.close`'
def close(self):
if self.isOpen(): self.transport.close() else: raise TransportLost()
'Implements :func:`autobahn.wamp.interfaces.ITransport.abort`'
def abort(self):
if self.isOpen(): if hasattr(self.transport, 'abort'): self.transport.abort() else: self.transport.close() else: raise TransportLost()
'Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id`'
def get_channel_id(self, channel_id_type=u'tls-unique'):
return None
'Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id`'
def get_channel_id(self, channel_id_type=u'tls-unique'):
return None
':param factory: A callable that produces instances that implement :class:`autobahn.wamp.interfaces.ITransportHandler` :type factory: callable :param serializers: A list of WAMP serializers to use (or ``None`` for all available serializers). :type serializers: list of objects implementing :class:`autobahn.wamp.interfac...
def __init__(self, factory, serializers=None):
if callable(factory): self._factory = factory else: self._factory = (lambda : factory) if (serializers is None): serializers = get_serializers() if (not serializers): raise Exception('could not import any WAMP serializers') self._serializers = {...
':param factory: A callable that produces instances that implement :class:`autobahn.wamp.interfaces.ITransportHandler` :type factory: callable :param serializer: The WAMP serializer to use (or ``None`` for "best" serializer, chosen as the first serializer available from this list: CBOR, MessagePack, UBJSON, JSON). :typ...
def __init__(self, factory, serializer=None):
if callable(factory): self._factory = factory else: self._factory = (lambda : factory) if (serializer is None): serializers = get_serializers() if serializers: serializer = serializers[0] if (serializer is None): raise Exception('could not import...
'Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id`'
def get_channel_id(self):
self.log.debug('FIXME: transport channel binding not implemented for asyncio (autobahn-python issue #729)') return None
'.. note:: In addition to all arguments to the constructor of :meth:`autobahn.websocket.interfaces.IWebSocketServerChannelFactory`, you can supply a ``loop`` keyword argument to specify the asyncio event loop to be used.'
def __init__(self, *args, **kwargs):
loop = kwargs.pop('loop', None) self.loop = (loop or asyncio.get_event_loop()) protocol.WebSocketServerFactory.__init__(self, *args, **kwargs)
'.. note:: In addition to all arguments to the constructor of :meth:`autobahn.websocket.interfaces.IWebSocketClientChannelFactory`, you can supply a ``loop`` keyword argument to specify the asyncio event loop to be used.'
def __init__(self, *args, **kwargs):
loop = kwargs.pop('loop', None) self.loop = (loop or asyncio.get_event_loop()) protocol.WebSocketClientFactory.__init__(self, *args, **kwargs)
':param factory: A callable that produces instances that implement :class:`autobahn.wamp.interfaces.ITransportHandler` :type factory: callable :param serializers: A list of WAMP serializers to use (or ``None`` for all available serializers). :type serializers: list of objects implementing :class:`autobahn.wamp.interfac...
def __init__(self, factory, *args, **kwargs):
serializers = kwargs.pop('serializers', None) websocket.WampWebSocketServerFactory.__init__(self, factory, serializers) kwargs['protocols'] = self._protocols WebSocketServerFactory.__init__(self, *args, **kwargs)
':param factory: A callable that produces instances that implement :class:`autobahn.wamp.interfaces.ITransportHandler` :type factory: callable :param serializer: The WAMP serializer to use (or ``None`` for "best" serializer, chosen as the first serializer available from this list: CBOR, MessagePack, UBJSON, JSON). :typ...
def __init__(self, factory, *args, **kwargs):
serializers = kwargs.pop('serializers', None) websocket.WampWebSocketClientFactory.__init__(self, factory, serializers) kwargs['protocols'] = self._protocols WebSocketClientFactory.__init__(self, *args, **kwargs)
':param url: The WebSocket URL of the WAMP router to connect to (e.g. `ws://somehost.com:8090/somepath`) :type url: str :param realm: The WAMP realm to join the application session to. :type realm: str :param extra: Optional extra configuration to forward to the application component. :type extra: dict :param serialize...
def __init__(self, url, realm=None, extra=None, serializers=None, ssl=None, proxy=None, headers=None):
assert (type(url) == six.text_type) assert ((realm is None) or (type(realm) == six.text_type)) assert ((extra is None) or (type(extra) == dict)) assert ((headers is None) or (type(headers) == dict)) assert ((proxy is None) or (type(proxy) == dict)) self.url = url self.realm = realm self....
'Stop reconnecting, if auto-reconnecting was enabled.'
@public def stop(self):
raise NotImplementedError()
'Run the application component. Under the hood, this runs the event loop (unless `start_loop=False` is passed) so won\'t return until the program is done. :param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession` when called with an instance of :class:`autobahn.wamp.types.Compo...
@public def run(self, make, start_loop=True, log_level='info'):
if callable(make): def create(): cfg = ComponentConfig(self.realm, self.extra) try: session = make(cfg) except Exception as e: self.log.error('ApplicationSession could not be instantiated: {}'.format(e)) loop ...
'IdGenerator follows the generator protocol'
def test_idgenerator_is_generator(self):
g = IdGenerator() self.assertEqual(1, next(g)) self.assertEqual(2, next(g))
'A dictionary mapping field names to field values in this version of the model. Parent links of inherited multi-table models will not be followed.'
@cached_property def _local_field_dict(self):
version_options = _get_options(self._model) object_version = self._object_version obj = object_version.object model = self._model field_dict = {} for field_name in version_options.fields: field = model._meta.get_field(field_name) if isinstance(field, models.ManyToManyField): ...
'A dictionary mapping field names to field values in this version of the model. This method will follow parent links, if present.'
@cached_property def field_dict(self):
field_dict = self._local_field_dict for (parent_model, field) in self._model._meta.concrete_model._meta.parents.items(): content_type = _get_content_type(parent_model, self._state.db) parent_id = field_dict[field.attname] parent_version = self.revision.version_set.get(content_type=conten...
'Registers the model with reversion.'
def reversion_register(self, model, **kwargs):
register(model, **kwargs)
'Applies the correct ordering to the given version queryset.'
def _reversion_order_version_queryset(self, queryset):
if (not self.history_latest_first): queryset = queryset.order_by(u'pk') return queryset
'Displays a form that can recover a deleted model.'
def recover_view(self, request, version_id, extra_context=None):
if (not self.has_add_permission(request)): raise PermissionDenied version = get_object_or_404(Version, pk=version_id) context = {u'title': (_(u'Recover %(name)s') % {u'name': version.object_repr}), u'recover': True} context.update((extra_context or {})) return self._reversion_revisionform...
'Displays the contents of the given revision.'
def revision_view(self, request, object_id, version_id, extra_context=None):
object_id = unquote(object_id) version = get_object_or_404(Version, pk=version_id, object_id=object_id) context = {u'title': (_(u'Revert %(name)s') % {u'name': version.object_repr}), u'revert': True} context.update((extra_context or {})) return self._reversion_revisionform_view(request, version, ...
'Displays a deleted model to allow recovery.'
def recoverlist_view(self, request, extra_context=None):
if ((not self.has_change_permission(request)) or (not self.has_add_permission(request))): raise PermissionDenied model = self.model opts = model._meta deleted = self._reversion_order_version_queryset(Version.objects.get_deleted(self.model)) request.current_app = self.admin_site.name cont...
'Renders the history view.'
def history_view(self, request, object_id, extra_context=None):
if (not self.has_change_permission(request)): raise PermissionDenied object_id = unquote(object_id) opts = self.model._meta action_list = [{u'revision': version.revision, u'url': reverse((u'%s:%s_%s_revision' % (self.admin_site.name, opts.app_label, opts.model_name)), args=(quote(version.object_...
'Construct a new restoring initializer. Will read from the checkpoint from the SSTables file `filename` using the RestoreV2 Tensorflow op. The actual variable read from the checkpoint will be `scope_name` + \'/\' + `var_name` (or just `var_name` if `scope_name` is empty), where `scope_name` is given by one of (1) The c...
def __init__(self, filename, var_name, scope=None):
self._filename = filename self._var_name = var_name self._scope = scope
'Build magic (and sparsely documented) shapes_and_slices spec string.'
def _partition_spec(self, shape, partition_info):
if (partition_info is None): return '' ssi = tf.Variable.SaveSliceInfo(full_name=self._var_name, full_shape=partition_info.full_shape, var_offset=partition_info.var_offset, var_shape=shape) return ssi.spec
'Check if an error is raised if we don\'t specify the is_training flag.'
@parameterized.Parameters((True, False, False), (False, True, False), (False, False, True)) def testBatchNormBuildFlag(self, use_batch_norm_h, use_batch_norm_x, use_batch_norm_c):
batch_size = 2 hidden_size = 4 inputs = tf.placeholder(tf.float32, shape=[batch_size, hidden_size]) prev_cell = tf.placeholder(tf.float32, shape=[batch_size, hidden_size]) prev_hidden = tf.placeholder(tf.float32, shape=[batch_size, hidden_size]) err = 'is_training flag must be explic...
'Test that everything trains OK, with or without trainable init. state.'
@parameterized.Parameters((False, 1), (False, 2), (True, 1), (True, 2)) def testTraining(self, trainable_initial_state, max_unique_stats):
hidden_size = 3 batch_size = 3 time_steps = 3 cell = snt.BatchNormLSTM(hidden_size=hidden_size, max_unique_stats=max_unique_stats) inputs = tf.constant(np.random.rand(batch_size, time_steps, 3), dtype=tf.float32) initial_state = cell.initial_state(batch_size, tf.float32, trainable_initial_state)...
'Test that training works, with or without trainable initial state.'
@parameterized.Parameters((snt.Conv1DLSTM, 1, False), (snt.Conv1DLSTM, 1, True), (snt.Conv2DLSTM, 2, False), (snt.Conv2DLSTM, 2, True)) def testTraining(self, lstm_class, dim, trainable_initial_state):
time_steps = 1 batch_size = 2 input_shape = ((8,) * dim) input_channels = 3 output_channels = 5 input_shape = (((batch_size,) + input_shape) + (input_channels,)) lstm = lstm_class(input_shape=input_shape[1:], output_channels=output_channels, kernel_shape=1) inputs = tf.random_normal(((ti...
'Tests block lower-triangular matrix.'
def test_lower(self):
btm = block_matrix.BlockTriangularMatrix(block_shape=(2, 3), block_rows=3, upper=False) self.assertEqual(btm.num_blocks, 6) self.assertEqual(btm.block_size, 6) self.assertEqual(btm.input_size, 36) output = btm(create_input(btm.input_size)) with self.test_session() as sess: result = sess....
'Tests block lower-triangular matrix without diagonal.'
def test_lower_no_diagonal(self):
btm = block_matrix.BlockTriangularMatrix(block_shape=(2, 3), block_rows=3, include_diagonal=False) self.assertEqual(btm.num_blocks, 3) self.assertEqual(btm.block_size, 6) self.assertEqual(btm.input_size, 18) output = btm(create_input(btm.input_size)) with self.test_session() as sess: res...
'Tests block upper-triangular matrix.'
def test_upper(self):
btm = block_matrix.BlockTriangularMatrix(block_shape=(2, 3), block_rows=3, upper=True) self.assertEqual(btm.num_blocks, 6) self.assertEqual(btm.block_size, 6) self.assertEqual(btm.input_size, 36) output = btm(create_input(btm.input_size)) with self.test_session() as sess: result = sess.r...
'Tests block upper-triangular matrix without diagonal.'
def test_upper_no_diagonal(self):
btm = block_matrix.BlockTriangularMatrix(block_shape=(2, 3), block_rows=3, upper=True, include_diagonal=False) self.assertEqual(btm.num_blocks, 3) self.assertEqual(btm.block_size, 6) self.assertEqual(btm.input_size, 18) output = btm(create_input(btm.input_size)) with self.test_session() as sess:...
'Tests batching.'
def test_batch(self):
btm = block_matrix.BlockTriangularMatrix(block_shape=(2, 2), block_rows=2, upper=False) output = btm(create_input(12, batch_size=2)) with self.test_session() as sess: result = sess.run(output) self._check_output_size(btm, result, batch_size=2) expected = np.array([[[0, 1, 0, 0], [2, 3, 0, 0]...
'Tests BlockDiagonalMatrix.'
def test_default(self):
bdm = block_matrix.BlockDiagonalMatrix(block_shape=(2, 3), block_rows=3) self.assertEqual(bdm.num_blocks, 3) self.assertEqual(bdm.block_size, 6) self.assertEqual(bdm.input_size, 18) output = bdm(create_input(bdm.input_size)) with self.test_session() as sess: result = sess.run(output) ...
'Tests properties of BlockDiagonalMatrix.'
def test_properties(self):
bdm = block_matrix.BlockDiagonalMatrix(block_shape=(3, 5), block_rows=7) self.assertEqual(bdm.num_blocks, 7) self.assertEqual(bdm.block_size, 15) self.assertEqual(bdm.input_size, 105) self.assertEqual(bdm.output_shape, (21, 35)) self.assertEqual(bdm.block_shape, (3, 5))
'Performs the initialisation necessary for all AbstractModule instances. Every subclass of AbstractModule must begin their constructor with a call to this constructor, i.e. `super(MySubModule, self).__init__(name=name)`. If you instantiate sub-modules in __init__ you must create them within the `_enter_variable_scope` ...
def __init__(self, _sentinel=None, custom_getter=None, name=None):
if (_sentinel is not None): raise ValueError('Calling AbstractModule.__init__ without named arguments is deprecated.') if (name is None): name = util.to_snake_case(self.__class__.__name__) elif (not isinstance(name, six.string_types)): raise TypeError('Name must ...
'Function which will be wrapped in a Template to do variable sharing. Passes through all arguments to the _build method, and returns the corresponding outputs, plus the name_scope generated by this call of the template. Args: *args: args list for self._build **kwargs: kwargs dict for self._build Returns: A tuple contai...
def _build_wrapper(self, *args, **kwargs):
output = self._build(*args, **kwargs) with tf.name_scope('dummy') as scope_name: this_scope_name = scope_name[:(- len('/dummy/'))] return (output, this_scope_name)
'Checks that the base class\'s __init__ method has been called. Raises: NotInitializedError: `AbstractModule.__init__` has not been called.'
def _check_init_called(self):
try: self._template except AttributeError: raise NotInitializedError(('You may have forgotten to call super at the start of %s.__init__.' % self.__class__.__name__))
'Checks that the module is not being connect to multiple Graphs. An instance of a Sonnet module \'owns\' the variables it contains, and permits seamless variable sharing. As such, connecting a single module instance to multiple Graphs is not possible - this function will raise an error should that occur. Raises: Differ...
def _check_same_graph(self):
current_graph = tf.get_default_graph() if (self._graph is None): self._graph = current_graph elif (self._graph != current_graph): raise DifferentGraphError('Cannot connect module to multiple Graphs.')
'Operator overload for calling. This is the entry point when users connect a Module into the Graph. The underlying _build method will have been wrapped in a Template by the constructor, and we call this template with the provided inputs here. Args: *args: Arguments for underlying _build method. **kwargs: Keyword argume...
def __call__(self, *args, **kwargs):
self._check_init_called() self._check_same_graph() (outputs, this_name_scope) = self._template(*args, **kwargs) inputs = SubgraphInputs(args, kwargs) self._connected_subgraphs.append(ConnectedSubGraph(self, this_name_scope, inputs, outputs)) return outputs
'Returns a tuple of all name_scopes generated by this module.'
@property def name_scopes(self):
return tuple((subgraph.name_scope for subgraph in self._connected_subgraphs))
'Returns the variable_scope declared by the module. It is valid for library users to access the internal templated variable_scope, but only makes sense to do so after connection. Therefore we raise an error here if the variable_scope is requested before connection. The only case where it does make sense to access the v...
@property def variable_scope(self):
self._ensure_is_connected() return self._template.variable_scope
'Returns the full name of the Module\'s variable scope.'
@property def scope_name(self):
return self._template.variable_scope.name
'Returns the name of the Module.'
@property def module_name(self):
return self._unique_name
'Returns true iff the Module been connected to the Graph at least once.'
@property def is_connected(self):
return bool(self._connected_subgraphs)
'Returns the subgraphs created by this module so far.'
@property def connected_subgraphs(self):
return tuple(self._connected_subgraphs)
'Returns the last subgraph created by this module. Returns: The last connected subgraph. Raises: NotConnectedError: If the module is not connected to the Graph.'
@property def last_connected_subgraph(self):
self._ensure_is_connected() return self._connected_subgraphs[(-1)]
'Returns the keys the dictionary of variable initializers may contain. This provides the user with a way of knowing the initializer keys that are available without having to instantiate a sonnet module. Subclasses may override this class method if they need additional arguments to determine what initializer keys may be...
@classmethod def get_possible_initializer_keys(cls):
return getattr(cls, 'POSSIBLE_INITIALIZER_KEYS', set())
'Raise an Error if the module has not been connected yet. Until the module is connected into the Graph, any variables created do not exist yet and cannot be created in advance due to not knowing the size of the input Tensor(s). This assertion ensures that any variables contained in this module must now exist. Raises: N...
def _ensure_is_connected(self):
if (not self.is_connected): raise NotConnectedError('Variables in {} not instantiated yet, __call__ the module first.'.format(self.scope_name))
'Returns a contextlib.contextmanager to enter the internal variable scope. This is useful for situations where submodules must be declared in the constructor, or somewhere else that is not called under the `_build` method. If such a case arises, calling `with self._enter_variable_scope():` will cause the variables in t...
def _enter_variable_scope(self, reuse=None):
self._check_init_called() self._check_same_graph() return tf.variable_scope(self._template.variable_scope, reuse=reuse)
'Returns tuple of `tf.Variable`s declared inside this module. Note that this operates by searching this module\'s variable scope, and so does not know about any modules that were constructed elsewhere but used inside this module. Args: collection: Collection to restrict query to. By default this is `tf.Graphkeys.TRAINA...
def get_variables(self, collection=tf.GraphKeys.TRAINABLE_VARIABLES):
return util.get_variables_in_scope(self.variable_scope, collection=collection)
'Constructs a module with a given build function. The Module class can be used to wrap a function assembling a network into a module. For example, the following code implements a simple one-hidden-layer MLP model by defining a function called make_model and using a Module instance to wrap it. ```python def make_model(i...
def __init__(self, build, name=None):
if (not callable(build)): raise TypeError("Input 'build' must be callable.") if (name is None): name = util.name_for_callable(build) super(Module, self).__init__(name=name) self._build_function = build
'Forwards call to the passed-in build function.'
def _build(self, *args, **kwargs):
return self._build_function(*args, **kwargs)
'Constructor. Args: core: A `sonnet.RNNCore` object. This should only take a single `Tensor` in input, and output only a single flat `Tensor`. output_size: An integer. The size of each output in the sequence. threshold: A float between 0 and 1. Probability to reach for ACT to stop pondering. get_state_for_halting: A ca...
def __init__(self, core, output_size, threshold, get_state_for_halting, name='act_core'):
super(ACTCore, self).__init__(name=name) self._core = core self._output_size = output_size self._threshold = threshold self._get_state_for_halting = get_state_for_halting if (not isinstance(self._core.output_size, tf.TensorShape)): raise ValueError('Output of core should be ...
'The `cond` of the `tf.while_loop`.'
def _cond(self, unused_x, unused_cumul_out, unused_prev_state, unused_cumul_state, cumul_halting, unused_iteration, unused_remainder):
return tf.reduce_any((cumul_halting < 1))
'The `body` of `tf.while_loop`.'
def _body(self, x, cumul_out, prev_state, cumul_state, cumul_halting, iteration, remainder, halting_linear, x_ones):
all_ones = tf.constant(1, shape=(self._batch_size, 1), dtype=self._dtype) is_iteration_over = tf.equal(cumul_halting, all_ones) next_iteration = tf.where(is_iteration_over, iteration, (iteration + 1)) (out, next_state) = self._core(x, prev_state) halting_input = halting_linear(self._get_state_for_ha...
'Connects the core to the graph. Args: x: Input `Tensor` of shape `(batch_size, input_size)`. prev_state: Previous state. This could be a `Tensor`, or a tuple of `Tensor`s. Returns: The tuple `(output, state)` for this core. Raises: ValueError: if the `Tensor` `x` does not have rank 2.'
def _build(self, x, prev_state):
x.get_shape().with_rank(2) self._batch_size = x.get_shape().as_list()[0] self._dtype = x.dtype x_zeros = tf.concat([x, tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)], 1) x_ones = tf.concat([x, tf.ones(shape=(self._batch_size, 1), dtype=self._dtype)], 1) halting_linear = basic.Linear(n...
'Test whether the result for different Data Formats is the same.'
def helperDataFormats(self, func, x, use_bias, atol=1e-05):
mod1 = func(name='default') mod2 = func(name='NCHW_conv', data_format='NCHW') x_transpose = tf.transpose(x, perm=(0, 3, 1, 2)) o1 = mod1(x) o2 = tf.transpose(mod2(x_transpose), perm=(0, 2, 3, 1)) with self.test_session(use_gpu=True, force_gpu=True): tf.global_variables_initializer().run(...
'Test data formats for Conv2D.'
@parameterized.NamedParameters(('WithBias', True), ('WithoutBias', False)) def testConv2DDataFormats(self, use_bias):
func = functools.partial(snt.Conv2D, output_channels=self.OUT_CHANNELS, kernel_shape=self.KERNEL_SHAPE, use_bias=use_bias, initializers=create_constant_initializers(1.0, 1.0, use_bias)) x = tf.constant(np.random.random(self.INPUT_SHAPE).astype(np.float32)) self.helperDataFormats(func, x, use_bias)
'Test data formats for Conv2DTranspose.'
@parameterized.NamedParameters(('WithBias', True), ('WithoutBias', False)) def testConv2DTransposeDataFormats(self, use_bias):
(mb, h, w, c) = self.INPUT_SHAPE def func(name, data_format='NHWC'): shape = (self.INPUT_SHAPE if (data_format == 'NHWC') else (mb, c, h, w)) temp_input = tf.constant(0.0, dtype=tf.float32, shape=shape) mod = snt.Conv2D(name=name, output_channels=self.OUT_CHANNELS, kernel_shape=self.KERN...
'Tests data formats for the convolutions with batch normalization.'
@parameterized.NamedParameters(('WithBias', True), ('WithoutBias', False)) def testConv2DDataFormatsBatchNorm(self, use_bias):
def func(name, data_format='NHWC'): conv = snt.Conv2D(name=name, output_channels=self.OUT_CHANNELS, kernel_shape=self.KERNEL_SHAPE, use_bias=use_bias, initializers=create_constant_initializers(1.0, 1.0, use_bias), data_format=data_format) if (data_format == 'NHWC'): bn = snt.BatchNorm(sc...
'Constructs a LayerNorm module. Args: eps: small epsilon to avoid division by zero variance. Defaults to 1e-5 as used in the paper. initializers: Dict containing ops to initialize the scale (with key \'gamma\') and bias (with key \'beta\'). partitioners: Optional dict containing partitioners to partition the scale (wit...
def __init__(self, eps=1e-05, initializers=None, partitioners=None, regularizers=None, name='layer_norm'):
super(LayerNorm, self).__init__(name=name) self._eps = eps self._initializers = util.check_initializers(initializers, self.POSSIBLE_INITIALIZER_KEYS) self._partitioners = util.check_partitioners(partitioners, self.POSSIBLE_INITIALIZER_KEYS) self._regularizers = util.check_regularizers(regularizers, ...
'Connects the LayerNorm module into the graph. Args: inputs: a Tensor of shape `[batch_size, layer_dim]`. Returns: normalized: layer normalized outputs with same shape as inputs. Raises: base.NotSupportedError: If `inputs` has data type of `tf.float16`.'
def _build(self, inputs):
if (inputs.dtype == tf.float16): raise base.NotSupportedError('LayerNorm does not support `tf.float16`, insufficient precision for calculating sufficient statistics.') if (inputs.get_shape().ndims != 2): raise base.NotSupportedError('Layer normalization expect...
'Check that inputs are approximately centered and scaled.'
def testNormalization(self):
inputs = tf.constant([[1.0, 2.0, 3.0], [6.0, 4.0, 7.0]], dtype=tf.float32) ln = snt.LayerNorm() outputs = ln(inputs) init = tf.global_variables_initializer() with self.test_session() as sess: sess.run(init) outputs_ = sess.run(outputs) self.assertAllClose(outputs_.mean(axis=1...