idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
43,400
def getOid ( self ) : if self . _state & self . ST_CLEAN : return self . _oid else : raise SmiError ( '%s object not fully initialized' % self . __class__ . __name__ )
Returns OID identifying MIB variable .
43,401
def getLabel ( self ) : if self . _state & self . ST_CLEAN : return self . _label else : raise SmiError ( '%s object not fully initialized' % self . __class__ . __name__ )
Returns symbolic path to this MIB variable .
43,402
def addMibSource ( self , * mibSources ) : if self . _mibSourcesToAdd is None : self . _mibSourcesToAdd = mibSources else : self . _mibSourcesToAdd += mibSources return self
Adds path to repository to search PySNMP MIB files .
43,403
def loadMibs ( self , * modNames ) : if self . _modNamesToLoad is None : self . _modNamesToLoad = modNames else : self . _modNamesToLoad += modNames return self
Schedules search and load of given MIB modules .
43,404
def resolveWithMib ( self , mibViewController ) : if self . _state & self . ST_CLEAM : return self self . _args [ 0 ] . resolveWithMib ( mibViewController ) MibScalar , MibTableColumn = mibViewController . mibBuilder . importSymbols ( 'SNMPv2-SMI' , 'MibScalar' , 'MibTableColumn' ) if not isinstance ( self . _args [ 0 ...
Perform MIB variable ID and associated value conversion .
43,405
def addVarBinds ( self , * varBinds ) : debug . logger & debug . FLAG_MIB and debug . logger ( 'additional var-binds: %r' % ( varBinds , ) ) if self . _state & self . ST_CLEAN : raise SmiError ( '%s object is already sealed' % self . __class__ . __name__ ) else : self . _additionalVarBinds . extend ( varBinds ) return ...
Appends variable - binding to notification .
43,406
def resolveWithMib ( self , mibViewController ) : if self . _state & self . ST_CLEAN : return self self . _objectIdentity . resolveWithMib ( mibViewController ) self . _varBinds . append ( ObjectType ( ObjectIdentity ( v2c . apiTrapPDU . snmpTrapOID ) , self . _objectIdentity ) . resolveWithMib ( mibViewController ) ) ...
Perform MIB variable ID conversion and notification objects expansion .
43,407
def withValues ( cls , * values ) : class X ( cls ) : subtypeSpec = cls . subtypeSpec + constraint . SingleValueConstraint ( * values ) X . __name__ = cls . __name__ return X
Creates a subclass with discreet values constraint .
43,408
def withRange ( cls , minimum , maximum ) : class X ( cls ) : subtypeSpec = cls . subtypeSpec + constraint . ValueRangeConstraint ( minimum , maximum ) X . __name__ = cls . __name__ return X
Creates a subclass with value range constraint .
43,409
def withNamedValues ( cls , ** values ) : enums = set ( cls . namedValues . items ( ) ) enums . update ( values . items ( ) ) class X ( cls ) : namedValues = namedval . NamedValues ( * enums ) subtypeSpec = cls . subtypeSpec + constraint . SingleValueConstraint ( * values . values ( ) ) X . __name__ = cls . __name__ re...
Create a subclass with discreet named values constraint .
43,410
def withSize ( cls , minimum , maximum ) : class X ( cls ) : subtypeSpec = cls . subtypeSpec + constraint . ValueSizeConstraint ( minimum , maximum ) X . __name__ = cls . __name__ return X
Creates a subclass with value size constraint .
43,411
def withNamedBits ( cls , ** values ) : enums = set ( cls . namedValues . items ( ) ) enums . update ( values . items ( ) ) class X ( cls ) : namedValues = namedval . NamedValues ( * enums ) X . __name__ = cls . __name__ return X
Creates a subclass with discreet named bits constraint .
43,412
def loadModule ( self , modName , ** userCtx ) : for mibSource in self . _mibSources : debug . logger & debug . FLAG_BLD and debug . logger ( 'loadModule: trying %s at %s' % ( modName , mibSource ) ) try : codeObj , sfx = mibSource . read ( modName ) except IOError as exc : debug . logger & debug . FLAG_BLD and debug ....
Load and execute MIB modules as Python code
43,413
def nextCmd ( snmpDispatcher , authData , transportTarget , * varBinds , ** options ) : def cbFun ( * args , ** kwargs ) : response [ : ] = args + ( kwargs . get ( 'nextVarBinds' , ( ) ) , ) options [ 'cbFun' ] = cbFun lexicographicMode = options . pop ( 'lexicographicMode' , True ) maxRows = options . pop ( 'maxRows' ...
Create a generator to perform one or more SNMP GETNEXT queries .
43,414
def registerContextEngineId ( self , contextEngineId , pduTypes , processPdu ) : for pduType in pduTypes : k = contextEngineId , pduType if k in self . _appsRegistration : raise error . ProtocolError ( 'Duplicate registration %r/%s' % ( contextEngineId , pduType ) ) self . _appsRegistration [ k ] = processPdu debug . l...
Register application with dispatcher
43,415
def unregisterContextEngineId ( self , contextEngineId , pduTypes ) : if contextEngineId is None : contextEngineId , = self . mibInstrumController . mibBuilder . importSymbols ( '__SNMP-FRAMEWORK-MIB' , 'snmpEngineID' ) for pduType in pduTypes : k = contextEngineId , pduType if k in self . _appsRegistration : del self ...
Unregister application with dispatcher
43,416
def sendNotification ( snmpEngine , authData , transportTarget , contextData , notifyType , * varBinds , ** options ) : def __cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBinds , cbCtx ) : lookupMib , deferred = cbCtx if errorIndication : deferred . errback ( Failure ( errorI...
Sends SNMP notification .
43,417
def nextCmd ( snmpEngine , authData , transportTarget , contextData , * varBinds , ** options ) : def __cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBindTable , cbCtx ) : lookupMib , deferred = cbCtx if ( options . get ( 'ignoreNonIncreasingOid' , False ) and errorIndication ...
Performs SNMP GETNEXT query .
43,418
def getBranch ( self , name , ** context ) : for keyLen in self . _vars . getKeysLens ( ) : subName = name [ : keyLen ] if subName in self . _vars : return self . _vars [ subName ] raise error . NoSuchObjectError ( name = name , idx = context . get ( 'idx' ) )
Return a branch of this tree where the name OID may reside
43,419
def getNode ( self , name , ** context ) : if name == self . name : return self else : return self . getBranch ( name , ** context ) . getNode ( name , ** context )
Return tree node found by name
43,420
def getNextNode ( self , name , ** context ) : try : nextNode = self . getBranch ( name , ** context ) except ( error . NoSuchInstanceError , error . NoSuchObjectError ) : return self . getNextBranch ( name , ** context ) else : try : return nextNode . getNextNode ( name , ** context ) except ( error . NoSuchInstanceEr...
Return tree node next to name
43,421
def writeCommit ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: writeCommit(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY ...
Commit new value of the Managed Object Instance .
43,422
def readGet ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: readGet(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] if name == self . name : cbFun ( ( name , exval . noSuchInstance ) , ** context ) return acFun = context . get ( 'acFu...
Read Managed Object Instance .
43,423
def readGetNext ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: readGetNext(%s, %r)' % ( self , name , val ) ) ) acFun = context . get ( 'acFun' ) if acFun : if ( self . maxAccess not in ( 'readonly' , 'readwrite' , 'readcreate' ) or acFun ( 'read' , ...
Read the next Managed Object Instance .
43,424
def createCommit ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: writeCommit(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY...
Create Managed Object Instance .
43,425
def createCleanup ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: createCleanup(%s, %r)' % ( self , name , val ) ) ) instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context ...
Finalize Managed Object Instance creation .
43,426
def destroyCommit ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: destroyCommit(%s, %r)' % ( self , name , val ) ) ) instances = context [ 'instances' ] . setdefault ( self . name , { self . ST_CREATE : { } , self . ST_DESTROY : { } } ) idx = context ...
Destroy Managed Object Instance .
43,427
def oidToValue ( self , syntax , identifier , impliedFlag = False , parentIndices = None ) : if not identifier : raise error . SmiError ( 'Short OID for index %r' % ( syntax , ) ) if hasattr ( syntax , 'cloneFromName' ) : return syntax . cloneFromName ( identifier , impliedFlag , parentRow = self , parentIndices = pare...
Turn SMI table instance identifier into a value object .
43,428
def valueToOid ( self , value , impliedFlag = False , parentIndices = None ) : if hasattr ( value , 'cloneAsName' ) : return value . cloneAsName ( impliedFlag , parentRow = self , parentIndices = parentIndices ) baseTag = value . getTagSet ( ) . getBaseTag ( ) if baseTag == Integer . tagSet . getBaseTag ( ) : return in...
Turn value object into SMI table instance identifier .
43,429
def announceManagementEvent ( self , action , varBind , ** context ) : name , val = varBind cbFun = context [ 'cbFun' ] if not self . _augmentingRows : cbFun ( varBind , ** context ) return instId = name [ len ( self . name ) + 1 : ] baseIndices = [ ] indices = [ ] for impliedFlag , modName , symName in self . _indexNa...
Announce mass operation on parent table s row .
43,430
def receiveManagementEvent ( self , action , varBind , ** context ) : baseIndices , val = varBind instId = ( ) for impliedFlag , modName , symName in self . _indexNames : mibObj , = mibBuilder . importSymbols ( modName , symName ) parentIndices = [ ] for name , syntax in baseIndices : if name == mibObj . name : instId ...
Apply mass operation on extending table s row .
43,431
def registerAugmentation ( self , * names ) : for name in names : if name in self . _augmentingRows : raise error . SmiError ( 'Row %s already augmented by %s::%s' % ( self . name , name [ 0 ] , name [ 1 ] ) ) self . _augmentingRows . add ( name ) return self
Register table extension .
43,432
def _manageColumns ( self , action , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: _manageColumns(%s, %s, %r)' % ( self , action , name , val ) ) ) cbFun = context [ 'cbFun' ] colLen = len ( self . name ) + 1 indexVals = { } instId = name [ colLen : ] indice...
Apply a management action on all columns
43,433
def _checkColumns ( self , varBind , ** context ) : name , val = varBind ( debug . logger & debug . FLAG_INS and debug . logger ( '%s: _checkColumns(%s, %r)' % ( self , name , val ) ) ) cbFun = context [ 'cbFun' ] if val != 1 : cbFun ( varBind , ** context ) return count = [ len ( self . _vars ) ] def _cbFun ( varBind ...
Check the consistency of all columns .
43,434
def getIndicesFromInstId ( self , instId ) : if instId in self . _idToIdxCache : return self . _idToIdxCache [ instId ] indices = [ ] for impliedFlag , modName , symName in self . _indexNames : mibObj , = mibBuilder . importSymbols ( modName , symName ) try : syntax , instId = self . oidToValue ( mibObj . syntax , inst...
Return index values for instance identification
43,435
def getInstIdFromIndices ( self , * indices ) : try : return self . _idxToIdCache [ indices ] except TypeError : cacheable = False except KeyError : cacheable = True idx = 0 instId = ( ) parentIndices = [ ] for impliedFlag , modName , symName in self . _indexNames : if idx >= len ( indices ) : break mibObj , = mibBuild...
Return column instance identification from indices
43,436
def getInstNameByIndex ( self , colId , * indices ) : return self . name + ( colId , ) + self . getInstIdFromIndices ( * indices )
Build column instance name from components
43,437
def getInstNamesByIndex ( self , * indices ) : instNames = [ ] for columnName in self . _vars . keys ( ) : instNames . append ( self . getInstNameByIndex ( * ( columnName [ - 1 ] , ) + indices ) ) return tuple ( instNames )
Build column instance names from indices
43,438
def nextCmd ( snmpEngine , authData , transportTarget , contextData , * varBinds , ** options ) : def cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBindTable , cbCtx ) : cbCtx [ 'errorIndication' ] = errorIndication cbCtx [ 'errorStatus' ] = errorStatus cbCtx [ 'errorIndex' ] ...
Creates a generator to perform one or more SNMP GETNEXT queries .
43,439
def _storeAccessContext ( snmpEngine ) : execCtx = snmpEngine . observer . getExecutionContext ( 'rfc3412.receiveMessage:request' ) return { 'securityModel' : execCtx [ 'securityModel' ] , 'securityName' : execCtx [ 'securityName' ] , 'securityLevel' : execCtx [ 'securityLevel' ] , 'contextName' : execCtx [ 'contextNam...
Copy received message metadata while it lasts
43,440
def _getManagedObjectsInstances ( self , varBinds , ** context ) : rspVarBinds = context [ 'rspVarBinds' ] varBindsMap = context [ 'varBindsMap' ] rtrVarBinds = [ ] for idx , varBind in enumerate ( varBinds ) : name , val = varBind if ( exval . noSuchObject . isSameTypeWith ( val ) or exval . noSuchInstance . isSameTyp...
Iterate over Managed Objects fulfilling SNMP query .
43,441
def clone ( self , value = univ . noValue , ** kwargs ) : cloned = univ . Choice . clone ( self , ** kwargs ) if value is not univ . noValue : if isinstance ( value , NetworkAddress ) : value = value . getComponent ( ) elif not isinstance ( value , IpAddress ) : value = IpAddress ( value ) try : tagSet = value . tagSet...
Clone this instance .
43,442
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
43,443
def readMibObjects ( self , * varBinds , ** context ) : if 'cbFun' not in context : context [ 'cbFun' ] = self . _defaultErrorHandler self . flipFlopFsm ( self . FSM_READ_VAR , * varBinds , ** context )
Read Managed Objects Instances .
43,444
def readNextMibObjects ( self , * varBinds , ** context ) : if 'cbFun' not in context : context [ 'cbFun' ] = self . _defaultErrorHandler self . flipFlopFsm ( self . FSM_READ_NEXT_VAR , * varBinds , ** context )
Read Managed Objects Instances next to the given ones .
43,445
def writeMibObjects ( self , * varBinds , ** context ) : if 'cbFun' not in context : context [ 'cbFun' ] = self . _defaultErrorHandler self . flipFlopFsm ( self . FSM_WRITE_VAR , * varBinds , ** context )
Create destroy or modify Managed Objects Instances .
43,446
def bulkCmd ( snmpDispatcher , authData , transportTarget , nonRepeaters , maxRepetitions , * varBinds , ** options ) : def _cbFun ( snmpDispatcher , stateHandle , errorIndication , rspPdu , _cbCtx ) : if not cbFun : return if errorIndication : cbFun ( errorIndication , pMod . Integer ( 0 ) , pMod . Integer ( 0 ) , Non...
Initiate SNMP GETBULK query over SNMPv2c .
43,447
def save ( self ) : if self . mode in ( "wb+" , 'rb+' ) : if not self . is_open : raise IOError ( "file closed" ) self . write_reference_properties ( ) self . manager . write_objects ( )
Writes current changes to disk and flushes modified objects in the AAFObjectManager
43,448
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 .
43,449
def run_apidoc ( _ ) : import os dirname = os . path . dirname ( __file__ ) ignore_paths = [ os . path . join ( dirname , '../../aaf2/model' ) , ] argv = [ '--force' , '--no-toc' , '--separate' , '--module-first' , '--output-dir' , os . path . join ( dirname , 'api' ) , os . path . join ( dirname , '../../aaf2' ) , ] +...
This method is required by the setup method below .
43,450
def from_dict ( self , d ) : 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' : 0 , 'Data2' : 0 , 'Data3' : 0 , 'Data4' : [ 0 for...
Set MobID from a dict
43,451
def to_dict ( self ) : material = { 'Data1' : self . Data1 , 'Data2' : self . Data2 , 'Data3' : self . Data3 , 'Data4' : list ( self . Data4 ) } return { 'material' : material , 'length' : self . length , 'instanceHigh' : self . instanceHigh , 'instanceMid' : self . instanceMid , 'instanceLow' : self . instanceLow , 'S...
MobID representation as dict
43,452
def wave_infochunk ( path ) : with open ( path , 'rb' ) as file : if file . read ( 4 ) != b"RIFF" : return None data_size = file . read ( 4 ) if file . read ( 4 ) != b"WAVE" : return None while True : chunkid = file . read ( 4 ) sizebuf = file . read ( 4 ) if len ( sizebuf ) < 4 or len ( chunkid ) < 4 : return None siz...
Returns a bytearray of the WAVE RIFF header and fmt chunk for a WAVEDescriptor Summary
43,453
def pop ( self ) : 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 if root . dir_id == entry . dir_id : parent . child_id = None else : while True : if count > max_dirs_entr...
remove self from binary search tree
43,454
def remove ( self , path ) : entry = self . find ( path ) if not entry : raise ValueError ( "%s does not exists" % path ) if entry . type == 'root storage' : raise ValueError ( "can no remove root entry" ) if entry . type == "storage" and not entry . child_id is None : raise ValueError ( "storage contains children" ) e...
Removes both streams and storage DirEntry types from file . storage type entries need to be empty dirs .
43,455
def rmtree ( self , path ) : 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 ) self . free_dir_entry ( item ) for item in storage : self . free_dir_entry ( item ) root . child_id = Non...
Removes directory structure similar to shutil . rmtree .
43,456
def listdir_dict ( self , path = None ) : if path is None : path = self . root root = self . find ( path ) if root is None : raise ValueError ( "unable to find dir: %s" % str ( path ) ) if not root . isdir ( ) : raise ValueError ( "can only list storage types" ) children = self . children_cache . get ( root . dir_id , ...
Return a dict containing the DirEntry objects in the directory given by path with name of the dir as key .
43,457
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
43,458
def makedirs ( self , path ) : root = "" assert path . startswith ( '/' ) p = path . strip ( '/' ) for item in p . split ( '/' ) : root += "/" + item if not self . exists ( root ) : self . makedir ( root ) return self . find ( path )
Recursive storage DirEntry creation function .
43,459
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 . endswith ( '/' ) : dst += src_entry . name if self . exists ( dst ) : raise ValueError ( "dst path already exist: %s" % dst ) if dst == '/' or src == '/' : raise Value...
Moves DirEntry from src to dst
43,460
def open ( self , path , mode = 'r' ) : 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 ) else : if not entry . isfile ( ) : raise ValueError ( "can only open stream type DirEntry's" ) if m...
Open stream returning Stream object
43,461
def add2set ( self , pid , key , value ) : 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 : prop . references [ key ] = prop . next_fre...
low level add to StrongRefSetProperty
43,462
def histogram_info ( self ) -> dict : return { 'support_atoms' : self . support_atoms , 'atom_delta' : self . atom_delta , 'vmin' : self . vmin , 'vmax' : self . vmax , 'num_atoms' : self . atoms }
Return extra information about histogram
43,463
def sample ( self , histogram_logits ) : histogram_probs = histogram_logits . exp ( ) atoms = self . support_atoms . view ( 1 , 1 , self . atoms ) return ( histogram_probs * atoms ) . sum ( dim = - 1 ) . argmax ( dim = 1 )
Sample from a greedy strategy with given q - value histogram
43,464
def download ( self ) : if not os . path . exists ( self . data_path ) : pathlib . Path ( self . data_path ) . mkdir ( parents = True , exist_ok = True ) if not os . path . exists ( self . text_path ) : http = urllib3 . PoolManager ( cert_reqs = 'CERT_REQUIRED' , ca_certs = certifi . where ( ) ) with open ( self . text...
Make sure data file is downloaded and stored properly
43,465
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
43,466
def create ( model_config , path , num_workers , batch_size , augmentations = None , tta = None ) : 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' ) train_ds = ImageDirSource ( train_path ...
Create an ImageDirSource with supplied arguments
43,467
def reset_weights ( self ) : self . input_block . reset_weights ( ) self . backbone . reset_weights ( ) self . q_head . reset_weights ( )
Initialize weights to reasonable defaults
43,468
def result ( self ) : return { k : torch . stack ( v ) for k , v in self . accumulants . items ( ) }
Concatenate accumulated tensors
43,469
def resolve_parameters ( self , func , extra_env = None ) : 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 None else { } kwargs = { } for parameter_name , is_required in parameter_list :...
Resolve parameter dictionary for the supplied function
43,470
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
43,471
def instantiate_from_data ( self , object_data ) : if isinstance ( object_data , dict ) and 'name' in object_data : name = object_data [ 'name' ] module = importlib . import_module ( name ) return self . resolve_and_call ( module . create , extra_env = object_data ) if isinstance ( object_data , dict ) and 'factory' in...
Instantiate object from the supplied data additional args may come from the environment
43,472
def render_configuration ( self , configuration = None ) : if configuration is None : configuration = self . environment if isinstance ( configuration , dict ) : return { k : self . render_configuration ( v ) for k , v in configuration . items ( ) } elif isinstance ( configuration , list ) : return [ self . render_conf...
Render variables in configuration object but don t instantiate anything
43,473
def is_provided ( self , name ) : if name in self . _storage : return True elif name in self . _providers : return True elif name . startswith ( 'rollout:' ) : rollout_name = name [ 8 : ] else : return False
Capability check if evaluator provides given value
43,474
def get ( self , name ) : if name in self . _storage : return self . _storage [ name ] elif name in self . _providers : value = self . _storage [ name ] = self . _providers [ name ] ( self ) return value elif name . startswith ( 'rollout:' ) : rollout_name = name [ 8 : ] value = self . _storage [ name ] = self . rollou...
Return a value from this evaluator .
43,475
def create ( model_config , batch_size , normalize = True , num_workers = 0 , augmentations = None ) : path = model_config . data_dir ( 'mnist' ) train_dataset = datasets . MNIST ( path , train = True , download = True ) test_dataset = datasets . MNIST ( path , train = False , download = True ) augmentations = [ ToArra...
Create a MNIST dataset normalized
43,476
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 .
43,477
def load ( self , train_info : TrainingInfo ) -> ( dict , dict ) : last_epoch = train_info . start_epoch_idx model_state = torch . load ( self . checkpoint_filename ( last_epoch ) ) hidden_state = torch . load ( self . checkpoint_hidden_filename ( last_epoch ) ) self . checkpoint_strategy . restore ( hidden_state ) tra...
Resume learning process and return loaded hidden state dictionary
43,478
def clean ( self , global_epoch_idx ) : 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 . match ( 'checkpoint_(\\d+)\\.data' , x ) if match : idx = int ( match [ ...
Clean old checkpoints
43,479
def checkpoint ( self , epoch_info : EpochInfo , model : Model ) : self . clean ( epoch_info . global_epoch_idx - 1 ) self . _make_sure_dir_exists ( ) torch . save ( model . state_dict ( ) , self . checkpoint_filename ( epoch_info . global_epoch_idx ) ) hidden_state = epoch_info . state_dict ( ) self . checkpoint_strat...
When epoch is done we persist the training state
43,480
def _persisted_last_epoch ( self ) -> int : 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 : idx = int ( match [ 1 ] ) if idx > epoch_number : epoch_number = idx return epoch_number
Return number of last epoch already calculated
43,481
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
43,482
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 : p . requires_grad , model . parameters ( ) ) , max_norm = max_grad_norm ) else : grad_norm = 0.0 batch_result [ 'grad_norm' ] = grad_norm
Clip gradients to a given maximum length
43,483
def sample_trajectories ( self , rollout_length , batch_info ) -> Trajectories : indexes = self . backend . sample_batch_trajectories ( rollout_length ) transition_tensors = self . backend . get_trajectories ( indexes , rollout_length ) return Trajectories ( num_steps = rollout_length , num_envs = self . backend . num_...
Sample batch of trajectories and return them
43,484
def conjugate_gradient_method ( matrix_vector_operator , loss_gradient , nsteps , rdotr_tol = 1e-10 ) : 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_vector_operator ( p ) alpha = rdotr / torch ...
Conjugate gradient algorithm
43,485
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 . clone ( ) for idx in range ( self . line_search_iters ) : stepsize = 0.5 ** idx new_parameter_vec = current_param...
Find the right stepsize to make sure policy improves
43,486
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 double_gradient = torch . autograd . grad ( dot_product , model . policy_parameters ( ) , retain_graph = True ) fvp = p2v ...
Calculate product Hessian
43,487
def value_loss ( self , model , observations , discounted_rewards ) : value_outputs = model . value ( observations ) value_loss = 0.5 * F . mse_loss ( value_outputs , discounted_rewards ) return value_loss
Loss of value estimator
43,488
def calc_policy_loss ( self , model , policy_params , policy_entropy , rollout ) : actions = rollout . batch_tensor ( 'actions' ) advantages = rollout . batch_tensor ( 'advantages' ) fixed_logprobs = rollout . batch_tensor ( 'action:logprobs' ) model_logprobs = model . logprob ( actions , policy_params ) advantages = (...
Policy gradient loss - calculate from probability distribution
43,489
def shuffled_batches ( self , batch_size ) : 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 ( indices ) for sub_indices in np . array_split ( indices , batch_splits ) : yield Transitio...
Generate randomized batches of data
43,490
def to_transitions ( self ) -> 'Transitions' : return Transitions ( size = self . num_steps * self . num_envs , environment_information = [ ei for l in self . environment_information for ei in l ] if self . environment_information is not None else None , transition_tensors = { name : tensor_util . merge_first_two_dims ...
Convert given rollout to Transitions
43,491
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 batch_splits = math_util . divide_ceiling ( self . num_envs , rollouts_in_batch ) indices = list ( range ( self . num_envs ) ) np . random . shuffle ( i...
Generate randomized batches of data - only sample whole trajectories
43,492
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
43,493
def forward_state ( self , sequence , state = None ) : if state is None : state = self . zero_state ( sequence . size ( 0 ) ) data = self . input_block ( sequence ) state_outputs = [ ] for idx in range ( len ( self . recurrent_layers ) ) : layer_length = self . recurrent_layers [ idx ] . state_dim current_state = state...
Forward propagate a sequence through the network accounting for the state
43,494
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 ) . to ( torch . long ) return F . nll_loss ( y_pred , y_true )
Calculate a value of loss function
43,495
def initialize_training ( self , training_info : TrainingInfo , model_state = None , hidden_state = None ) : if model_state is None : self . model . reset_weights ( ) else : self . model . load_state_dict ( model_state )
Prepare for training
43,496
def run_epoch ( self , epoch_info : EpochInfo , source : 'vel.api.Source' ) : 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 ) ) self . train_epoch ( epoch_info , source ) epo...
Run full epoch of learning
43,497
def train_epoch ( self , epoch_info , source : 'vel.api.Source' , interactive = True ) : self . train ( ) if interactive : iterator = tqdm . tqdm ( source . train_loader ( ) , desc = "Training" , unit = "iter" , file = sys . stdout ) else : iterator = source . train_loader ( ) for batch_idx , ( data , target ) in enume...
Run a single training epoch
43,498
def validation_epoch ( self , epoch_info , source : 'vel.api.Source' ) : 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 ( iterator ) : batch_info = BatchInfo ( epoch_...
Run a single evaluation epoch
43,499
def feed_batch ( self , batch_info , data , target ) : data , target = data . to ( self . device ) , target . to ( self . device ) output , loss = self . model . loss ( data , target ) batch_info [ 'data' ] = data batch_info [ 'target' ] = target batch_info [ 'output' ] = output batch_info [ 'loss' ] = loss return loss
Run single batch of data