repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
etingof/pysnmp
pysnmp/smi/mibs/SNMPv2-SMI.py
MibTableRow.getInstIdFromIndices
def getInstIdFromIndices(self, *indices): """Return column instance identification from indices""" try: return self._idxToIdCache[indices] except TypeError: cacheable = False except KeyError: cacheable = True idx = 0 instId = () ...
python
def getInstIdFromIndices(self, *indices): """Return column instance identification from indices""" try: return self._idxToIdCache[indices] except TypeError: cacheable = False except KeyError: cacheable = True idx = 0 instId = () ...
[ "def", "getInstIdFromIndices", "(", "self", ",", "*", "indices", ")", ":", "try", ":", "return", "self", ".", "_idxToIdCache", "[", "indices", "]", "except", "TypeError", ":", "cacheable", "=", "False", "except", "KeyError", ":", "cacheable", "=", "True", ...
Return column instance identification from indices
[ "Return", "column", "instance", "identification", "from", "indices" ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3308-L3329
train
etingof/pysnmp
pysnmp/smi/mibs/SNMPv2-SMI.py
MibTableRow.getInstNameByIndex
def getInstNameByIndex(self, colId, *indices): """Build column instance name from components""" return self.name + (colId,) + self.getInstIdFromIndices(*indices)
python
def getInstNameByIndex(self, colId, *indices): """Build column instance name from components""" return self.name + (colId,) + self.getInstIdFromIndices(*indices)
[ "def", "getInstNameByIndex", "(", "self", ",", "colId", ",", "*", "indices", ")", ":", "return", "self", ".", "name", "+", "(", "colId", ",", ")", "+", "self", ".", "getInstIdFromIndices", "(", "*", "indices", ")" ]
Build column instance name from components
[ "Build", "column", "instance", "name", "from", "components" ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3333-L3335
train
etingof/pysnmp
pysnmp/smi/mibs/SNMPv2-SMI.py
MibTableRow.getInstNamesByIndex
def getInstNamesByIndex(self, *indices): """Build column instance names from indices""" instNames = [] for columnName in self._vars.keys(): instNames.append( self.getInstNameByIndex(*(columnName[-1],) + indices) ) return tuple(instNames)
python
def getInstNamesByIndex(self, *indices): """Build column instance names from indices""" instNames = [] for columnName in self._vars.keys(): instNames.append( self.getInstNameByIndex(*(columnName[-1],) + indices) ) return tuple(instNames)
[ "def", "getInstNamesByIndex", "(", "self", ",", "*", "indices", ")", ":", "instNames", "=", "[", "]", "for", "columnName", "in", "self", ".", "_vars", ".", "keys", "(", ")", ":", "instNames", ".", "append", "(", "self", ".", "getInstNameByIndex", "(", ...
Build column instance names from indices
[ "Build", "column", "instance", "names", "from", "indices" ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3337-L3345
train
etingof/pysnmp
pysnmp/hlapi/v3arch/asyncore/sync/cmdgen.py
nextCmd
def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP GETNEXT queries. On each iteration, new SNMP GETNEXT request is send (:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response to arrive or e...
python
def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP GETNEXT queries. On each iteration, new SNMP GETNEXT request is send (:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response to arrive or e...
[ "def", "nextCmd", "(", "snmpEngine", ",", "authData", ",", "transportTarget", ",", "contextData", ",", "*", "varBinds", ",", "**", "options", ")", ":", "def", "cbFun", "(", "snmpEngine", ",", "sendRequestHandle", ",", "errorIndication", ",", "errorStatus", ","...
Creates a generator to perform one or more SNMP GETNEXT queries. On each iteration, new SNMP GETNEXT request is send (:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` ...
[ "Creates", "a", "generator", "to", "perform", "one", "or", "more", "SNMP", "GETNEXT", "queries", "." ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/asyncore/sync/cmdgen.py#L229-L413
train
etingof/pysnmp
pysnmp/entity/rfc3413/cmdrsp.py
CommandResponderBase._storeAccessContext
def _storeAccessContext(snmpEngine): """Copy received message metadata while it lasts""" execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request') return { 'securityModel': execCtx['securityModel'], 'securityName': execCtx['securityName'], ...
python
def _storeAccessContext(snmpEngine): """Copy received message metadata while it lasts""" execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request') return { 'securityModel': execCtx['securityModel'], 'securityName': execCtx['securityName'], ...
[ "def", "_storeAccessContext", "(", "snmpEngine", ")", ":", "execCtx", "=", "snmpEngine", ".", "observer", ".", "getExecutionContext", "(", "'rfc3412.receiveMessage:request'", ")", "return", "{", "'securityModel'", ":", "execCtx", "[", "'securityModel'", "]", ",", "'...
Copy received message metadata while it lasts
[ "Copy", "received", "message", "metadata", "while", "it", "lasts" ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/entity/rfc3413/cmdrsp.py#L174-L184
train
etingof/pysnmp
pysnmp/entity/rfc3413/cmdrsp.py
NextCommandResponder._getManagedObjectsInstances
def _getManagedObjectsInstances(self, varBinds, **context): """Iterate over Managed Objects fulfilling SNMP query. Returns ------- :py:class:`list` - List of Managed Objects Instances to respond with or `None` to indicate that not all objects have been gathered s...
python
def _getManagedObjectsInstances(self, varBinds, **context): """Iterate over Managed Objects fulfilling SNMP query. Returns ------- :py:class:`list` - List of Managed Objects Instances to respond with or `None` to indicate that not all objects have been gathered s...
[ "def", "_getManagedObjectsInstances", "(", "self", ",", "varBinds", ",", "**", "context", ")", ":", "rspVarBinds", "=", "context", "[", "'rspVarBinds'", "]", "varBindsMap", "=", "context", "[", "'varBindsMap'", "]", "rtrVarBinds", "=", "[", "]", "for", "idx", ...
Iterate over Managed Objects fulfilling SNMP query. Returns ------- :py:class:`list` - List of Managed Objects Instances to respond with or `None` to indicate that not all objects have been gathered so far.
[ "Iterate", "over", "Managed", "Objects", "fulfilling", "SNMP", "query", "." ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/entity/rfc3413/cmdrsp.py#L339-L375
train
etingof/pysnmp
pysnmp/proto/rfc1155.py
NetworkAddress.clone
def clone(self, value=univ.noValue, **kwargs): """Clone this instance. If *value* is specified, use its tag as the component type selector, and itself as the component value. :param value: (Optional) the component value. :type value: :py:obj:`pyasn1.type.base.Asn1ItemBase` ...
python
def clone(self, value=univ.noValue, **kwargs): """Clone this instance. If *value* is specified, use its tag as the component type selector, and itself as the component value. :param value: (Optional) the component value. :type value: :py:obj:`pyasn1.type.base.Asn1ItemBase` ...
[ "def", "clone", "(", "self", ",", "value", "=", "univ", ".", "noValue", ",", "**", "kwargs", ")", ":", "cloned", "=", "univ", ".", "Choice", ".", "clone", "(", "self", ",", "**", "kwargs", ")", "if", "value", "is", "not", "univ", ".", "noValue", ...
Clone this instance. If *value* is specified, use its tag as the component type selector, and itself as the component value. :param value: (Optional) the component value. :type value: :py:obj:`pyasn1.type.base.Asn1ItemBase` :return: the cloned instance. :rtype: :py:obj:...
[ "Clone", "this", "instance", "." ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1155.py#L63-L95
train
etingof/pysnmp
pysnmp/smi/instrum.py
MibInstrumController._defaultErrorHandler
def _defaultErrorHandler(varBinds, **context): """Raise exception on any error if user callback is missing""" errors = context.get('errors') if errors: err = errors[-1] raise err['error']
python
def _defaultErrorHandler(varBinds, **context): """Raise exception on any error if user callback is missing""" errors = context.get('errors') if errors: err = errors[-1] raise err['error']
[ "def", "_defaultErrorHandler", "(", "varBinds", ",", "**", "context", ")", ":", "errors", "=", "context", ".", "get", "(", "'errors'", ")", "if", "errors", ":", "err", "=", "errors", "[", "-", "1", "]", "raise", "err", "[", "'error'", "]" ]
Raise exception on any error if user callback is missing
[ "Raise", "exception", "on", "any", "error", "if", "user", "callback", "is", "missing" ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L375-L381
train
etingof/pysnmp
pysnmp/smi/instrum.py
MibInstrumController.readMibObjects
def readMibObjects(self, *varBinds, **context): """Read Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the referenced Managed Objects Instances. Parameters ---------- varBinds: :py:class:`tuple` of :py...
python
def readMibObjects(self, *varBinds, **context): """Read Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the referenced Managed Objects Instances. Parameters ---------- varBinds: :py:class:`tuple` of :py...
[ "def", "readMibObjects", "(", "self", ",", "*", "varBinds", ",", "**", "context", ")", ":", "if", "'cbFun'", "not", "in", "context", ":", "context", "[", "'cbFun'", "]", "=", "self", ".", "_defaultErrorHandler", "self", ".", "flipFlopFsm", "(", "self", "...
Read Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the referenced Managed Objects Instances. Parameters ---------- varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects ...
[ "Read", "Managed", "Objects", "Instances", "." ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L383-L435
train
etingof/pysnmp
pysnmp/smi/instrum.py
MibInstrumController.readNextMibObjects
def readNextMibObjects(self, *varBinds, **context): """Read Managed Objects Instances next to the given ones. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the Managed Objects Instances next to the referenced ones. Parameters ---------...
python
def readNextMibObjects(self, *varBinds, **context): """Read Managed Objects Instances next to the given ones. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the Managed Objects Instances next to the referenced ones. Parameters ---------...
[ "def", "readNextMibObjects", "(", "self", ",", "*", "varBinds", ",", "**", "context", ")", ":", "if", "'cbFun'", "not", "in", "context", ":", "context", "[", "'cbFun'", "]", "=", "self", ".", "_defaultErrorHandler", "self", ".", "flipFlopFsm", "(", "self",...
Read Managed Objects Instances next to the given ones. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the Managed Objects Instances next to the referenced ones. Parameters ---------- varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi...
[ "Read", "Managed", "Objects", "Instances", "next", "to", "the", "given", "ones", "." ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L437-L495
train
etingof/pysnmp
pysnmp/smi/instrum.py
MibInstrumController.writeMibObjects
def writeMibObjects(self, *varBinds, **context): """Create, destroy or modify Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create, destroy or modify all or none of the referenced Managed Objects Instances. If a non-existing Managed Ob...
python
def writeMibObjects(self, *varBinds, **context): """Create, destroy or modify Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create, destroy or modify all or none of the referenced Managed Objects Instances. If a non-existing Managed Ob...
[ "def", "writeMibObjects", "(", "self", ",", "*", "varBinds", ",", "**", "context", ")", ":", "if", "'cbFun'", "not", "in", "context", ":", "context", "[", "'cbFun'", "]", "=", "self", ".", "_defaultErrorHandler", "self", ".", "flipFlopFsm", "(", "self", ...
Create, destroy or modify Managed Objects Instances. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create, destroy or modify all or none of the referenced Managed Objects Instances. If a non-existing Managed Object Instance is written, the new Managed Object Ins...
[ "Create", "destroy", "or", "modify", "Managed", "Objects", "Instances", "." ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L497-L564
train
etingof/pysnmp
pysnmp/hlapi/v1arch/asyncore/cmdgen.py
bulkCmd
def bulkCmd(snmpDispatcher, authData, transportTarget, nonRepeaters, maxRepetitions, *varBinds, **options): """Initiate SNMP GETBULK query over SNMPv2c. Based on passed parameters, prepares SNMP GETBULK packet (:RFC:`1905#section-4.2.3`) and schedules its transmission by I/O framework at a ...
python
def bulkCmd(snmpDispatcher, authData, transportTarget, nonRepeaters, maxRepetitions, *varBinds, **options): """Initiate SNMP GETBULK query over SNMPv2c. Based on passed parameters, prepares SNMP GETBULK packet (:RFC:`1905#section-4.2.3`) and schedules its transmission by I/O framework at a ...
[ "def", "bulkCmd", "(", "snmpDispatcher", ",", "authData", ",", "transportTarget", ",", "nonRepeaters", ",", "maxRepetitions", ",", "*", "varBinds", ",", "**", "options", ")", ":", "def", "_cbFun", "(", "snmpDispatcher", ",", "stateHandle", ",", "errorIndication"...
Initiate SNMP GETBULK query over SNMPv2c. Based on passed parameters, prepares SNMP GETBULK packet (:RFC:`1905#section-4.2.3`) and schedules its transmission by I/O framework at a later point of time. Parameters ---------- snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher...
[ "Initiate", "SNMP", "GETBULK", "query", "over", "SNMPv2c", "." ]
cde062dd42f67dfd2d7686286a322d40e9c3a4b7
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v1arch/asyncore/cmdgen.py#L451-L626
train
markreidvfx/pyaaf2
aaf2/file.py
AAFFile.save
def save(self): """ Writes current changes to disk and flushes modified objects in the AAFObjectManager """ if self.mode in ("wb+", 'rb+'): if not self.is_open: raise IOError("file closed") self.write_reference_properties() self...
python
def save(self): """ Writes current changes to disk and flushes modified objects in the AAFObjectManager """ if self.mode in ("wb+", 'rb+'): if not self.is_open: raise IOError("file closed") self.write_reference_properties() self...
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "mode", "in", "(", "\"wb+\"", ",", "'rb+'", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "IOError", "(", "\"file closed\"", ")", "self", ".", "write_reference_properties", "(", ")...
Writes current changes to disk and flushes modified objects in the AAFObjectManager
[ "Writes", "current", "changes", "to", "disk", "and", "flushes", "modified", "objects", "in", "the", "AAFObjectManager" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L339-L348
train
markreidvfx/pyaaf2
aaf2/file.py
AAFFile.close
def close(self): """ Close the file. A closed file cannot be read or written any more. """ self.save() self.manager.remove_temp() self.cfb.close() self.is_open = False self.f.close()
python
def close(self): """ Close the file. A closed file cannot be read or written any more. """ self.save() self.manager.remove_temp() self.cfb.close() self.is_open = False self.f.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "save", "(", ")", "self", ".", "manager", ".", "remove_temp", "(", ")", "self", ".", "cfb", ".", "close", "(", ")", "self", ".", "is_open", "=", "False", "self", ".", "f", ".", "close", "(", "...
Close the file. A closed file cannot be read or written any more.
[ "Close", "the", "file", ".", "A", "closed", "file", "cannot", "be", "read", "or", "written", "any", "more", "." ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L350-L358
train
markreidvfx/pyaaf2
docs/source/conf.py
run_apidoc
def run_apidoc(_): """This method is required by the setup method below.""" import os dirname = os.path.dirname(__file__) ignore_paths = [os.path.join(dirname, '../../aaf2/model'),] # https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py argv = [ '--force', '--no-...
python
def run_apidoc(_): """This method is required by the setup method below.""" import os dirname = os.path.dirname(__file__) ignore_paths = [os.path.join(dirname, '../../aaf2/model'),] # https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py argv = [ '--force', '--no-...
[ "def", "run_apidoc", "(", "_", ")", ":", "import", "os", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "ignore_paths", "=", "[", "os", ".", "path", ".", "join", "(", "dirname", ",", "'../../aaf2/model'", ")", ",", "]", "arg...
This method is required by the setup method below.
[ "This", "method", "is", "required", "by", "the", "setup", "method", "below", "." ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/docs/source/conf.py#L182-L199
train
markreidvfx/pyaaf2
aaf2/mobid.py
MobID.from_dict
def from_dict(self, d): """ Set MobID from a dict """ self.length = d.get("length", 0) self.instanceHigh = d.get("instanceHigh", 0) self.instanceMid = d.get("instanceMid", 0) self.instanceLow = d.get("instanceLow", 0) material = d.get("material", {'Data1'...
python
def from_dict(self, d): """ Set MobID from a dict """ self.length = d.get("length", 0) self.instanceHigh = d.get("instanceHigh", 0) self.instanceMid = d.get("instanceMid", 0) self.instanceLow = d.get("instanceLow", 0) material = d.get("material", {'Data1'...
[ "def", "from_dict", "(", "self", ",", "d", ")", ":", "self", ".", "length", "=", "d", ".", "get", "(", "\"length\"", ",", "0", ")", "self", ".", "instanceHigh", "=", "d", ".", "get", "(", "\"instanceHigh\"", ",", "0", ")", "self", ".", "instanceMid...
Set MobID from a dict
[ "Set", "MobID", "from", "a", "dict" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L280-L296
train
markreidvfx/pyaaf2
aaf2/mobid.py
MobID.to_dict
def to_dict(self): """ MobID representation as dict """ material = {'Data1': self.Data1, 'Data2': self.Data2, 'Data3': self.Data3, 'Data4': list(self.Data4) } return {'material':material, ...
python
def to_dict(self): """ MobID representation as dict """ material = {'Data1': self.Data1, 'Data2': self.Data2, 'Data3': self.Data3, 'Data4': list(self.Data4) } return {'material':material, ...
[ "def", "to_dict", "(", "self", ")", ":", "material", "=", "{", "'Data1'", ":", "self", ".", "Data1", ",", "'Data2'", ":", "self", ".", "Data2", ",", "'Data3'", ":", "self", ".", "Data3", ",", "'Data4'", ":", "list", "(", "self", ".", "Data4", ")", ...
MobID representation as dict
[ "MobID", "representation", "as", "dict" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L298-L315
train
markreidvfx/pyaaf2
aaf2/ama.py
wave_infochunk
def wave_infochunk(path): """ Returns a bytearray of the WAVE RIFF header and fmt chunk for a `WAVEDescriptor` `Summary` """ with open(path,'rb') as file: if file.read(4) != b"RIFF": return None data_size = file.read(4) # container size if file.read(4) != b"WAVE":...
python
def wave_infochunk(path): """ Returns a bytearray of the WAVE RIFF header and fmt chunk for a `WAVEDescriptor` `Summary` """ with open(path,'rb') as file: if file.read(4) != b"RIFF": return None data_size = file.read(4) # container size if file.read(4) != b"WAVE":...
[ "def", "wave_infochunk", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "file", ":", "if", "file", ".", "read", "(", "4", ")", "!=", "b\"RIFF\"", ":", "return", "None", "data_size", "=", "file", ".", "read", "(", "4", ...
Returns a bytearray of the WAVE RIFF header and fmt chunk for a `WAVEDescriptor` `Summary`
[ "Returns", "a", "bytearray", "of", "the", "WAVE", "RIFF", "header", "and", "fmt", "chunk", "for", "a", "WAVEDescriptor", "Summary" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/ama.py#L329-L353
train
markreidvfx/pyaaf2
aaf2/cfb.py
DirEntry.pop
def pop(self): """ remove self from binary search tree """ entry = self parent = self.parent root = parent.child() dir_per_sector = self.storage.sector_size // 128 max_dirs_entries = self.storage.dir_sector_count * dir_per_sector count = 0 ...
python
def pop(self): """ remove self from binary search tree """ entry = self parent = self.parent root = parent.child() dir_per_sector = self.storage.sector_size // 128 max_dirs_entries = self.storage.dir_sector_count * dir_per_sector count = 0 ...
[ "def", "pop", "(", "self", ")", ":", "entry", "=", "self", "parent", "=", "self", ".", "parent", "root", "=", "parent", ".", "child", "(", ")", "dir_per_sector", "=", "self", ".", "storage", ".", "sector_size", "//", "128", "max_dirs_entries", "=", "se...
remove self from binary search tree
[ "remove", "self", "from", "binary", "search", "tree" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L609-L664
train
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.remove
def remove(self, path): """ Removes both streams and storage DirEntry types from file. storage type entries need to be empty dirs. """ entry = self.find(path) if not entry: raise ValueError("%s does not exists" % path) if entry.type == 'root storage...
python
def remove(self, path): """ Removes both streams and storage DirEntry types from file. storage type entries need to be empty dirs. """ entry = self.find(path) if not entry: raise ValueError("%s does not exists" % path) if entry.type == 'root storage...
[ "def", "remove", "(", "self", ",", "path", ")", ":", "entry", "=", "self", ".", "find", "(", "path", ")", "if", "not", "entry", ":", "raise", "ValueError", "(", "\"%s does not exists\"", "%", "path", ")", "if", "entry", ".", "type", "==", "'root storag...
Removes both streams and storage DirEntry types from file. storage type entries need to be empty dirs.
[ "Removes", "both", "streams", "and", "storage", "DirEntry", "types", "from", "file", ".", "storage", "type", "entries", "need", "to", "be", "empty", "dirs", "." ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1606-L1629
train
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.rmtree
def rmtree(self, path): """ Removes directory structure, similar to shutil.rmtree. """ for root, storage, streams in self.walk(path, topdown=False): for item in streams: self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size) ...
python
def rmtree(self, path): """ Removes directory structure, similar to shutil.rmtree. """ for root, storage, streams in self.walk(path, topdown=False): for item in streams: self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size) ...
[ "def", "rmtree", "(", "self", ",", "path", ")", ":", "for", "root", ",", "storage", ",", "streams", "in", "self", ".", "walk", "(", "path", ",", "topdown", "=", "False", ")", ":", "for", "item", "in", "streams", ":", "self", ".", "free_fat_chain", ...
Removes directory structure, similar to shutil.rmtree.
[ "Removes", "directory", "structure", "similar", "to", "shutil", ".", "rmtree", "." ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1632-L1648
train
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.listdir_dict
def listdir_dict(self, path = None): """ Return a dict containing the ``DirEntry`` objects in the directory given by path with name of the dir as key. """ if path is None: path = self.root root = self.find(path) if root is None: raise Val...
python
def listdir_dict(self, path = None): """ Return a dict containing the ``DirEntry`` objects in the directory given by path with name of the dir as key. """ if path is None: path = self.root root = self.find(path) if root is None: raise Val...
[ "def", "listdir_dict", "(", "self", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "self", ".", "root", "root", "=", "self", ".", "find", "(", "path", ")", "if", "root", "is", "None", ":", "raise", "ValueError", ...
Return a dict containing the ``DirEntry`` objects in the directory given by path with name of the dir as key.
[ "Return", "a", "dict", "containing", "the", "DirEntry", "objects", "in", "the", "directory", "given", "by", "path", "with", "name", "of", "the", "dir", "as", "key", "." ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1660-L1709
train
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.makedir
def makedir(self, path, class_id=None): """ Create a storage DirEntry name path """ return self.create_dir_entry(path, dir_type='storage', class_id=class_id)
python
def makedir(self, path, class_id=None): """ Create a storage DirEntry name path """ return self.create_dir_entry(path, dir_type='storage', class_id=class_id)
[ "def", "makedir", "(", "self", ",", "path", ",", "class_id", "=", "None", ")", ":", "return", "self", ".", "create_dir_entry", "(", "path", ",", "dir_type", "=", "'storage'", ",", "class_id", "=", "class_id", ")" ]
Create a storage DirEntry name path
[ "Create", "a", "storage", "DirEntry", "name", "path" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1800-L1804
train
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.makedirs
def makedirs(self, path): """ Recursive storage DirEntry creation function. """ root = "" assert path.startswith('/') p = path.strip('/') for item in p.split('/'): root += "/" + item if not self.exists(root): self.makedir(r...
python
def makedirs(self, path): """ Recursive storage DirEntry creation function. """ root = "" assert path.startswith('/') p = path.strip('/') for item in p.split('/'): root += "/" + item if not self.exists(root): self.makedir(r...
[ "def", "makedirs", "(", "self", ",", "path", ")", ":", "root", "=", "\"\"", "assert", "path", ".", "startswith", "(", "'/'", ")", "p", "=", "path", ".", "strip", "(", "'/'", ")", "for", "item", "in", "p", ".", "split", "(", "'/'", ")", ":", "ro...
Recursive storage DirEntry creation function.
[ "Recursive", "storage", "DirEntry", "creation", "function", "." ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1806-L1819
train
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.move
def move(self, src, dst): """ Moves ``DirEntry`` from src to dst """ src_entry = self.find(src) if src_entry is None: raise ValueError("src path does not exist: %s" % src) if dst.endswith('/'): dst += src_entry.name if self.exists(dst): ...
python
def move(self, src, dst): """ Moves ``DirEntry`` from src to dst """ src_entry = self.find(src) if src_entry is None: raise ValueError("src path does not exist: %s" % src) if dst.endswith('/'): dst += src_entry.name if self.exists(dst): ...
[ "def", "move", "(", "self", ",", "src", ",", "dst", ")", ":", "src_entry", "=", "self", ".", "find", "(", "src", ")", "if", "src_entry", "is", "None", ":", "raise", "ValueError", "(", "\"src path does not exist: %s\"", "%", "src", ")", "if", "dst", "."...
Moves ``DirEntry`` from src to dst
[ "Moves", "DirEntry", "from", "src", "to", "dst" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1821-L1862
train
markreidvfx/pyaaf2
aaf2/cfb.py
CompoundFileBinary.open
def open(self, path, mode='r'): """Open stream, returning ``Stream`` object""" entry = self.find(path) if entry is None: if mode == 'r': raise ValueError("stream does not exists: %s" % path) entry = self.create_dir_entry(path, 'stream', None) els...
python
def open(self, path, mode='r'): """Open stream, returning ``Stream`` object""" entry = self.find(path) if entry is None: if mode == 'r': raise ValueError("stream does not exists: %s" % path) entry = self.create_dir_entry(path, 'stream', None) els...
[ "def", "open", "(", "self", ",", "path", ",", "mode", "=", "'r'", ")", ":", "entry", "=", "self", ".", "find", "(", "path", ")", "if", "entry", "is", "None", ":", "if", "mode", "==", "'r'", ":", "raise", "ValueError", "(", "\"stream does not exists: ...
Open stream, returning ``Stream`` object
[ "Open", "stream", "returning", "Stream", "object" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1864-L1887
train
markreidvfx/pyaaf2
aaf2/properties.py
add2set
def add2set(self, pid, key, value): """low level add to StrongRefSetProperty""" prop = self.property_entries[pid] current = prop.objects.get(key, None) current_local_key = prop.references.get(key, None) if current and current is not value: current.detach() if current_local_key is None...
python
def add2set(self, pid, key, value): """low level add to StrongRefSetProperty""" prop = self.property_entries[pid] current = prop.objects.get(key, None) current_local_key = prop.references.get(key, None) if current and current is not value: current.detach() if current_local_key is None...
[ "def", "add2set", "(", "self", ",", "pid", ",", "key", ",", "value", ")", ":", "prop", "=", "self", ".", "property_entries", "[", "pid", "]", "current", "=", "prop", ".", "objects", ".", "get", "(", "key", ",", "None", ")", "current_local_key", "=", ...
low level add to StrongRefSetProperty
[ "low", "level", "add", "to", "StrongRefSetProperty" ]
37de8c10d3c3495cc00c705eb6c5048bc4a7e51f
https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/properties.py#L1313-L1336
train
MillionIntegrals/vel
vel/rl/modules/q_distributional_head.py
QDistributionalHead.histogram_info
def histogram_info(self) -> dict: """ Return extra information about histogram """ return { 'support_atoms': self.support_atoms, 'atom_delta': self.atom_delta, 'vmin': self.vmin, 'vmax': self.vmax, 'num_atoms': self.atoms }
python
def histogram_info(self) -> dict: """ Return extra information about histogram """ return { 'support_atoms': self.support_atoms, 'atom_delta': self.atom_delta, 'vmin': self.vmin, 'vmax': self.vmax, 'num_atoms': self.atoms }
[ "def", "histogram_info", "(", "self", ")", "->", "dict", ":", "return", "{", "'support_atoms'", ":", "self", ".", "support_atoms", ",", "'atom_delta'", ":", "self", ".", "atom_delta", ",", "'vmin'", ":", "self", ".", "vmin", ",", "'vmax'", ":", "self", "...
Return extra information about histogram
[ "Return", "extra", "information", "about", "histogram" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/q_distributional_head.py#L31-L39
train
MillionIntegrals/vel
vel/rl/modules/q_distributional_head.py
QDistributionalHead.sample
def sample(self, histogram_logits): """ Sample from a greedy strategy with given q-value histogram """ histogram_probs = histogram_logits.exp() # Batch size * actions * atoms atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions return (histogram_prob...
python
def sample(self, histogram_logits): """ Sample from a greedy strategy with given q-value histogram """ histogram_probs = histogram_logits.exp() # Batch size * actions * atoms atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions return (histogram_prob...
[ "def", "sample", "(", "self", ",", "histogram_logits", ")", ":", "histogram_probs", "=", "histogram_logits", ".", "exp", "(", ")", "atoms", "=", "self", ".", "support_atoms", ".", "view", "(", "1", ",", "1", ",", "self", ".", "atoms", ")", "return", "(...
Sample from a greedy strategy with given q-value histogram
[ "Sample", "from", "a", "greedy", "strategy", "with", "given", "q", "-", "value", "histogram" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/q_distributional_head.py#L52-L56
train
MillionIntegrals/vel
vel/sources/nlp/text_url.py
TextUrlSource.download
def download(self): """ Make sure data file is downloaded and stored properly """ if not os.path.exists(self.data_path): # Create if it doesn't exist pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True) if not os.path.exists(self.text_path): http =...
python
def download(self): """ Make sure data file is downloaded and stored properly """ if not os.path.exists(self.data_path): # Create if it doesn't exist pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True) if not os.path.exists(self.text_path): http =...
[ "def", "download", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "data_path", ")", ":", "pathlib", ".", "Path", "(", "self", ".", "data_path", ")", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok"...
Make sure data file is downloaded and stored properly
[ "Make", "sure", "data", "file", "is", "downloaded", "and", "stored", "properly" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/nlp/text_url.py#L148-L186
train
MillionIntegrals/vel
vel/math/functions.py
explained_variance
def explained_variance(returns, values): """ Calculate how much variance in returns do the values explain """ exp_var = 1 - torch.var(returns - values) / torch.var(returns) return exp_var.item()
python
def explained_variance(returns, values): """ Calculate how much variance in returns do the values explain """ exp_var = 1 - torch.var(returns - values) / torch.var(returns) return exp_var.item()
[ "def", "explained_variance", "(", "returns", ",", "values", ")", ":", "exp_var", "=", "1", "-", "torch", ".", "var", "(", "returns", "-", "values", ")", "/", "torch", ".", "var", "(", "returns", ")", "return", "exp_var", ".", "item", "(", ")" ]
Calculate how much variance in returns do the values explain
[ "Calculate", "how", "much", "variance", "in", "returns", "do", "the", "values", "explain" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/math/functions.py#L4-L7
train
MillionIntegrals/vel
vel/sources/img_dir_source.py
create
def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None): """ Create an ImageDirSource with supplied arguments """ if not os.path.isabs(path): path = model_config.project_top_dir(path) train_path = os.path.join(path, 'train') valid_path = os.path.join(path, 'valid')...
python
def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None): """ Create an ImageDirSource with supplied arguments """ if not os.path.isabs(path): path = model_config.project_top_dir(path) train_path = os.path.join(path, 'train') valid_path = os.path.join(path, 'valid')...
[ "def", "create", "(", "model_config", ",", "path", ",", "num_workers", ",", "batch_size", ",", "augmentations", "=", "None", ",", "tta", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "path", "=", "model_c...
Create an ImageDirSource with supplied arguments
[ "Create", "an", "ImageDirSource", "with", "supplied", "arguments" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/img_dir_source.py#L12-L30
train
MillionIntegrals/vel
vel/rl/models/q_model.py
QModel.reset_weights
def reset_weights(self): """ Initialize weights to reasonable defaults """ self.input_block.reset_weights() self.backbone.reset_weights() self.q_head.reset_weights()
python
def reset_weights(self): """ Initialize weights to reasonable defaults """ self.input_block.reset_weights() self.backbone.reset_weights() self.q_head.reset_weights()
[ "def", "reset_weights", "(", "self", ")", ":", "self", ".", "input_block", ".", "reset_weights", "(", ")", "self", ".", "backbone", ".", "reset_weights", "(", ")", "self", ".", "q_head", ".", "reset_weights", "(", ")" ]
Initialize weights to reasonable defaults
[ "Initialize", "weights", "to", "reasonable", "defaults" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/models/q_model.py#L50-L54
train
MillionIntegrals/vel
vel/util/tensor_accumulator.py
TensorAccumulator.result
def result(self): """ Concatenate accumulated tensors """ return {k: torch.stack(v) for k, v in self.accumulants.items()}
python
def result(self): """ Concatenate accumulated tensors """ return {k: torch.stack(v) for k, v in self.accumulants.items()}
[ "def", "result", "(", "self", ")", ":", "return", "{", "k", ":", "torch", ".", "stack", "(", "v", ")", "for", "k", ",", "v", "in", "self", ".", "accumulants", ".", "items", "(", ")", "}" ]
Concatenate accumulated tensors
[ "Concatenate", "accumulated", "tensors" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/tensor_accumulator.py#L14-L16
train
MillionIntegrals/vel
vel/internals/provider.py
Provider.resolve_parameters
def resolve_parameters(self, func, extra_env=None): """ Resolve parameter dictionary for the supplied function """ parameter_list = [ (k, v.default == inspect.Parameter.empty) for k, v in inspect.signature(func).parameters.items() ] extra_env = extra_env if extra_env is not N...
python
def resolve_parameters(self, func, extra_env=None): """ Resolve parameter dictionary for the supplied function """ parameter_list = [ (k, v.default == inspect.Parameter.empty) for k, v in inspect.signature(func).parameters.items() ] extra_env = extra_env if extra_env is not N...
[ "def", "resolve_parameters", "(", "self", ",", "func", ",", "extra_env", "=", "None", ")", ":", "parameter_list", "=", "[", "(", "k", ",", "v", ".", "default", "==", "inspect", ".", "Parameter", ".", "empty", ")", "for", "k", ",", "v", "in", "inspect...
Resolve parameter dictionary for the supplied function
[ "Resolve", "parameter", "dictionary", "for", "the", "supplied", "function" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L24-L52
train
MillionIntegrals/vel
vel/internals/provider.py
Provider.resolve_and_call
def resolve_and_call(self, func, extra_env=None): """ Resolve function arguments and call them, possibily filling from the environment """ kwargs = self.resolve_parameters(func, extra_env=extra_env) return func(**kwargs)
python
def resolve_and_call(self, func, extra_env=None): """ Resolve function arguments and call them, possibily filling from the environment """ kwargs = self.resolve_parameters(func, extra_env=extra_env) return func(**kwargs)
[ "def", "resolve_and_call", "(", "self", ",", "func", ",", "extra_env", "=", "None", ")", ":", "kwargs", "=", "self", ".", "resolve_parameters", "(", "func", ",", "extra_env", "=", "extra_env", ")", "return", "func", "(", "**", "kwargs", ")" ]
Resolve function arguments and call them, possibily filling from the environment
[ "Resolve", "function", "arguments", "and", "call", "them", "possibily", "filling", "from", "the", "environment" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L54-L57
train
MillionIntegrals/vel
vel/internals/provider.py
Provider.instantiate_from_data
def instantiate_from_data(self, object_data): """ Instantiate object from the supplied data, additional args may come from the environment """ if isinstance(object_data, dict) and 'name' in object_data: name = object_data['name'] module = importlib.import_module(name) ...
python
def instantiate_from_data(self, object_data): """ Instantiate object from the supplied data, additional args may come from the environment """ if isinstance(object_data, dict) and 'name' in object_data: name = object_data['name'] module = importlib.import_module(name) ...
[ "def", "instantiate_from_data", "(", "self", ",", "object_data", ")", ":", "if", "isinstance", "(", "object_data", ",", "dict", ")", "and", "'name'", "in", "object_data", ":", "name", "=", "object_data", "[", "'name'", "]", "module", "=", "importlib", ".", ...
Instantiate object from the supplied data, additional args may come from the environment
[ "Instantiate", "object", "from", "the", "supplied", "data", "additional", "args", "may", "come", "from", "the", "environment" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L59-L77
train
MillionIntegrals/vel
vel/internals/provider.py
Provider.render_configuration
def render_configuration(self, configuration=None): """ Render variables in configuration object but don't instantiate anything """ if configuration is None: configuration = self.environment if isinstance(configuration, dict): return {k: self.render_configuration(v) for ...
python
def render_configuration(self, configuration=None): """ Render variables in configuration object but don't instantiate anything """ if configuration is None: configuration = self.environment if isinstance(configuration, dict): return {k: self.render_configuration(v) for ...
[ "def", "render_configuration", "(", "self", ",", "configuration", "=", "None", ")", ":", "if", "configuration", "is", "None", ":", "configuration", "=", "self", ".", "environment", "if", "isinstance", "(", "configuration", ",", "dict", ")", ":", "return", "{...
Render variables in configuration object but don't instantiate anything
[ "Render", "variables", "in", "configuration", "object", "but", "don", "t", "instantiate", "anything" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L79-L91
train
MillionIntegrals/vel
vel/rl/api/evaluator.py
Evaluator.is_provided
def is_provided(self, name): """ Capability check if evaluator provides given value """ if name in self._storage: return True elif name in self._providers: return True elif name.startswith('rollout:'): rollout_name = name[8:] else: ...
python
def is_provided(self, name): """ Capability check if evaluator provides given value """ if name in self._storage: return True elif name in self._providers: return True elif name.startswith('rollout:'): rollout_name = name[8:] else: ...
[ "def", "is_provided", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_storage", ":", "return", "True", "elif", "name", "in", "self", ".", "_providers", ":", "return", "True", "elif", "name", ".", "startswith", "(", "'rollout:'", ...
Capability check if evaluator provides given value
[ "Capability", "check", "if", "evaluator", "provides", "given", "value" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/evaluator.py#L103-L112
train
MillionIntegrals/vel
vel/rl/api/evaluator.py
Evaluator.get
def get(self, name): """ Return a value from this evaluator. Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times with and without no_grad() context. It is advised in such cases to not use no_grad and stick to .detach() ...
python
def get(self, name): """ Return a value from this evaluator. Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times with and without no_grad() context. It is advised in such cases to not use no_grad and stick to .detach() ...
[ "def", "get", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_storage", ":", "return", "self", ".", "_storage", "[", "name", "]", "elif", "name", "in", "self", ".", "_providers", ":", "value", "=", "self", ".", "_storage", "[...
Return a value from this evaluator. Because tensor calculated is cached, it may lead to suble bugs if the same value is used multiple times with and without no_grad() context. It is advised in such cases to not use no_grad and stick to .detach()
[ "Return", "a", "value", "from", "this", "evaluator", "." ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/evaluator.py#L114-L133
train
MillionIntegrals/vel
vel/sources/vision/mnist.py
create
def create(model_config, batch_size, normalize=True, num_workers=0, augmentations=None): """ Create a MNIST dataset, normalized """ path = model_config.data_dir('mnist') train_dataset = datasets.MNIST(path, train=True, download=True) test_dataset = datasets.MNIST(path, train=False, download=True) ...
python
def create(model_config, batch_size, normalize=True, num_workers=0, augmentations=None): """ Create a MNIST dataset, normalized """ path = model_config.data_dir('mnist') train_dataset = datasets.MNIST(path, train=True, download=True) test_dataset = datasets.MNIST(path, train=False, download=True) ...
[ "def", "create", "(", "model_config", ",", "batch_size", ",", "normalize", "=", "True", ",", "num_workers", "=", "0", ",", "augmentations", "=", "None", ")", ":", "path", "=", "model_config", ".", "data_dir", "(", "'mnist'", ")", "train_dataset", "=", "dat...
Create a MNIST dataset, normalized
[ "Create", "a", "MNIST", "dataset", "normalized" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/vision/mnist.py#L11-L35
train
MillionIntegrals/vel
vel/storage/classic.py
ClassicStorage.reset
def reset(self, configuration: dict) -> None: """ Whenever there was anything stored in the database or not, purge previous state and start new training process from scratch. """ self.clean(0) self.backend.store_config(configuration)
python
def reset(self, configuration: dict) -> None: """ Whenever there was anything stored in the database or not, purge previous state and start new training process from scratch. """ self.clean(0) self.backend.store_config(configuration)
[ "def", "reset", "(", "self", ",", "configuration", ":", "dict", ")", "->", "None", ":", "self", ".", "clean", "(", "0", ")", "self", ".", "backend", ".", "store_config", "(", "configuration", ")" ]
Whenever there was anything stored in the database or not, purge previous state and start new training process from scratch.
[ "Whenever", "there", "was", "anything", "stored", "in", "the", "database", "or", "not", "purge", "previous", "state", "and", "start", "new", "training", "process", "from", "scratch", "." ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L26-L32
train
MillionIntegrals/vel
vel/storage/classic.py
ClassicStorage.load
def load(self, train_info: TrainingInfo) -> (dict, dict): """ Resume learning process and return loaded hidden state dictionary """ last_epoch = train_info.start_epoch_idx model_state = torch.load(self.checkpoint_filename(last_epoch)) hidden_state = torch.load(self.check...
python
def load(self, train_info: TrainingInfo) -> (dict, dict): """ Resume learning process and return loaded hidden state dictionary """ last_epoch = train_info.start_epoch_idx model_state = torch.load(self.checkpoint_filename(last_epoch)) hidden_state = torch.load(self.check...
[ "def", "load", "(", "self", ",", "train_info", ":", "TrainingInfo", ")", "->", "(", "dict", ",", "dict", ")", ":", "last_epoch", "=", "train_info", ".", "start_epoch_idx", "model_state", "=", "torch", ".", "load", "(", "self", ".", "checkpoint_filename", "...
Resume learning process and return loaded hidden state dictionary
[ "Resume", "learning", "process", "and", "return", "loaded", "hidden", "state", "dictionary" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L34-L46
train
MillionIntegrals/vel
vel/storage/classic.py
ClassicStorage.clean
def clean(self, global_epoch_idx): """ Clean old checkpoints """ if self.cleaned: return self.cleaned = True self.backend.clean(global_epoch_idx) self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.ma...
python
def clean(self, global_epoch_idx): """ Clean old checkpoints """ if self.cleaned: return self.cleaned = True self.backend.clean(global_epoch_idx) self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.ma...
[ "def", "clean", "(", "self", ",", "global_epoch_idx", ")", ":", "if", "self", ".", "cleaned", ":", "return", "self", ".", "cleaned", "=", "True", "self", ".", "backend", ".", "clean", "(", "global_epoch_idx", ")", "self", ".", "_make_sure_dir_exists", "(",...
Clean old checkpoints
[ "Clean", "old", "checkpoints" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L52-L85
train
MillionIntegrals/vel
vel/storage/classic.py
ClassicStorage.checkpoint
def checkpoint(self, epoch_info: EpochInfo, model: Model): """ When epoch is done, we persist the training state """ self.clean(epoch_info.global_epoch_idx - 1) self._make_sure_dir_exists() # Checkpoint latest torch.save(model.state_dict(), self.checkpoint_filename(epoch_info.g...
python
def checkpoint(self, epoch_info: EpochInfo, model: Model): """ When epoch is done, we persist the training state """ self.clean(epoch_info.global_epoch_idx - 1) self._make_sure_dir_exists() # Checkpoint latest torch.save(model.state_dict(), self.checkpoint_filename(epoch_info.g...
[ "def", "checkpoint", "(", "self", ",", "epoch_info", ":", "EpochInfo", ",", "model", ":", "Model", ")", ":", "self", ".", "clean", "(", "epoch_info", ".", "global_epoch_idx", "-", "1", ")", "self", ".", "_make_sure_dir_exists", "(", ")", "torch", ".", "s...
When epoch is done, we persist the training state
[ "When", "epoch", "is", "done", "we", "persist", "the", "training", "state" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L87-L118
train
MillionIntegrals/vel
vel/storage/classic.py
ClassicStorage._persisted_last_epoch
def _persisted_last_epoch(self) -> int: """ Return number of last epoch already calculated """ epoch_number = 0 self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.match('checkpoint_(\\d+)\\.data', x) if match: ...
python
def _persisted_last_epoch(self) -> int: """ Return number of last epoch already calculated """ epoch_number = 0 self._make_sure_dir_exists() for x in os.listdir(self.model_config.checkpoint_dir()): match = re.match('checkpoint_(\\d+)\\.data', x) if match: ...
[ "def", "_persisted_last_epoch", "(", "self", ")", "->", "int", ":", "epoch_number", "=", "0", "self", ".", "_make_sure_dir_exists", "(", ")", "for", "x", "in", "os", ".", "listdir", "(", "self", ".", "model_config", ".", "checkpoint_dir", "(", ")", ")", ...
Return number of last epoch already calculated
[ "Return", "number", "of", "last", "epoch", "already", "calculated" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L140-L153
train
MillionIntegrals/vel
vel/storage/classic.py
ClassicStorage._make_sure_dir_exists
def _make_sure_dir_exists(self): """ Make sure directory exists """ filename = self.model_config.checkpoint_dir() pathlib.Path(filename).mkdir(parents=True, exist_ok=True)
python
def _make_sure_dir_exists(self): """ Make sure directory exists """ filename = self.model_config.checkpoint_dir() pathlib.Path(filename).mkdir(parents=True, exist_ok=True)
[ "def", "_make_sure_dir_exists", "(", "self", ")", ":", "filename", "=", "self", ".", "model_config", ".", "checkpoint_dir", "(", ")", "pathlib", ".", "Path", "(", "filename", ")", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", "...
Make sure directory exists
[ "Make", "sure", "directory", "exists" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/classic.py#L155-L158
train
MillionIntegrals/vel
vel/rl/api/algo_base.py
clip_gradients
def clip_gradients(batch_result, model, max_grad_norm): """ Clip gradients to a given maximum length """ if max_grad_norm is not None: grad_norm = torch.nn.utils.clip_grad_norm_( filter(lambda p: p.requires_grad, model.parameters()), max_norm=max_grad_norm ) else: ...
python
def clip_gradients(batch_result, model, max_grad_norm): """ Clip gradients to a given maximum length """ if max_grad_norm is not None: grad_norm = torch.nn.utils.clip_grad_norm_( filter(lambda p: p.requires_grad, model.parameters()), max_norm=max_grad_norm ) else: ...
[ "def", "clip_gradients", "(", "batch_result", ",", "model", ",", "max_grad_norm", ")", ":", "if", "max_grad_norm", "is", "not", "None", ":", "grad_norm", "=", "torch", ".", "nn", ".", "utils", ".", "clip_grad_norm_", "(", "filter", "(", "lambda", "p", ":",...
Clip gradients to a given maximum length
[ "Clip", "gradients", "to", "a", "given", "maximum", "length" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/algo_base.py#L4-L14
train
MillionIntegrals/vel
vel/rl/buffers/circular_replay_buffer.py
CircularReplayBuffer.sample_trajectories
def sample_trajectories(self, rollout_length, batch_info) -> Trajectories: """ Sample batch of trajectories and return them """ indexes = self.backend.sample_batch_trajectories(rollout_length) transition_tensors = self.backend.get_trajectories(indexes, rollout_length) return Trajectorie...
python
def sample_trajectories(self, rollout_length, batch_info) -> Trajectories: """ Sample batch of trajectories and return them """ indexes = self.backend.sample_batch_trajectories(rollout_length) transition_tensors = self.backend.get_trajectories(indexes, rollout_length) return Trajectorie...
[ "def", "sample_trajectories", "(", "self", ",", "rollout_length", ",", "batch_info", ")", "->", "Trajectories", ":", "indexes", "=", "self", ".", "backend", ".", "sample_batch_trajectories", "(", "rollout_length", ")", "transition_tensors", "=", "self", ".", "back...
Sample batch of trajectories and return them
[ "Sample", "batch", "of", "trajectories", "and", "return", "them" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/circular_replay_buffer.py#L52-L63
train
MillionIntegrals/vel
vel/rl/algo/policy_gradient/trpo.py
conjugate_gradient_method
def conjugate_gradient_method(matrix_vector_operator, loss_gradient, nsteps, rdotr_tol=1e-10): """ Conjugate gradient algorithm """ x = torch.zeros_like(loss_gradient) r = loss_gradient.clone() p = loss_gradient.clone() rdotr = torch.dot(r, r) for i in range(nsteps): Avp = matrix_vect...
python
def conjugate_gradient_method(matrix_vector_operator, loss_gradient, nsteps, rdotr_tol=1e-10): """ Conjugate gradient algorithm """ x = torch.zeros_like(loss_gradient) r = loss_gradient.clone() p = loss_gradient.clone() rdotr = torch.dot(r, r) for i in range(nsteps): Avp = matrix_vect...
[ "def", "conjugate_gradient_method", "(", "matrix_vector_operator", ",", "loss_gradient", ",", "nsteps", ",", "rdotr_tol", "=", "1e-10", ")", ":", "x", "=", "torch", ".", "zeros_like", "(", "loss_gradient", ")", "r", "=", "loss_gradient", ".", "clone", "(", ")"...
Conjugate gradient algorithm
[ "Conjugate", "gradient", "algorithm" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L23-L47
train
MillionIntegrals/vel
vel/rl/algo/policy_gradient/trpo.py
TrpoPolicyGradient.line_search
def line_search(self, model, rollout, original_policy_loss, original_policy_params, original_parameter_vec, full_step, expected_improvement_full): """ Find the right stepsize to make sure policy improves """ current_parameter_vec = original_parameter_vec.clone() for idx in r...
python
def line_search(self, model, rollout, original_policy_loss, original_policy_params, original_parameter_vec, full_step, expected_improvement_full): """ Find the right stepsize to make sure policy improves """ current_parameter_vec = original_parameter_vec.clone() for idx in r...
[ "def", "line_search", "(", "self", ",", "model", ",", "rollout", ",", "original_policy_loss", ",", "original_policy_params", ",", "original_parameter_vec", ",", "full_step", ",", "expected_improvement_full", ")", ":", "current_parameter_vec", "=", "original_parameter_vec"...
Find the right stepsize to make sure policy improves
[ "Find", "the", "right", "stepsize", "to", "make", "sure", "policy", "improves" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L167-L205
train
MillionIntegrals/vel
vel/rl/algo/policy_gradient/trpo.py
TrpoPolicyGradient.fisher_vector_product
def fisher_vector_product(self, vector, kl_divergence_gradient, model): """ Calculate product Hessian @ vector """ assert not vector.requires_grad, "Vector must not propagate gradient" dot_product = vector @ kl_divergence_gradient # at least one dimension spans across two contiguous sub...
python
def fisher_vector_product(self, vector, kl_divergence_gradient, model): """ Calculate product Hessian @ vector """ assert not vector.requires_grad, "Vector must not propagate gradient" dot_product = vector @ kl_divergence_gradient # at least one dimension spans across two contiguous sub...
[ "def", "fisher_vector_product", "(", "self", ",", "vector", ",", "kl_divergence_gradient", ",", "model", ")", ":", "assert", "not", "vector", ".", "requires_grad", ",", "\"Vector must not propagate gradient\"", "dot_product", "=", "vector", "@", "kl_divergence_gradient"...
Calculate product Hessian @ vector
[ "Calculate", "product", "Hessian" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L207-L216
train
MillionIntegrals/vel
vel/rl/algo/policy_gradient/trpo.py
TrpoPolicyGradient.value_loss
def value_loss(self, model, observations, discounted_rewards): """ Loss of value estimator """ value_outputs = model.value(observations) value_loss = 0.5 * F.mse_loss(value_outputs, discounted_rewards) return value_loss
python
def value_loss(self, model, observations, discounted_rewards): """ Loss of value estimator """ value_outputs = model.value(observations) value_loss = 0.5 * F.mse_loss(value_outputs, discounted_rewards) return value_loss
[ "def", "value_loss", "(", "self", ",", "model", ",", "observations", ",", "discounted_rewards", ")", ":", "value_outputs", "=", "model", ".", "value", "(", "observations", ")", "value_loss", "=", "0.5", "*", "F", ".", "mse_loss", "(", "value_outputs", ",", ...
Loss of value estimator
[ "Loss", "of", "value", "estimator" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L218-L222
train
MillionIntegrals/vel
vel/rl/algo/policy_gradient/trpo.py
TrpoPolicyGradient.calc_policy_loss
def calc_policy_loss(self, model, policy_params, policy_entropy, rollout): """ Policy gradient loss - calculate from probability distribution Calculate surrogate loss - advantage * policy_probability / fixed_initial_policy_probability Because we operate with logarithm of -probability (...
python
def calc_policy_loss(self, model, policy_params, policy_entropy, rollout): """ Policy gradient loss - calculate from probability distribution Calculate surrogate loss - advantage * policy_probability / fixed_initial_policy_probability Because we operate with logarithm of -probability (...
[ "def", "calc_policy_loss", "(", "self", ",", "model", ",", "policy_params", ",", "policy_entropy", ",", "rollout", ")", ":", "actions", "=", "rollout", ".", "batch_tensor", "(", "'actions'", ")", "advantages", "=", "rollout", ".", "batch_tensor", "(", "'advant...
Policy gradient loss - calculate from probability distribution Calculate surrogate loss - advantage * policy_probability / fixed_initial_policy_probability Because we operate with logarithm of -probability (neglogp) we do - advantage * exp(fixed_neglogps - model_neglogps)
[ "Policy", "gradient", "loss", "-", "calculate", "from", "probability", "distribution" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L224-L245
train
MillionIntegrals/vel
vel/rl/api/rollout.py
Transitions.shuffled_batches
def shuffled_batches(self, batch_size): """ Generate randomized batches of data """ if batch_size >= self.size: yield self else: batch_splits = math_util.divide_ceiling(self.size, batch_size) indices = list(range(self.size)) np.random.shuffle(indic...
python
def shuffled_batches(self, batch_size): """ Generate randomized batches of data """ if batch_size >= self.size: yield self else: batch_splits = math_util.divide_ceiling(self.size, batch_size) indices = list(range(self.size)) np.random.shuffle(indic...
[ "def", "shuffled_batches", "(", "self", ",", "batch_size", ")", ":", "if", "batch_size", ">=", "self", ".", "size", ":", "yield", "self", "else", ":", "batch_splits", "=", "math_util", ".", "divide_ceiling", "(", "self", ".", "size", ",", "batch_size", ")"...
Generate randomized batches of data
[ "Generate", "randomized", "batches", "of", "data" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L59-L76
train
MillionIntegrals/vel
vel/rl/api/rollout.py
Trajectories.to_transitions
def to_transitions(self) -> 'Transitions': """ Convert given rollout to Transitions """ # No need to propagate 'rollout_tensors' as they won't mean anything return Transitions( size=self.num_steps * self.num_envs, environment_information= [ei for l in self...
python
def to_transitions(self) -> 'Transitions': """ Convert given rollout to Transitions """ # No need to propagate 'rollout_tensors' as they won't mean anything return Transitions( size=self.num_steps * self.num_envs, environment_information= [ei for l in self...
[ "def", "to_transitions", "(", "self", ")", "->", "'Transitions'", ":", "return", "Transitions", "(", "size", "=", "self", ".", "num_steps", "*", "self", ".", "num_envs", ",", "environment_information", "=", "[", "ei", "for", "l", "in", "self", ".", "enviro...
Convert given rollout to Transitions
[ "Convert", "given", "rollout", "to", "Transitions" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L111-L123
train
MillionIntegrals/vel
vel/rl/api/rollout.py
Trajectories.shuffled_batches
def shuffled_batches(self, batch_size): """ Generate randomized batches of data - only sample whole trajectories """ if batch_size >= self.num_envs * self.num_steps: yield self else: rollouts_in_batch = batch_size // self.num_steps batch_splits = math_util.di...
python
def shuffled_batches(self, batch_size): """ Generate randomized batches of data - only sample whole trajectories """ if batch_size >= self.num_envs * self.num_steps: yield self else: rollouts_in_batch = batch_size // self.num_steps batch_splits = math_util.di...
[ "def", "shuffled_batches", "(", "self", ",", "batch_size", ")", ":", "if", "batch_size", ">=", "self", ".", "num_envs", "*", "self", ".", "num_steps", ":", "yield", "self", "else", ":", "rollouts_in_batch", "=", "batch_size", "//", "self", ".", "num_steps", ...
Generate randomized batches of data - only sample whole trajectories
[ "Generate", "randomized", "batches", "of", "data", "-", "only", "sample", "whole", "trajectories" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L125-L147
train
MillionIntegrals/vel
vel/rl/api/rollout.py
Trajectories.episode_information
def episode_information(self): """ List of information about finished episodes """ return [ info.get('episode') for infolist in self.environment_information for info in infolist if 'episode' in info ]
python
def episode_information(self): """ List of information about finished episodes """ return [ info.get('episode') for infolist in self.environment_information for info in infolist if 'episode' in info ]
[ "def", "episode_information", "(", "self", ")", ":", "return", "[", "info", ".", "get", "(", "'episode'", ")", "for", "infolist", "in", "self", ".", "environment_information", "for", "info", "in", "infolist", "if", "'episode'", "in", "info", "]" ]
List of information about finished episodes
[ "List", "of", "information", "about", "finished", "episodes" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/rollout.py#L164-L168
train
MillionIntegrals/vel
vel/models/rnn/multilayer_rnn_sequence_model.py
MultilayerRnnSequenceModel.forward_state
def forward_state(self, sequence, state=None): """ Forward propagate a sequence through the network accounting for the state """ if state is None: state = self.zero_state(sequence.size(0)) data = self.input_block(sequence) state_outputs = [] # for layer_length, lay...
python
def forward_state(self, sequence, state=None): """ Forward propagate a sequence through the network accounting for the state """ if state is None: state = self.zero_state(sequence.size(0)) data = self.input_block(sequence) state_outputs = [] # for layer_length, lay...
[ "def", "forward_state", "(", "self", ",", "sequence", ",", "state", "=", "None", ")", ":", "if", "state", "is", "None", ":", "state", "=", "self", ".", "zero_state", "(", "sequence", ".", "size", "(", "0", ")", ")", "data", "=", "self", ".", "input...
Forward propagate a sequence through the network accounting for the state
[ "Forward", "propagate", "a", "sequence", "through", "the", "network", "accounting", "for", "the", "state" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/rnn/multilayer_rnn_sequence_model.py#L66-L95
train
MillionIntegrals/vel
vel/models/rnn/multilayer_rnn_sequence_model.py
MultilayerRnnSequenceModel.loss_value
def loss_value(self, x_data, y_true, y_pred): """ Calculate a value of loss function """ y_pred = y_pred.view(-1, y_pred.size(2)) y_true = y_true.view(-1).to(torch.long) return F.nll_loss(y_pred, y_true)
python
def loss_value(self, x_data, y_true, y_pred): """ Calculate a value of loss function """ y_pred = y_pred.view(-1, y_pred.size(2)) y_true = y_true.view(-1).to(torch.long) return F.nll_loss(y_pred, y_true)
[ "def", "loss_value", "(", "self", ",", "x_data", ",", "y_true", ",", "y_pred", ")", ":", "y_pred", "=", "y_pred", ".", "view", "(", "-", "1", ",", "y_pred", ".", "size", "(", "2", ")", ")", "y_true", "=", "y_true", ".", "view", "(", "-", "1", "...
Calculate a value of loss function
[ "Calculate", "a", "value", "of", "loss", "function" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/rnn/multilayer_rnn_sequence_model.py#L106-L110
train
MillionIntegrals/vel
vel/api/learner.py
Learner.initialize_training
def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None): """ Prepare for training """ if model_state is None: self.model.reset_weights() else: self.model.load_state_dict(model_state)
python
def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None): """ Prepare for training """ if model_state is None: self.model.reset_weights() else: self.model.load_state_dict(model_state)
[ "def", "initialize_training", "(", "self", ",", "training_info", ":", "TrainingInfo", ",", "model_state", "=", "None", ",", "hidden_state", "=", "None", ")", ":", "if", "model_state", "is", "None", ":", "self", ".", "model", ".", "reset_weights", "(", ")", ...
Prepare for training
[ "Prepare", "for", "training" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L36-L41
train
MillionIntegrals/vel
vel/api/learner.py
Learner.run_epoch
def run_epoch(self, epoch_info: EpochInfo, source: 'vel.api.Source'): """ Run full epoch of learning """ epoch_info.on_epoch_begin() lr = epoch_info.optimizer.param_groups[-1]['lr'] print("|-------- Epoch {:06} Lr={:.6f} ----------|".format(epoch_info.global_epoch_idx, lr)) sel...
python
def run_epoch(self, epoch_info: EpochInfo, source: 'vel.api.Source'): """ Run full epoch of learning """ epoch_info.on_epoch_begin() lr = epoch_info.optimizer.param_groups[-1]['lr'] print("|-------- Epoch {:06} Lr={:.6f} ----------|".format(epoch_info.global_epoch_idx, lr)) sel...
[ "def", "run_epoch", "(", "self", ",", "epoch_info", ":", "EpochInfo", ",", "source", ":", "'vel.api.Source'", ")", ":", "epoch_info", ".", "on_epoch_begin", "(", ")", "lr", "=", "epoch_info", ".", "optimizer", ".", "param_groups", "[", "-", "1", "]", "[", ...
Run full epoch of learning
[ "Run", "full", "epoch", "of", "learning" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L43-L56
train
MillionIntegrals/vel
vel/api/learner.py
Learner.train_epoch
def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True): """ Run a single training epoch """ self.train() if interactive: iterator = tqdm.tqdm(source.train_loader(), desc="Training", unit="iter", file=sys.stdout) else: iterator = source.trai...
python
def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True): """ Run a single training epoch """ self.train() if interactive: iterator = tqdm.tqdm(source.train_loader(), desc="Training", unit="iter", file=sys.stdout) else: iterator = source.trai...
[ "def", "train_epoch", "(", "self", ",", "epoch_info", ",", "source", ":", "'vel.api.Source'", ",", "interactive", "=", "True", ")", ":", "self", ".", "train", "(", ")", "if", "interactive", ":", "iterator", "=", "tqdm", ".", "tqdm", "(", "source", ".", ...
Run a single training epoch
[ "Run", "a", "single", "training", "epoch" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L58-L74
train
MillionIntegrals/vel
vel/api/learner.py
Learner.validation_epoch
def validation_epoch(self, epoch_info, source: 'vel.api.Source'): """ Run a single evaluation epoch """ self.eval() iterator = tqdm.tqdm(source.val_loader(), desc="Validation", unit="iter", file=sys.stdout) with torch.no_grad(): for batch_idx, (data, target) in enumerate(it...
python
def validation_epoch(self, epoch_info, source: 'vel.api.Source'): """ Run a single evaluation epoch """ self.eval() iterator = tqdm.tqdm(source.val_loader(), desc="Validation", unit="iter", file=sys.stdout) with torch.no_grad(): for batch_idx, (data, target) in enumerate(it...
[ "def", "validation_epoch", "(", "self", ",", "epoch_info", ",", "source", ":", "'vel.api.Source'", ")", ":", "self", ".", "eval", "(", ")", "iterator", "=", "tqdm", ".", "tqdm", "(", "source", ".", "val_loader", "(", ")", ",", "desc", "=", "\"Validation\...
Run a single evaluation epoch
[ "Run", "a", "single", "evaluation", "epoch" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L76-L88
train
MillionIntegrals/vel
vel/api/learner.py
Learner.feed_batch
def feed_batch(self, batch_info, data, target): """ Run single batch of data """ data, target = data.to(self.device), target.to(self.device) output, loss = self.model.loss(data, target) # Store extra batch information for calculation of the statistics batch_info['data'] = data ...
python
def feed_batch(self, batch_info, data, target): """ Run single batch of data """ data, target = data.to(self.device), target.to(self.device) output, loss = self.model.loss(data, target) # Store extra batch information for calculation of the statistics batch_info['data'] = data ...
[ "def", "feed_batch", "(", "self", ",", "batch_info", ",", "data", ",", "target", ")", ":", "data", ",", "target", "=", "data", ".", "to", "(", "self", ".", "device", ")", ",", "target", ".", "to", "(", "self", ".", "device", ")", "output", ",", "...
Run single batch of data
[ "Run", "single", "batch", "of", "data" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L90-L101
train
MillionIntegrals/vel
vel/api/learner.py
Learner.train_batch
def train_batch(self, batch_info, data, target): """ Train single batch of data """ batch_info.optimizer.zero_grad() loss = self.feed_batch(batch_info, data, target) loss.backward() if self.max_grad_norm is not None: batch_info['grad_norm'] = torch.nn.utils.clip_grad...
python
def train_batch(self, batch_info, data, target): """ Train single batch of data """ batch_info.optimizer.zero_grad() loss = self.feed_batch(batch_info, data, target) loss.backward() if self.max_grad_norm is not None: batch_info['grad_norm'] = torch.nn.utils.clip_grad...
[ "def", "train_batch", "(", "self", ",", "batch_info", ",", "data", ",", "target", ")", ":", "batch_info", ".", "optimizer", ".", "zero_grad", "(", ")", "loss", "=", "self", ".", "feed_batch", "(", "batch_info", ",", "data", ",", "target", ")", "loss", ...
Train single batch of data
[ "Train", "single", "batch", "of", "data" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/learner.py#L103-L115
train
MillionIntegrals/vel
vel/util/situational.py
process_environment_settings
def process_environment_settings(default_dictionary: dict, settings: typing.Optional[dict]=None, presets: typing.Optional[dict]=None): """ Process a dictionary of env settings """ settings = settings if settings is not None else {} presets = presets if presets is not None el...
python
def process_environment_settings(default_dictionary: dict, settings: typing.Optional[dict]=None, presets: typing.Optional[dict]=None): """ Process a dictionary of env settings """ settings = settings if settings is not None else {} presets = presets if presets is not None el...
[ "def", "process_environment_settings", "(", "default_dictionary", ":", "dict", ",", "settings", ":", "typing", ".", "Optional", "[", "dict", "]", "=", "None", ",", "presets", ":", "typing", ".", "Optional", "[", "dict", "]", "=", "None", ")", ":", "setting...
Process a dictionary of env settings
[ "Process", "a", "dictionary", "of", "env", "settings" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/situational.py#L4-L27
train
MillionIntegrals/vel
vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py
BufferedOffPolicyIterationReinforcer.roll_out_and_store
def roll_out_and_store(self, batch_info): """ Roll out environment and store result in the replay buffer """ self.model.train() if self.env_roller.is_ready_for_sampling(): rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device) ...
python
def roll_out_and_store(self, batch_info): """ Roll out environment and store result in the replay buffer """ self.model.train() if self.env_roller.is_ready_for_sampling(): rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device) ...
[ "def", "roll_out_and_store", "(", "self", ",", "batch_info", ")", ":", "self", ".", "model", ".", "train", "(", ")", "if", "self", ".", "env_roller", ".", "is_ready_for_sampling", "(", ")", ":", "rollout", "=", "self", ".", "env_roller", ".", "rollout", ...
Roll out environment and store result in the replay buffer
[ "Roll", "out", "environment", "and", "store", "result", "in", "the", "replay", "buffer" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py#L109-L135
train
MillionIntegrals/vel
vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py
BufferedOffPolicyIterationReinforcer.train_on_replay_memory
def train_on_replay_memory(self, batch_info): """ Train agent on a memory gotten from replay buffer """ self.model.train() # Algo will aggregate data into this list: batch_info['sub_batch_data'] = [] for i in range(self.settings.training_rounds): sampled_rollout = s...
python
def train_on_replay_memory(self, batch_info): """ Train agent on a memory gotten from replay buffer """ self.model.train() # Algo will aggregate data into this list: batch_info['sub_batch_data'] = [] for i in range(self.settings.training_rounds): sampled_rollout = s...
[ "def", "train_on_replay_memory", "(", "self", ",", "batch_info", ")", ":", "self", ".", "model", ".", "train", "(", ")", "batch_info", "[", "'sub_batch_data'", "]", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "settings", ".", "training_ro...
Train agent on a memory gotten from replay buffer
[ "Train", "agent", "on", "a", "memory", "gotten", "from", "replay", "buffer" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py#L137-L158
train
MillionIntegrals/vel
vel/modules/resnet_v1.py
conv3x3
def conv3x3(in_channels, out_channels, stride=1): """ 3x3 convolution with padding. Original code has had bias turned off, because Batch Norm would remove the bias either way """ return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
python
def conv3x3(in_channels, out_channels, stride=1): """ 3x3 convolution with padding. Original code has had bias turned off, because Batch Norm would remove the bias either way """ return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
[ "def", "conv3x3", "(", "in_channels", ",", "out_channels", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_channels", ",", "out_channels", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ...
3x3 convolution with padding. Original code has had bias turned off, because Batch Norm would remove the bias either way
[ "3x3", "convolution", "with", "padding", ".", "Original", "code", "has", "had", "bias", "turned", "off", "because", "Batch", "Norm", "would", "remove", "the", "bias", "either", "way" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/modules/resnet_v1.py#L10-L15
train
MillionIntegrals/vel
vel/notebook/loader.py
load
def load(config_path, run_number=0, device='cuda:0'): """ Load a ModelConfig from filename """ model_config = ModelConfig.from_file(config_path, run_number, device=device) return model_config
python
def load(config_path, run_number=0, device='cuda:0'): """ Load a ModelConfig from filename """ model_config = ModelConfig.from_file(config_path, run_number, device=device) return model_config
[ "def", "load", "(", "config_path", ",", "run_number", "=", "0", ",", "device", "=", "'cuda:0'", ")", ":", "model_config", "=", "ModelConfig", ".", "from_file", "(", "config_path", ",", "run_number", ",", "device", "=", "device", ")", "return", "model_config"...
Load a ModelConfig from filename
[ "Load", "a", "ModelConfig", "from", "filename" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/notebook/loader.py#L4-L8
train
MillionIntegrals/vel
vel/api/info.py
TrainingInfo.restore
def restore(self, hidden_state): """ Restore any state from checkpoint - currently not implemented but possible to do so in the future """ for callback in self.callbacks: callback.load_state_dict(self, hidden_state) if 'optimizer' in hidden_state: self.optimizer_initial_...
python
def restore(self, hidden_state): """ Restore any state from checkpoint - currently not implemented but possible to do so in the future """ for callback in self.callbacks: callback.load_state_dict(self, hidden_state) if 'optimizer' in hidden_state: self.optimizer_initial_...
[ "def", "restore", "(", "self", ",", "hidden_state", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "callback", ".", "load_state_dict", "(", "self", ",", "hidden_state", ")", "if", "'optimizer'", "in", "hidden_state", ":", "self", ".", "o...
Restore any state from checkpoint - currently not implemented but possible to do so in the future
[ "Restore", "any", "state", "from", "checkpoint", "-", "currently", "not", "implemented", "but", "possible", "to", "do", "so", "in", "the", "future" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L47-L53
train
MillionIntegrals/vel
vel/api/info.py
EpochResultAccumulator.result
def result(self): """ Return the epoch result """ final_result = {'epoch_idx': self.global_epoch_idx} for key, value in self.frozen_results.items(): final_result[key] = value return final_result
python
def result(self): """ Return the epoch result """ final_result = {'epoch_idx': self.global_epoch_idx} for key, value in self.frozen_results.items(): final_result[key] = value return final_result
[ "def", "result", "(", "self", ")", ":", "final_result", "=", "{", "'epoch_idx'", ":", "self", ".", "global_epoch_idx", "}", "for", "key", ",", "value", "in", "self", ".", "frozen_results", ".", "items", "(", ")", ":", "final_result", "[", "key", "]", "...
Return the epoch result
[ "Return", "the", "epoch", "result" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L144-L151
train
MillionIntegrals/vel
vel/api/info.py
EpochInfo.state_dict
def state_dict(self) -> dict: """ Calculate hidden state dictionary """ hidden_state = {} if self.optimizer is not None: hidden_state['optimizer'] = self.optimizer.state_dict() for callback in self.callbacks: callback.write_state_dict(self.training_info, hidden_...
python
def state_dict(self) -> dict: """ Calculate hidden state dictionary """ hidden_state = {} if self.optimizer is not None: hidden_state['optimizer'] = self.optimizer.state_dict() for callback in self.callbacks: callback.write_state_dict(self.training_info, hidden_...
[ "def", "state_dict", "(", "self", ")", "->", "dict", ":", "hidden_state", "=", "{", "}", "if", "self", ".", "optimizer", "is", "not", "None", ":", "hidden_state", "[", "'optimizer'", "]", "=", "self", ".", "optimizer", ".", "state_dict", "(", ")", "for...
Calculate hidden state dictionary
[ "Calculate", "hidden", "state", "dictionary" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L186-L196
train
MillionIntegrals/vel
vel/api/info.py
EpochInfo.on_epoch_end
def on_epoch_end(self): """ Finish epoch processing """ self.freeze_epoch_result() for callback in self.callbacks: callback.on_epoch_end(self) self.training_info.history.add(self.result)
python
def on_epoch_end(self): """ Finish epoch processing """ self.freeze_epoch_result() for callback in self.callbacks: callback.on_epoch_end(self) self.training_info.history.add(self.result)
[ "def", "on_epoch_end", "(", "self", ")", ":", "self", ".", "freeze_epoch_result", "(", ")", "for", "callback", "in", "self", ".", "callbacks", ":", "callback", ".", "on_epoch_end", "(", "self", ")", "self", ".", "training_info", ".", "history", ".", "add",...
Finish epoch processing
[ "Finish", "epoch", "processing" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L203-L210
train
MillionIntegrals/vel
vel/api/info.py
BatchInfo.aggregate_key
def aggregate_key(self, aggregate_key): """ Aggregate values from key and put them into the top-level dictionary """ aggregation = self.data_dict[aggregate_key] # List of dictionaries of numpy arrays/scalars # Aggregate sub batch data data_dict_keys = {y for x in aggregation for y in x...
python
def aggregate_key(self, aggregate_key): """ Aggregate values from key and put them into the top-level dictionary """ aggregation = self.data_dict[aggregate_key] # List of dictionaries of numpy arrays/scalars # Aggregate sub batch data data_dict_keys = {y for x in aggregation for y in x...
[ "def", "aggregate_key", "(", "self", ",", "aggregate_key", ")", ":", "aggregation", "=", "self", ".", "data_dict", "[", "aggregate_key", "]", "data_dict_keys", "=", "{", "y", "for", "x", "in", "aggregation", "for", "y", "in", "x", ".", "keys", "(", ")", ...
Aggregate values from key and put them into the top-level dictionary
[ "Aggregate", "values", "from", "key", "and", "put", "them", "into", "the", "top", "-", "level", "dictionary" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/info.py#L316-L326
train
MillionIntegrals/vel
vel/rl/commands/rl_train_command.py
RlTrainCommand.run
def run(self): """ Run reinforcement learning algorithm """ device = self.model_config.torch_device() # Reinforcer is the learner for the reinforcement learning model reinforcer = self.reinforcer.instantiate(device) optimizer = self.optimizer_factory.instantiate(reinforcer.model...
python
def run(self): """ Run reinforcement learning algorithm """ device = self.model_config.torch_device() # Reinforcer is the learner for the reinforcement learning model reinforcer = self.reinforcer.instantiate(device) optimizer = self.optimizer_factory.instantiate(reinforcer.model...
[ "def", "run", "(", "self", ")", ":", "device", "=", "self", ".", "model_config", ".", "torch_device", "(", ")", "reinforcer", "=", "self", ".", "reinforcer", ".", "instantiate", "(", "device", ")", "optimizer", "=", "self", ".", "optimizer_factory", ".", ...
Run reinforcement learning algorithm
[ "Run", "reinforcement", "learning", "algorithm" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L62-L104
train
MillionIntegrals/vel
vel/rl/commands/rl_train_command.py
RlTrainCommand.resume_training
def resume_training(self, reinforcer, callbacks, metrics) -> TrainingInfo: """ Possibly resume training from a saved state from the storage """ if self.model_config.continue_training: start_epoch = self.storage.last_epoch_idx() else: start_epoch = 0 training_info...
python
def resume_training(self, reinforcer, callbacks, metrics) -> TrainingInfo: """ Possibly resume training from a saved state from the storage """ if self.model_config.continue_training: start_epoch = self.storage.last_epoch_idx() else: start_epoch = 0 training_info...
[ "def", "resume_training", "(", "self", ",", "reinforcer", ",", "callbacks", ",", "metrics", ")", "->", "TrainingInfo", ":", "if", "self", ".", "model_config", ".", "continue_training", ":", "start_epoch", "=", "self", ".", "storage", ".", "last_epoch_idx", "("...
Possibly resume training from a saved state from the storage
[ "Possibly", "resume", "training", "from", "a", "saved", "state", "from", "the", "storage" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L118-L139
train
MillionIntegrals/vel
vel/rl/commands/rl_train_command.py
RlTrainCommand._openai_logging
def _openai_logging(self, epoch_result): """ Use OpenAI logging facilities for the same type of logging """ for key in sorted(epoch_result.keys()): if key == 'fps': # Not super elegant, but I like nicer display of FPS openai_logger.record_tabular(key, int(epoc...
python
def _openai_logging(self, epoch_result): """ Use OpenAI logging facilities for the same type of logging """ for key in sorted(epoch_result.keys()): if key == 'fps': # Not super elegant, but I like nicer display of FPS openai_logger.record_tabular(key, int(epoc...
[ "def", "_openai_logging", "(", "self", ",", "epoch_result", ")", ":", "for", "key", "in", "sorted", "(", "epoch_result", ".", "keys", "(", ")", ")", ":", "if", "key", "==", "'fps'", ":", "openai_logger", ".", "record_tabular", "(", "key", ",", "int", "...
Use OpenAI logging facilities for the same type of logging
[ "Use", "OpenAI", "logging", "facilities", "for", "the", "same", "type", "of", "logging" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/rl_train_command.py#L141-L150
train
MillionIntegrals/vel
vel/util/module_util.py
module_broadcast
def module_broadcast(m, broadcast_fn, *args, **kwargs): """ Call given function in all submodules with given parameters """ apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs))
python
def module_broadcast(m, broadcast_fn, *args, **kwargs): """ Call given function in all submodules with given parameters """ apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs))
[ "def", "module_broadcast", "(", "m", ",", "broadcast_fn", ",", "*", "args", ",", "**", "kwargs", ")", ":", "apply_leaf", "(", "m", ",", "lambda", "x", ":", "module_apply_broadcast", "(", "x", ",", "broadcast_fn", ",", "args", ",", "kwargs", ")", ")" ]
Call given function in all submodules with given parameters
[ "Call", "given", "function", "in", "all", "submodules", "with", "given", "parameters" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/module_util.py#L34-L36
train
MillionIntegrals/vel
vel/commands/phase_train_command.py
PhaseTrainCommand._select_phase_left_bound
def _select_phase_left_bound(self, epoch_number): """ Return number of current phase. Return index of first phase not done after all up to epoch_number were done. """ idx = bisect.bisect_left(self.ladder, epoch_number) if idx >= len(self.ladder): return len(s...
python
def _select_phase_left_bound(self, epoch_number): """ Return number of current phase. Return index of first phase not done after all up to epoch_number were done. """ idx = bisect.bisect_left(self.ladder, epoch_number) if idx >= len(self.ladder): return len(s...
[ "def", "_select_phase_left_bound", "(", "self", ",", "epoch_number", ")", ":", "idx", "=", "bisect", ".", "bisect_left", "(", "self", ".", "ladder", ",", "epoch_number", ")", "if", "idx", ">=", "len", "(", "self", ".", "ladder", ")", ":", "return", "len"...
Return number of current phase. Return index of first phase not done after all up to epoch_number were done.
[ "Return", "number", "of", "current", "phase", ".", "Return", "index", "of", "first", "phase", "not", "done", "after", "all", "up", "to", "epoch_number", "were", "done", "." ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/phase_train_command.py#L29-L41
train
MillionIntegrals/vel
vel/rl/env/classic_atari.py
wrapped_env_maker
def wrapped_env_maker(environment_id, seed, serial_id, disable_reward_clipping=False, disable_episodic_life=False, monitor=False, allow_early_resets=False, scale_float_frames=False, max_episode_frames=10000, frame_stack=None): """ Wrap atari environment so that it's nicer...
python
def wrapped_env_maker(environment_id, seed, serial_id, disable_reward_clipping=False, disable_episodic_life=False, monitor=False, allow_early_resets=False, scale_float_frames=False, max_episode_frames=10000, frame_stack=None): """ Wrap atari environment so that it's nicer...
[ "def", "wrapped_env_maker", "(", "environment_id", ",", "seed", ",", "serial_id", ",", "disable_reward_clipping", "=", "False", ",", "disable_episodic_life", "=", "False", ",", "monitor", "=", "False", ",", "allow_early_resets", "=", "False", ",", "scale_float_frame...
Wrap atari environment so that it's nicer to learn RL algorithms
[ "Wrap", "atari", "environment", "so", "that", "it", "s", "nicer", "to", "learn", "RL", "algorithms" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_atari.py#L55-L98
train
MillionIntegrals/vel
vel/rl/env/classic_atari.py
ClassicAtariEnv.instantiate
def instantiate(self, seed=0, serial_id=0, preset='default', extra_args=None) -> gym.Env: """ Make a single environment compatible with the experiments """ settings = self.get_preset(preset) return wrapped_env_maker(self.envname, seed, serial_id, **settings)
python
def instantiate(self, seed=0, serial_id=0, preset='default', extra_args=None) -> gym.Env: """ Make a single environment compatible with the experiments """ settings = self.get_preset(preset) return wrapped_env_maker(self.envname, seed, serial_id, **settings)
[ "def", "instantiate", "(", "self", ",", "seed", "=", "0", ",", "serial_id", "=", "0", ",", "preset", "=", "'default'", ",", "extra_args", "=", "None", ")", "->", "gym", ".", "Env", ":", "settings", "=", "self", ".", "get_preset", "(", "preset", ")", ...
Make a single environment compatible with the experiments
[ "Make", "a", "single", "environment", "compatible", "with", "the", "experiments" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_atari.py#L115-L118
train
MillionIntegrals/vel
vel/util/visdom.py
visdom_send_metrics
def visdom_send_metrics(vis, metrics, update='replace'): """ Send set of metrics to visdom """ visited = {} sorted_metrics = sorted(metrics.columns, key=_column_original_name) for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name): metric_list = list(metric_li...
python
def visdom_send_metrics(vis, metrics, update='replace'): """ Send set of metrics to visdom """ visited = {} sorted_metrics = sorted(metrics.columns, key=_column_original_name) for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name): metric_list = list(metric_li...
[ "def", "visdom_send_metrics", "(", "vis", ",", "metrics", ",", "update", "=", "'replace'", ")", ":", "visited", "=", "{", "}", "sorted_metrics", "=", "sorted", "(", "metrics", ".", "columns", ",", "key", "=", "_column_original_name", ")", "for", "metric_base...
Send set of metrics to visdom
[ "Send", "set", "of", "metrics", "to", "visdom" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/visdom.py#L27-L71
train
MillionIntegrals/vel
vel/api/train_phase.py
TrainPhase.restore
def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict): """ Restore learning from intermediate state. """ pass
python
def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict): """ Restore learning from intermediate state. """ pass
[ "def", "restore", "(", "self", ",", "training_info", ":", "TrainingInfo", ",", "local_batch_idx", ":", "int", ",", "model", ":", "Model", ",", "hidden_state", ":", "dict", ")", ":", "pass" ]
Restore learning from intermediate state.
[ "Restore", "learning", "from", "intermediate", "state", "." ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/train_phase.py#L18-L22
train
MillionIntegrals/vel
vel/rl/buffers/backend/prioritized_vec_buffer_backend.py
PrioritizedCircularVecEnvBufferBackend.update_priority
def update_priority(self, tree_idx_list, priority_list): """ Update priorities of the elements in the tree """ for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees): segment_tree.update(tree_idx, priority)
python
def update_priority(self, tree_idx_list, priority_list): """ Update priorities of the elements in the tree """ for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees): segment_tree.update(tree_idx, priority)
[ "def", "update_priority", "(", "self", ",", "tree_idx_list", ",", "priority_list", ")", ":", "for", "tree_idx", ",", "priority", ",", "segment_tree", "in", "zip", "(", "tree_idx_list", ",", "priority_list", ",", "self", ".", "segment_trees", ")", ":", "segment...
Update priorities of the elements in the tree
[ "Update", "priorities", "of", "the", "elements", "in", "the", "tree" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/prioritized_vec_buffer_backend.py#L72-L75
train
MillionIntegrals/vel
vel/rl/buffers/backend/prioritized_vec_buffer_backend.py
PrioritizedCircularVecEnvBufferBackend._sample_batch_prioritized
def _sample_batch_prioritized(self, segment_tree, batch_size, history, forward_steps=1): """ Return indexes of the next sample in from prioritized distribution """ p_total = segment_tree.total() segment = p_total / batch_size # Get batch of valid samples batch = [ se...
python
def _sample_batch_prioritized(self, segment_tree, batch_size, history, forward_steps=1): """ Return indexes of the next sample in from prioritized distribution """ p_total = segment_tree.total() segment = p_total / batch_size # Get batch of valid samples batch = [ se...
[ "def", "_sample_batch_prioritized", "(", "self", ",", "segment_tree", ",", "batch_size", ",", "history", ",", "forward_steps", "=", "1", ")", ":", "p_total", "=", "segment_tree", ".", "total", "(", ")", "segment", "=", "p_total", "/", "batch_size", "batch", ...
Return indexes of the next sample in from prioritized distribution
[ "Return", "indexes", "of", "the", "next", "sample", "in", "from", "prioritized", "distribution" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/prioritized_vec_buffer_backend.py#L87-L99
train
MillionIntegrals/vel
vel/rl/buffers/backend/circular_vec_buffer_backend.py
take_along_axis
def take_along_axis(large_array, indexes): """ Take along axis """ # Reshape indexes into the right shape if len(large_array.shape) > len(indexes.shape): indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape)))) return np.take_along_axis(large_array, ...
python
def take_along_axis(large_array, indexes): """ Take along axis """ # Reshape indexes into the right shape if len(large_array.shape) > len(indexes.shape): indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape)))) return np.take_along_axis(large_array, ...
[ "def", "take_along_axis", "(", "large_array", ",", "indexes", ")", ":", "if", "len", "(", "large_array", ".", "shape", ")", ">", "len", "(", "indexes", ".", "shape", ")", ":", "indexes", "=", "indexes", ".", "reshape", "(", "indexes", ".", "shape", "+"...
Take along axis
[ "Take", "along", "axis" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L7-L13
train
MillionIntegrals/vel
vel/rl/buffers/backend/circular_vec_buffer_backend.py
CircularVecEnvBufferBackend.get_transition
def get_transition(self, frame_idx, env_idx): """ Single transition with given index """ past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx) data_dict = { 'observations': past_frame, 'observations_next': future_frame, 'actions': self.act...
python
def get_transition(self, frame_idx, env_idx): """ Single transition with given index """ past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx) data_dict = { 'observations': past_frame, 'observations_next': future_frame, 'actions': self.act...
[ "def", "get_transition", "(", "self", ",", "frame_idx", ",", "env_idx", ")", ":", "past_frame", ",", "future_frame", "=", "self", ".", "get_frame_with_future", "(", "frame_idx", ",", "env_idx", ")", "data_dict", "=", "{", "'observations'", ":", "past_frame", "...
Single transition with given index
[ "Single", "transition", "with", "given", "index" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L190-L205
train
MillionIntegrals/vel
vel/rl/buffers/backend/circular_vec_buffer_backend.py
CircularVecEnvBufferBackend.get_transitions_forward_steps
def get_transitions_forward_steps(self, indexes, forward_steps, discount_factor): """ Get dictionary of a transition data - where the target of a transition is n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor, and the process stops wh...
python
def get_transitions_forward_steps(self, indexes, forward_steps, discount_factor): """ Get dictionary of a transition data - where the target of a transition is n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor, and the process stops wh...
[ "def", "get_transitions_forward_steps", "(", "self", ",", "indexes", ",", "forward_steps", ",", "discount_factor", ")", ":", "frame_batch_shape", "=", "(", "[", "indexes", ".", "shape", "[", "0", "]", ",", "indexes", ".", "shape", "[", "1", "]", "]", "+", ...
Get dictionary of a transition data - where the target of a transition is n steps forward along the trajectory. Rewards are properly aggregated according to the discount factor, and the process stops when trajectory is done.
[ "Get", "dictionary", "of", "a", "transition", "data", "-", "where", "the", "target", "of", "a", "transition", "is", "n", "steps", "forward", "along", "the", "trajectory", ".", "Rewards", "are", "properly", "aggregated", "according", "to", "the", "discount", ...
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L244-L288
train
MillionIntegrals/vel
vel/rl/buffers/backend/circular_vec_buffer_backend.py
CircularVecEnvBufferBackend.sample_batch_trajectories
def sample_batch_trajectories(self, rollout_length): """ Return indexes of next random rollout """ results = [] for i in range(self.num_envs): results.append(self.sample_rollout_single_env(rollout_length)) return np.stack(results, axis=-1)
python
def sample_batch_trajectories(self, rollout_length): """ Return indexes of next random rollout """ results = [] for i in range(self.num_envs): results.append(self.sample_rollout_single_env(rollout_length)) return np.stack(results, axis=-1)
[ "def", "sample_batch_trajectories", "(", "self", ",", "rollout_length", ")", ":", "results", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "num_envs", ")", ":", "results", ".", "append", "(", "self", ".", "sample_rollout_single_env", "(", "ro...
Return indexes of next random rollout
[ "Return", "indexes", "of", "next", "random", "rollout" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L310-L317
train
MillionIntegrals/vel
vel/rl/buffers/backend/circular_vec_buffer_backend.py
CircularVecEnvBufferBackend.sample_frame_single_env
def sample_frame_single_env(self, batch_size, forward_steps=1): """ Return an in index of a random set of frames from a buffer, that have enough history and future """ # Whole idea of this function is to make sure that sample we take is far away from the point which we are # currently writing to...
python
def sample_frame_single_env(self, batch_size, forward_steps=1): """ Return an in index of a random set of frames from a buffer, that have enough history and future """ # Whole idea of this function is to make sure that sample we take is far away from the point which we are # currently writing to...
[ "def", "sample_frame_single_env", "(", "self", ",", "batch_size", ",", "forward_steps", "=", "1", ")", ":", "if", "self", ".", "current_size", "<", "self", ".", "buffer_capacity", ":", "return", "np", ".", "random", ".", "choice", "(", "self", ".", "curren...
Return an in index of a random set of frames from a buffer, that have enough history and future
[ "Return", "an", "in", "index", "of", "a", "random", "set", "of", "frames", "from", "a", "buffer", "that", "have", "enough", "history", "and", "future" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L346-L367
train
MillionIntegrals/vel
vel/rl/commands/record_movie_command.py
RecordMovieCommand.record_take
def record_take(self, model, env_instance, device, take_number): """ Record a single movie and store it on hard drive """ frames = [] observation = env_instance.reset() if model.is_recurrent: hidden_state = model.zero_state(1).to(device) frames.append(env_instance....
python
def record_take(self, model, env_instance, device, take_number): """ Record a single movie and store it on hard drive """ frames = [] observation = env_instance.reset() if model.is_recurrent: hidden_state = model.zero_state(1).to(device) frames.append(env_instance....
[ "def", "record_take", "(", "self", ",", "model", ",", "env_instance", ",", "device", ",", "take_number", ")", ":", "frames", "=", "[", "]", "observation", "=", "env_instance", ".", "reset", "(", ")", "if", "model", ".", "is_recurrent", ":", "hidden_state",...
Record a single movie and store it on hard drive
[ "Record", "a", "single", "movie", "and", "store", "it", "on", "hard", "drive" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/commands/record_movie_command.py#L47-L91
train
MillionIntegrals/vel
vel/rl/modules/noise/ou_noise.py
OuNoise.reset_training_state
def reset_training_state(self, dones, batch_info): """ A hook for a model to react when during training episode is finished """ for idx, done in enumerate(dones): if done > 0.5: self.processes[idx].reset()
python
def reset_training_state(self, dones, batch_info): """ A hook for a model to react when during training episode is finished """ for idx, done in enumerate(dones): if done > 0.5: self.processes[idx].reset()
[ "def", "reset_training_state", "(", "self", ",", "dones", ",", "batch_info", ")", ":", "for", "idx", ",", "done", "in", "enumerate", "(", "dones", ")", ":", "if", "done", ">", "0.5", ":", "self", ".", "processes", "[", "idx", "]", ".", "reset", "(", ...
A hook for a model to react when during training episode is finished
[ "A", "hook", "for", "a", "model", "to", "react", "when", "during", "training", "episode", "is", "finished" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/noise/ou_noise.py#L22-L26
train
MillionIntegrals/vel
vel/rl/modules/noise/ou_noise.py
OuNoise.forward
def forward(self, actions, batch_info): """ Return model step after applying noise """ while len(self.processes) < actions.shape[0]: len_action_space = self.action_space.shape[-1] self.processes.append( OrnsteinUhlenbeckNoiseProcess( np.zeros(...
python
def forward(self, actions, batch_info): """ Return model step after applying noise """ while len(self.processes) < actions.shape[0]: len_action_space = self.action_space.shape[-1] self.processes.append( OrnsteinUhlenbeckNoiseProcess( np.zeros(...
[ "def", "forward", "(", "self", ",", "actions", ",", "batch_info", ")", ":", "while", "len", "(", "self", ".", "processes", ")", "<", "actions", ".", "shape", "[", "0", "]", ":", "len_action_space", "=", "self", ".", "action_space", ".", "shape", "[", ...
Return model step after applying noise
[ "Return", "model", "step", "after", "applying", "noise" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/noise/ou_noise.py#L28-L41
train
MillionIntegrals/vel
vel/util/intepolate.py
interpolate_logscale
def interpolate_logscale(start, end, steps): """ Interpolate series between start and end in given number of steps - logscale interpolation """ if start <= 0.0: warnings.warn("Start of logscale interpolation must be positive!") start = 1e-5 return np.logspace(np.log10(float(start)), np.log1...
python
def interpolate_logscale(start, end, steps): """ Interpolate series between start and end in given number of steps - logscale interpolation """ if start <= 0.0: warnings.warn("Start of logscale interpolation must be positive!") start = 1e-5 return np.logspace(np.log10(float(start)), np.log1...
[ "def", "interpolate_logscale", "(", "start", ",", "end", ",", "steps", ")", ":", "if", "start", "<=", "0.0", ":", "warnings", ".", "warn", "(", "\"Start of logscale interpolation must be positive!\"", ")", "start", "=", "1e-5", "return", "np", ".", "logspace", ...
Interpolate series between start and end in given number of steps - logscale interpolation
[ "Interpolate", "series", "between", "start", "and", "end", "in", "given", "number", "of", "steps", "-", "logscale", "interpolation" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L10-L16
train
MillionIntegrals/vel
vel/util/intepolate.py
interpolate_series
def interpolate_series(start, end, steps, how='linear'): """ Interpolate series between start and end in given number of steps """ return INTERP_DICT[how](start, end, steps)
python
def interpolate_series(start, end, steps, how='linear'): """ Interpolate series between start and end in given number of steps """ return INTERP_DICT[how](start, end, steps)
[ "def", "interpolate_series", "(", "start", ",", "end", ",", "steps", ",", "how", "=", "'linear'", ")", ":", "return", "INTERP_DICT", "[", "how", "]", "(", "start", ",", "end", ",", "steps", ")" ]
Interpolate series between start and end in given number of steps
[ "Interpolate", "series", "between", "start", "and", "end", "in", "given", "number", "of", "steps" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L48-L50
train
MillionIntegrals/vel
vel/util/intepolate.py
interpolate_single
def interpolate_single(start, end, coefficient, how='linear'): """ Interpolate single value between start and end in given number of steps """ return INTERP_SINGLE_DICT[how](start, end, coefficient)
python
def interpolate_single(start, end, coefficient, how='linear'): """ Interpolate single value between start and end in given number of steps """ return INTERP_SINGLE_DICT[how](start, end, coefficient)
[ "def", "interpolate_single", "(", "start", ",", "end", ",", "coefficient", ",", "how", "=", "'linear'", ")", ":", "return", "INTERP_SINGLE_DICT", "[", "how", "]", "(", "start", ",", "end", ",", "coefficient", ")" ]
Interpolate single value between start and end in given number of steps
[ "Interpolate", "single", "value", "between", "start", "and", "end", "in", "given", "number", "of", "steps" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L53-L55
train
MillionIntegrals/vel
vel/commands/summary_command.py
ModelSummary.run
def run(self, *args): """ Print model summary """ if self.source is None: self.model.summary() else: x_data, y_data = next(iter(self.source.train_loader())) self.model.summary(input_size=x_data.shape[1:])
python
def run(self, *args): """ Print model summary """ if self.source is None: self.model.summary() else: x_data, y_data = next(iter(self.source.train_loader())) self.model.summary(input_size=x_data.shape[1:])
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "source", "is", "None", ":", "self", ".", "model", ".", "summary", "(", ")", "else", ":", "x_data", ",", "y_data", "=", "next", "(", "iter", "(", "self", ".", "source", "...
Print model summary
[ "Print", "model", "summary" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/summary_command.py#L10-L16
train
MillionIntegrals/vel
vel/rl/reinforcers/on_policy_iteration_reinforcer.py
OnPolicyIterationReinforcer.initialize_training
def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None): """ Prepare models for training """ if model_state is not None: self.model.load_state_dict(model_state) else: self.model.reset_weights() self.algo.initialize( ...
python
def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None): """ Prepare models for training """ if model_state is not None: self.model.load_state_dict(model_state) else: self.model.reset_weights() self.algo.initialize( ...
[ "def", "initialize_training", "(", "self", ",", "training_info", ":", "TrainingInfo", ",", "model_state", "=", "None", ",", "hidden_state", "=", "None", ")", ":", "if", "model_state", "is", "not", "None", ":", "self", ".", "model", ".", "load_state_dict", "(...
Prepare models for training
[ "Prepare", "models", "for", "training" ]
e0726e1f63742b728966ccae0c8b825ea0ba491a
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/on_policy_iteration_reinforcer.py#L63-L72
train