idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
19,500 | public double precision ( Integer classLabel , double edgeCase ) { double tpCount = truePositives . getCount ( classLabel ) ; double fpCount = falsePositives . getCount ( classLabel ) ; return EvaluationUtils . precision ( ( long ) tpCount , ( long ) fpCount , edgeCase ) ; } | Returns the precision for a given label |
19,501 | public double recall ( int classLabel , double edgeCase ) { double tpCount = truePositives . getCount ( classLabel ) ; double fnCount = falseNegatives . getCount ( classLabel ) ; return EvaluationUtils . recall ( ( long ) tpCount , ( long ) fnCount , edgeCase ) ; } | Returns the recall for a given label |
19,502 | public double falsePositiveRate ( int classLabel , double edgeCase ) { double fpCount = falsePositives . getCount ( classLabel ) ; double tnCount = trueNegatives . getCount ( classLabel ) ; return EvaluationUtils . falsePositiveRate ( ( long ) fpCount , ( long ) tnCount , edgeCase ) ; } | Returns the false positive rate for a given label |
19,503 | public double falsePositiveRate ( EvaluationAveraging averaging ) { int nClasses = confusion ( ) . getClasses ( ) . size ( ) ; if ( averaging == EvaluationAveraging . Macro ) { double macroFPR = 0.0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { macroFPR += falsePositiveRate ( i ) ; } macroFPR /= nClasses ; return macroFPR ; } else if ( averaging == EvaluationAveraging . Micro ) { long fpCount = 0 ; long tnCount = 0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { fpCount += falsePositives . getCount ( i ) ; tnCount += trueNegatives . getCount ( i ) ; } return EvaluationUtils . falsePositiveRate ( fpCount , tnCount , DEFAULT_EDGE_VALUE ) ; } else { throw new UnsupportedOperationException ( "Unknown averaging approach: " + averaging ) ; } } | Calculate the average false positive rate across all classes . Can specify whether macro or micro averaging should be used |
19,504 | public double falseNegativeRate ( EvaluationAveraging averaging ) { int nClasses = confusion ( ) . getClasses ( ) . size ( ) ; if ( averaging == EvaluationAveraging . Macro ) { double macroFNR = 0.0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { macroFNR += falseNegativeRate ( i ) ; } macroFNR /= nClasses ; return macroFNR ; } else if ( averaging == EvaluationAveraging . Micro ) { long fnCount = 0 ; long tnCount = 0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { fnCount += falseNegatives . getCount ( i ) ; tnCount += trueNegatives . getCount ( i ) ; } return EvaluationUtils . falseNegativeRate ( fnCount , tnCount , DEFAULT_EDGE_VALUE ) ; } else { throw new UnsupportedOperationException ( "Unknown averaging approach: " + averaging ) ; } } | Calculate the average false negative rate for all classes - can specify whether macro or micro averaging should be used |
19,505 | public double fBeta ( double beta , EvaluationAveraging averaging ) { if ( getNumRowCounter ( ) == 0.0 ) { return Double . NaN ; } int nClasses = confusion ( ) . getClasses ( ) . size ( ) ; if ( nClasses == 2 ) { return EvaluationUtils . fBeta ( beta , ( long ) truePositives . getCount ( 1 ) , ( long ) falsePositives . getCount ( 1 ) , ( long ) falseNegatives . getCount ( 1 ) ) ; } if ( averaging == EvaluationAveraging . Macro ) { double macroFBeta = 0.0 ; int count = 0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { double thisFBeta = fBeta ( beta , i , - 1 ) ; if ( thisFBeta != - 1 ) { macroFBeta += thisFBeta ; count ++ ; } } macroFBeta /= count ; return macroFBeta ; } else if ( averaging == EvaluationAveraging . Micro ) { long tpCount = 0 ; long fpCount = 0 ; long fnCount = 0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { tpCount += truePositives . getCount ( i ) ; fpCount += falsePositives . getCount ( i ) ; fnCount += falseNegatives . getCount ( i ) ; } return EvaluationUtils . fBeta ( beta , tpCount , fpCount , fnCount ) ; } else { throw new UnsupportedOperationException ( "Unknown averaging approach: " + averaging ) ; } } | Calculate the average F_beta score across all classes using macro or micro averaging |
19,506 | public double gMeasure ( EvaluationAveraging averaging ) { int nClasses = confusion ( ) . getClasses ( ) . size ( ) ; if ( averaging == EvaluationAveraging . Macro ) { double macroGMeasure = 0.0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { macroGMeasure += gMeasure ( i ) ; } macroGMeasure /= nClasses ; return macroGMeasure ; } else if ( averaging == EvaluationAveraging . Micro ) { long tpCount = 0 ; long fpCount = 0 ; long fnCount = 0 ; for ( int i = 0 ; i < nClasses ; i ++ ) { tpCount += truePositives . getCount ( i ) ; fpCount += falsePositives . getCount ( i ) ; fnCount += falseNegatives . getCount ( i ) ; } double precision = EvaluationUtils . precision ( tpCount , fpCount , DEFAULT_EDGE_VALUE ) ; double recall = EvaluationUtils . recall ( tpCount , fnCount , DEFAULT_EDGE_VALUE ) ; return EvaluationUtils . gMeasure ( precision , recall ) ; } else { throw new UnsupportedOperationException ( "Unknown averaging approach: " + averaging ) ; } } | Calculates the average G measure for all outputs using micro or macro averaging |
19,507 | public void merge ( Evaluation other ) { if ( other == null ) return ; truePositives . incrementAll ( other . truePositives ) ; falsePositives . incrementAll ( other . falsePositives ) ; trueNegatives . incrementAll ( other . trueNegatives ) ; falseNegatives . incrementAll ( other . falseNegatives ) ; if ( confusion == null ) { if ( other . confusion != null ) confusion = new ConfusionMatrix < > ( other . confusion ) ; } else { if ( other . confusion != null ) confusion ( ) . add ( other . confusion ) ; } numRowCounter += other . numRowCounter ; if ( labelsList . isEmpty ( ) ) labelsList . addAll ( other . labelsList ) ; if ( topN != other . topN ) { log . warn ( "Different topN values ({} vs {}) detected during Evaluation merging. Top N accuracy may not be accurate." , topN , other . topN ) ; } this . topNCorrectCount += other . topNCorrectCount ; this . topNTotalCount += other . topNTotalCount ; } | Merge the other evaluation object into this one . The result is that this Evaluation instance contains the counts etc from both |
19,508 | public String confusionToString ( ) { int nClasses = confusion ( ) . getClasses ( ) . size ( ) ; int maxLabelSize = 0 ; for ( String s : labelsList ) { maxLabelSize = Math . max ( maxLabelSize , s . length ( ) ) ; } int labelSize = Math . max ( maxLabelSize + 5 , 10 ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "%-3d" ) ; sb . append ( "%-" ) ; sb . append ( labelSize ) ; sb . append ( "s | " ) ; StringBuilder headerFormat = new StringBuilder ( ) ; headerFormat . append ( " %-" ) . append ( labelSize ) . append ( "s " ) ; for ( int i = 0 ; i < nClasses ; i ++ ) { sb . append ( "%7d" ) ; headerFormat . append ( "%7d" ) ; } String rowFormat = sb . toString ( ) ; StringBuilder out = new StringBuilder ( ) ; Object [ ] headerArgs = new Object [ nClasses + 1 ] ; headerArgs [ 0 ] = "Predicted:" ; for ( int i = 0 ; i < nClasses ; i ++ ) headerArgs [ i + 1 ] = i ; out . append ( String . format ( headerFormat . toString ( ) , headerArgs ) ) . append ( "\n" ) ; out . append ( " Actual:\n" ) ; for ( int i = 0 ; i < nClasses ; i ++ ) { Object [ ] args = new Object [ nClasses + 2 ] ; args [ 0 ] = i ; args [ 1 ] = labelsList . get ( i ) ; for ( int j = 0 ; j < nClasses ; j ++ ) { args [ j + 2 ] = confusion ( ) . getCount ( i , j ) ; } out . append ( String . format ( rowFormat , args ) ) ; out . append ( "\n" ) ; } return out . toString ( ) ; } | Get a String representation of the confusion matrix |
19,509 | public MultiLayerConfiguration getMultiLayerConfiguration ( ) throws InvalidKerasConfigurationException , UnsupportedKerasConfigurationException { if ( ! this . className . equals ( config . getFieldClassNameSequential ( ) ) ) throw new InvalidKerasConfigurationException ( "Keras model class name " + this . className + " incompatible with MultiLayerNetwork" ) ; if ( this . inputLayerNames . size ( ) != 1 ) throw new InvalidKerasConfigurationException ( "MultiLayerNetwork expects only 1 input (found " + this . inputLayerNames . size ( ) + ")" ) ; if ( this . outputLayerNames . size ( ) != 1 ) throw new InvalidKerasConfigurationException ( "MultiLayerNetwork expects only 1 output (found " + this . outputLayerNames . size ( ) + ")" ) ; NeuralNetConfiguration . Builder modelBuilder = new NeuralNetConfiguration . Builder ( ) ; if ( optimizer != null ) { modelBuilder . updater ( optimizer ) ; } NeuralNetConfiguration . ListBuilder listBuilder = modelBuilder . list ( ) ; KerasLayer prevLayer = null ; int layerIndex = 0 ; for ( KerasLayer layer : this . layersOrdered ) { if ( layer . isLayer ( ) ) { int nbInbound = layer . getInboundLayerNames ( ) . size ( ) ; if ( nbInbound != 1 ) throw new InvalidKerasConfigurationException ( "Layers in MultiLayerConfiguration must have exactly one inbound layer (found " + nbInbound + " for layer " + layer . getLayerName ( ) + ")" ) ; if ( prevLayer != null ) { InputType [ ] inputTypes = new InputType [ 1 ] ; InputPreProcessor preprocessor ; if ( prevLayer . isInputPreProcessor ( ) ) { inputTypes [ 0 ] = this . outputTypes . get ( prevLayer . getInboundLayerNames ( ) . get ( 0 ) ) ; preprocessor = prevLayer . getInputPreprocessor ( inputTypes ) ; } else { inputTypes [ 0 ] = this . outputTypes . get ( prevLayer . getLayerName ( ) ) ; preprocessor = layer . getInputPreprocessor ( inputTypes ) ; } if ( preprocessor != null ) listBuilder . inputPreProcessor ( layerIndex , preprocessor ) ; } listBuilder . layer ( layerIndex ++ , layer . getLayer ( ) ) ; } else if ( layer . getVertex ( ) != null ) throw new InvalidKerasConfigurationException ( "Cannot add vertex to MultiLayerConfiguration (class name " + layer . getClassName ( ) + ", layer name " + layer . getLayerName ( ) + ")" ) ; prevLayer = layer ; } InputType inputType = this . layersOrdered . get ( 0 ) . getOutputType ( ) ; if ( inputType != null ) listBuilder . setInputType ( inputType ) ; if ( this . useTruncatedBPTT && this . truncatedBPTT > 0 ) listBuilder . backpropType ( BackpropType . TruncatedBPTT ) . tBPTTForwardLength ( truncatedBPTT ) . tBPTTBackwardLength ( truncatedBPTT ) ; else listBuilder . backpropType ( BackpropType . Standard ) ; return listBuilder . build ( ) ; } | Configure a MultiLayerConfiguration from this Keras Sequential model configuration . |
19,510 | public MultiLayerNetwork getMultiLayerNetwork ( boolean importWeights ) throws InvalidKerasConfigurationException , UnsupportedKerasConfigurationException { MultiLayerNetwork model = new MultiLayerNetwork ( getMultiLayerConfiguration ( ) ) ; model . init ( ) ; if ( importWeights ) model = ( MultiLayerNetwork ) KerasModelUtils . copyWeightsToModel ( model , this . layers ) ; return model ; } | Build a MultiLayerNetwork from this Keras Sequential model configuration and import weights . |
19,511 | public long [ ] lookup ( int index ) { if ( exists [ index ] ) { return indexes [ index ] ; } else { exists [ index ] = true ; indexes [ index ] = ordering == 'c' ? Shape . ind2subC ( shape , index , numIndexes ) : Shape . ind2sub ( shape , index , numIndexes ) ; return indexes [ index ] ; } } | Give back a sub wrt the given linear index |
19,512 | public static Op . Type getTypeFromByte ( byte type ) { switch ( type ) { case OpType . SCALAR : return Op . Type . SCALAR ; case OpType . SCALAR_BOOL : return Op . Type . SCALAR_BOOL ; case OpType . BROADCAST : return Op . Type . BROADCAST ; case OpType . BROADCAST_BOOL : return Op . Type . BROADCAST_BOOL ; case OpType . TRANSFORM_BOOL : return Op . Type . TRANSFORM_BOOL ; case OpType . TRANSFORM_FLOAT : return Op . Type . TRANSFORM_FLOAT ; case OpType . TRANSFORM_SAME : return Op . Type . TRANSFORM_SAME ; case OpType . TRANSFORM_ANY : return Op . Type . TRANSFORM_ANY ; case OpType . TRANSFORM_STRICT : return Op . Type . TRANSFORM_STRICT ; case OpType . REDUCE_BOOL : return Op . Type . REDUCE_BOOL ; case OpType . REDUCE_LONG : return Op . Type . REDUCE_LONG ; case OpType . REDUCE_FLOAT : return Op . Type . REDUCE_FLOAT ; case OpType . REDUCE_SAME : return Op . Type . REDUCE_SAME ; case OpType . REDUCE_3 : return Op . Type . REDUCE3 ; case OpType . INDEX_REDUCE : return Op . Type . INDEXREDUCE ; case OpType . RANDOM : return Op . Type . RANDOM ; case OpType . LOGIC : return Op . Type . META ; case OpType . CUSTOM : return Op . Type . CUSTOM ; case OpType . PAIRWISE : return Op . Type . PAIRWISE ; case OpType . PAIRWISE_BOOL : return Op . Type . PAIRWISE_BOOL ; case OpType . SUMMARYSTATS : return Op . Type . SUMMARYSTATS ; default : throw new UnsupportedOperationException ( "Unknown op type passed in: " + type ) ; } } | This method converts enums for Op . Type |
19,513 | public static byte getFlatOpType ( Op . Type type ) { switch ( type ) { case SCALAR : return OpType . SCALAR ; case SCALAR_BOOL : return OpType . SCALAR_BOOL ; case BROADCAST : return OpType . BROADCAST ; case BROADCAST_BOOL : return OpType . BROADCAST_BOOL ; case TRANSFORM_BOOL : return OpType . TRANSFORM_BOOL ; case TRANSFORM_FLOAT : return OpType . TRANSFORM_FLOAT ; case TRANSFORM_SAME : return OpType . TRANSFORM_SAME ; case TRANSFORM_ANY : return OpType . TRANSFORM_ANY ; case TRANSFORM_STRICT : return OpType . TRANSFORM_STRICT ; case SPECIAL : return OpType . TRANSFORM_STRICT ; case VARIANCE : case REDUCE_FLOAT : return OpType . REDUCE_FLOAT ; case REDUCE_BOOL : return OpType . REDUCE_BOOL ; case REDUCE_SAME : return OpType . REDUCE_SAME ; case REDUCE_LONG : return OpType . REDUCE_LONG ; case REDUCE3 : return OpType . REDUCE_3 ; case INDEXREDUCE : return OpType . INDEX_REDUCE ; case RANDOM : return OpType . RANDOM ; case MERGE : case CONDITIONAL : case LOOP : case RETURN : case ENTER : case EXIT : case NEXT_ITERATION : case LOOP_COND : case IF : return OpType . LOGIC ; case CUSTOM : return OpType . CUSTOM ; case PAIRWISE : return OpType . PAIRWISE ; case PAIRWISE_BOOL : return OpType . PAIRWISE_BOOL ; case SUMMARYSTATS : return OpType . SUMMARYSTATS ; default : throw new UnsupportedOperationException ( "Unknown op type passed in: " + type ) ; } } | This method converts an Op . Type to it s corresponding byte value |
19,514 | public static ByteOrder getOrderFromByte ( byte val ) { if ( val == org . nd4j . graph . ByteOrder . LE ) return ByteOrder . LITTLE_ENDIAN ; else return ByteOrder . BIG_ENDIAN ; } | This method just converts enums |
19,515 | public static byte getOrderAsByte ( ) { if ( ByteOrder . nativeOrder ( ) . equals ( ByteOrder . BIG_ENDIAN ) ) return org . nd4j . graph . ByteOrder . BE ; else return org . nd4j . graph . ByteOrder . LE ; } | This method returns current byte order for this JVM as libnd4j enum |
19,516 | public static ByteBuffer toBuffer ( NDArrayMessageChunk chunk ) { ByteBuffer ret = ByteBuffer . allocateDirect ( sizeForMessage ( chunk ) ) . order ( ByteOrder . nativeOrder ( ) ) ; ret . putInt ( chunk . getMessageType ( ) . ordinal ( ) ) ; ret . putInt ( chunk . getNumChunks ( ) ) ; ret . putInt ( chunk . getChunkSize ( ) ) ; ret . putInt ( chunk . getId ( ) . getBytes ( ) . length ) ; ret . put ( chunk . getId ( ) . getBytes ( ) ) ; ret . putInt ( chunk . getChunkIndex ( ) ) ; ret . put ( chunk . getData ( ) ) ; return ret ; } | Convert an ndarray message chunk to a buffer . |
19,517 | public static List < String > tarGzListFiles ( File tarGzFile ) throws IOException { try ( TarArchiveInputStream tin = new TarArchiveInputStream ( new GZIPInputStream ( new BufferedInputStream ( new FileInputStream ( tarGzFile ) ) ) ) ) { ArchiveEntry entry ; List < String > out = new ArrayList < > ( ) ; while ( ( entry = tin . getNextTarEntry ( ) ) != null ) { String name = entry . getName ( ) ; out . add ( name ) ; } return out ; } } | List all of the files and directories in the specified tar . gz file |
19,518 | public static List < String > zipListFiles ( File zipFile ) throws IOException { List < String > out = new ArrayList < > ( ) ; try ( ZipFile zf = new ZipFile ( zipFile ) ) { Enumeration entries = zf . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry ze = ( ZipEntry ) entries . nextElement ( ) ; out . add ( ze . getName ( ) ) ; } } return out ; } | List all of the files and directories in the specified . zip file |
19,519 | public static void zipExtractSingleFile ( File zipFile , File destination , String pathInZip ) throws IOException { try ( ZipFile zf = new ZipFile ( zipFile ) ; InputStream is = new BufferedInputStream ( zf . getInputStream ( zf . getEntry ( pathInZip ) ) ) ; OutputStream os = new BufferedOutputStream ( new FileOutputStream ( destination ) ) ) { IOUtils . copy ( is , os ) ; } } | Extract a single file from a . zip file . Does not support directories |
19,520 | public static String validate ( OpTestCase testCase ) { collectCoverageInformation ( testCase ) ; List < LongShapeDescriptor > outShapes ; try { outShapes = Nd4j . getExecutioner ( ) . calculateOutputShape ( testCase . op ( ) ) ; } catch ( Throwable t ) { throw new IllegalStateException ( "Error calculating output shapes during op validation" , t ) ; } if ( outShapes . size ( ) != testCase . testFns ( ) . size ( ) ) { return "Expected number of output shapes and number of outputs differ. " + outShapes . size ( ) + " output shapes," + " but OpTestCase specifies " + testCase . testFns ( ) . size ( ) + " outputs expected" ; } for ( int i = 0 ; i < outShapes . size ( ) ; i ++ ) { val act = outShapes . get ( i ) ; val exp = testCase . expShapes ( ) . get ( i ) ; if ( ! Objects . equals ( exp . dataType ( ) , act . dataType ( ) ) ) { return "Shape function check failed for output " + i + ": expected shape " + exp + ", actual shape " + act ; } if ( ! Arrays . equals ( act . getShape ( ) , exp . getShape ( ) ) ) { return "Shape function check failed for output " + i + ": expected shape " + exp + ", actual shape " + act ; } } try { Nd4j . getExecutioner ( ) . execAndReturn ( testCase . op ( ) ) ; } catch ( Throwable t ) { throw new IllegalStateException ( "Error during op execution" , t ) ; } for ( int i = 0 ; i < testCase . testFns ( ) . size ( ) ; i ++ ) { String error ; try { error = testCase . testFns ( ) . get ( i ) . apply ( testCase . op ( ) . outputArguments ( ) [ i ] ) ; } catch ( Throwable t ) { throw new IllegalStateException ( "Exception thrown during op output validation for output " + i , t ) ; } if ( error != null ) { return "Output " + i + " failed: " + error ; } } return null ; } | Validate the outputs of a single op |
19,521 | private static Set < String > excludeFromTfImportCoverage ( ) { List < String > list = Arrays . asList ( "Reverse" , "LogSigmoid" , "HardSigmoid" , "SpaceToBatch" , "BatchToSpace" , "Pad" , "TopK" , "InTopK" , "BatchMatrixDeterminant" , "BatchMatrixDiagPart" , "BatchMatrixDiag" , "BatchMatrixBandPart" , "BatchMatrixInverse" , "BatchMatrixSetDiag" , "BatchMatrixSolve" , "BatchMatrixSolveLs" , "BatchMatrixTriangularSolve" , "BatchSelfAdjointEig" , "BatchSelfAdjointEigV2" , "BatchSvd" , "HardTanh" , "Swish" , "RDiv" , "DivScalar" , "LogX" , "RationalTanh" , "absargmax" , "absargmin" , "entropy_shannon" , "count_zero" ) ; return new HashSet < > ( list ) ; } | These ops are excluded from TF import test coverage for various reasons |
19,522 | public static MultiDataSet toMultiDataSet ( DataSet dataSet ) { INDArray f = dataSet . getFeatures ( ) ; INDArray l = dataSet . getLabels ( ) ; INDArray fMask = dataSet . getFeaturesMaskArray ( ) ; INDArray lMask = dataSet . getLabelsMaskArray ( ) ; INDArray [ ] fNew = f == null ? null : new INDArray [ ] { f } ; INDArray [ ] lNew = l == null ? null : new INDArray [ ] { l } ; INDArray [ ] fMaskNew = ( fMask != null ? new INDArray [ ] { fMask } : null ) ; INDArray [ ] lMaskNew = ( lMask != null ? new INDArray [ ] { lMask } : null ) ; return new org . nd4j . linalg . dataset . MultiDataSet ( fNew , lNew , fMaskNew , lMaskNew ) ; } | Convert a DataSet to the equivalent MultiDataSet |
19,523 | public static Pair < WeightInit , Distribution > getWeightInitFromConfig ( Map < String , Object > layerConfig , String initField , boolean enforceTrainingConfig , KerasLayerConfiguration conf , int kerasMajorVersion ) throws InvalidKerasConfigurationException , UnsupportedKerasConfigurationException { Map < String , Object > innerConfig = KerasLayerUtils . getInnerLayerConfigFromConfig ( layerConfig , conf ) ; if ( ! innerConfig . containsKey ( initField ) ) throw new InvalidKerasConfigurationException ( "Keras layer is missing " + initField + " field" ) ; String kerasInit ; Map < String , Object > initMap ; if ( kerasMajorVersion != 2 ) { kerasInit = ( String ) innerConfig . get ( initField ) ; initMap = innerConfig ; } else { @ SuppressWarnings ( "unchecked" ) Map < String , Object > fullInitMap = ( HashMap ) innerConfig . get ( initField ) ; initMap = ( HashMap ) fullInitMap . get ( "config" ) ; if ( fullInitMap . containsKey ( "class_name" ) ) { kerasInit = ( String ) fullInitMap . get ( "class_name" ) ; } else { throw new UnsupportedKerasConfigurationException ( "Incomplete initialization class" ) ; } } Pair < WeightInit , Distribution > init ; try { init = mapWeightInitialization ( kerasInit , conf , initMap , kerasMajorVersion ) ; } catch ( UnsupportedKerasConfigurationException e ) { if ( enforceTrainingConfig ) throw e ; else { init = new Pair < > ( WeightInit . XAVIER , null ) ; log . warn ( "Unknown weight initializer " + kerasInit + " (Using XAVIER instead)." ) ; } } return init ; } | Get weight initialization from Keras layer configuration . |
19,524 | protected void shardMessageHandler ( DirectBuffer buffer , int offset , int length , Header header ) { byte [ ] data = new byte [ length ] ; buffer . getBytes ( offset , data ) ; VoidMessage message = VoidMessage . fromBytes ( data ) ; if ( message . getMessageType ( ) == 7 ) { messages . add ( message ) ; } else { publicationForShards . offer ( buffer , offset , length ) ; } } | This message handler is responsible for receiving messages on Shard side |
19,525 | protected void internalMessageHandler ( DirectBuffer buffer , int offset , int length , Header header ) { byte [ ] data = new byte [ length ] ; buffer . getBytes ( offset , data ) ; VoidMessage message = VoidMessage . fromBytes ( data ) ; messages . add ( message ) ; } | This message handler is responsible for receiving coordination messages on Shard side |
19,526 | protected void clientMessageHandler ( DirectBuffer buffer , int offset , int length , Header header ) { byte [ ] data = new byte [ length ] ; buffer . getBytes ( offset , data ) ; MeaningfulMessage message = ( MeaningfulMessage ) VoidMessage . fromBytes ( data ) ; completed . put ( message . getTaskId ( ) , message ) ; } | This message handler is responsible for receiving messages on Client side |
19,527 | public void init ( VoidConfiguration voidConfiguration , Clipboard clipboard , NodeRole role , String localIp , int localPort , short shardIndex ) { } | This method does initialization of Transport instance |
19,528 | public void shutdown ( ) { runner . set ( false ) ; try { threadA . join ( ) ; if ( threadB != null ) threadB . join ( ) ; } catch ( Exception e ) { } CloseHelper . quietClose ( driver ) ; try { Thread . sleep ( 500 ) ; } catch ( Exception e ) { } } | This method stops transport system . |
19,529 | public void receiveMessage ( VoidMessage message ) { try { log . info ( "Message received, saving..." ) ; messages . put ( message ) ; } catch ( Exception e ) { } } | This method saves incoming message to the Queue for later dispatch from higher - level code like actual TrainingFunction or VoidParameterServer itself |
19,530 | public VoidMessage takeMessage ( ) { if ( threadingModel != ThreadingModel . SAME_THREAD ) { try { return messages . take ( ) ; } catch ( InterruptedException e ) { return null ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else { if ( subscriptionForShards != null ) subscriptionForShards . poll ( messageHandlerForShards , 512 ) ; subscriptionForClients . poll ( messageHandlerForClients , 512 ) ; return messages . poll ( ) ; } } | This method takes 1 message from incoming messages queue blocking if queue is empty |
19,531 | protected synchronized void sendCommandToShard ( VoidMessage message ) { if ( nodeRole == NodeRole . SHARD ) { message . setTargetId ( shardIndex ) ; messages . add ( message ) ; return ; } message . setTargetId ( targetIndex ) ; DirectBuffer buffer = message . asUnsafeBuffer ( ) ; long result = publicationForShards . offer ( buffer ) ; if ( result < 0 ) for ( int i = 0 ; i < 5 && result < 0 ; i ++ ) { try { Thread . sleep ( 1000 ) ; } catch ( Exception e ) { } result = publicationForShards . offer ( buffer ) ; } if ( result < 0 ) throw new RuntimeException ( "Unable to send message over the wire. Error code: " + result ) ; } | This command is possible to issue only from Client |
19,532 | public Long getTrackingPoint ( ) { if ( underlyingDataBuffer ( ) != this ) return underlyingDataBuffer ( ) == null ? trackingPoint : underlyingDataBuffer ( ) . getTrackingPoint ( ) ; return trackingPoint ; } | Returns tracking point for Allocator |
19,533 | protected QLStepReturn < O > trainStep ( O obs ) { Integer action ; INDArray input = getInput ( obs ) ; boolean isHistoryProcessor = getHistoryProcessor ( ) != null ; if ( isHistoryProcessor ) getHistoryProcessor ( ) . record ( input ) ; int skipFrame = isHistoryProcessor ? getHistoryProcessor ( ) . getConf ( ) . getSkipFrame ( ) : 1 ; int historyLength = isHistoryProcessor ? getHistoryProcessor ( ) . getConf ( ) . getHistoryLength ( ) : 1 ; int updateStart = getConfiguration ( ) . getUpdateStart ( ) + ( ( getConfiguration ( ) . getBatchSize ( ) + historyLength ) * skipFrame ) ; Double maxQ = Double . NaN ; if ( getStepCounter ( ) % skipFrame != 0 ) { action = lastAction ; } else { if ( history == null ) { if ( isHistoryProcessor ) { getHistoryProcessor ( ) . add ( input ) ; history = getHistoryProcessor ( ) . getHistory ( ) ; } else history = new INDArray [ ] { input } ; } INDArray hstack = Transition . concat ( Transition . dup ( history ) ) ; if ( isHistoryProcessor ) { hstack . muli ( 1.0 / getHistoryProcessor ( ) . getScale ( ) ) ; } if ( hstack . shape ( ) . length > 2 ) hstack = hstack . reshape ( Learning . makeShape ( 1 , ArrayUtil . toInts ( hstack . shape ( ) ) ) ) ; INDArray qs = getCurrentDQN ( ) . output ( hstack ) ; int maxAction = Learning . getMaxAction ( qs ) ; maxQ = qs . getDouble ( maxAction ) ; action = getEgPolicy ( ) . nextAction ( hstack ) ; } lastAction = action ; StepReply < O > stepReply = getMdp ( ) . step ( action ) ; accuReward += stepReply . getReward ( ) * configuration . getRewardFactor ( ) ; if ( getStepCounter ( ) % skipFrame == 0 || stepReply . isDone ( ) ) { INDArray ninput = getInput ( stepReply . getObservation ( ) ) ; if ( isHistoryProcessor ) getHistoryProcessor ( ) . add ( ninput ) ; INDArray [ ] nhistory = isHistoryProcessor ? getHistoryProcessor ( ) . getHistory ( ) : new INDArray [ ] { ninput } ; Transition < Integer > trans = new Transition ( history , action , accuReward , stepReply . isDone ( ) , nhistory [ 0 ] ) ; getExpReplay ( ) . store ( trans ) ; if ( getStepCounter ( ) > updateStart ) { Pair < INDArray , INDArray > targets = setTarget ( getExpReplay ( ) . getBatch ( ) ) ; getCurrentDQN ( ) . fit ( targets . getFirst ( ) , targets . getSecond ( ) ) ; } history = nhistory ; accuReward = 0 ; } return new QLStepReturn < O > ( maxQ , getCurrentDQN ( ) . getLatestScore ( ) , stepReply ) ; } | Single step of training |
19,534 | public String nextToken ( ) { if ( ! tokens . isEmpty ( ) && position . get ( ) < tokens . size ( ) ) return tokens . get ( position . getAndIncrement ( ) ) ; return nextTokenFromStream ( ) ; } | This method returns next token from prebuffered list of tokens or underlying InputStream |
19,535 | private List < List < Writable > > filterRequiredColumns ( String readerName , List < List < Writable > > list ) { boolean entireReader = false ; List < SubsetDetails > subsetList = null ; int max = - 1 ; int min = Integer . MAX_VALUE ; for ( List < SubsetDetails > sdList : Arrays . asList ( inputs , outputs ) ) { for ( SubsetDetails sd : sdList ) { if ( readerName . equals ( sd . readerName ) ) { if ( sd . entireReader ) { entireReader = true ; break ; } else { if ( subsetList == null ) { subsetList = new ArrayList < > ( ) ; } subsetList . add ( sd ) ; max = Math . max ( max , sd . subsetEndInclusive ) ; min = Math . min ( min , sd . subsetStart ) ; } } } } if ( entireReader ) { return list ; } else if ( subsetList == null ) { throw new IllegalStateException ( "Found no usages of reader: " + readerName ) ; } else { boolean [ ] req = new boolean [ max + 1 ] ; for ( SubsetDetails sd : subsetList ) { for ( int i = sd . subsetStart ; i <= sd . subsetEndInclusive ; i ++ ) { req [ i ] = true ; } } List < List < Writable > > out = new ArrayList < > ( ) ; IntWritable zero = new IntWritable ( 0 ) ; for ( List < Writable > l : list ) { List < Writable > lNew = new ArrayList < > ( l . size ( ) ) ; for ( int i = 0 ; i < l . size ( ) ; i ++ ) { if ( i >= req . length || ! req [ i ] ) { lNew . add ( zero ) ; } else { lNew . add ( l . get ( i ) ) ; } } out . add ( lNew ) ; } return out ; } } | Filter out the required columns before conversion . This is to avoid trying to convert String etc columns |
19,536 | public void preProcess ( DataSet toPreProcess ) { for ( DataSetPreProcessor preProcessor : preProcessors ) { preProcessor . preProcess ( toPreProcess ) ; } } | Pre process a dataset sequentially |
19,537 | private Result getModelLastUpdateTimes ( String modelIDs ) { if ( currentSessionID == null ) { return ok ( ) ; } StatsStorage ss = knownSessionIDs . get ( currentSessionID ) ; if ( ss == null ) { log . debug ( "getModelLastUpdateTimes(): Session ID is unknown: {}" , currentSessionID ) ; return ok ( "-1" ) ; } String [ ] split = modelIDs . split ( "," ) ; long [ ] lastUpdateTimes = new long [ split . length ] ; for ( int i = 0 ; i < split . length ; i ++ ) { String s = split [ i ] ; Persistable p = ss . getLatestUpdate ( currentSessionID , ARBITER_UI_TYPE_ID , s ) ; if ( p != null ) { lastUpdateTimes [ i ] = p . getTimeStamp ( ) ; } } return ok ( Json . toJson ( lastUpdateTimes ) ) ; } | Get the last update time for the specified model IDs |
19,538 | public static int [ ] get3DSameModeTopLeftPadding ( int [ ] outSize , int [ ] inSize , int [ ] kernel , int [ ] strides , int [ ] dilation ) { int [ ] eKernel = effectiveKernelSize ( kernel , dilation ) ; int [ ] outPad = new int [ 3 ] ; outPad [ 0 ] = ( ( outSize [ 0 ] - 1 ) * strides [ 0 ] + eKernel [ 0 ] - inSize [ 0 ] ) / 2 ; outPad [ 1 ] = ( ( outSize [ 1 ] - 1 ) * strides [ 1 ] + eKernel [ 1 ] - inSize [ 1 ] ) / 2 ; outPad [ 2 ] = ( ( outSize [ 2 ] - 1 ) * strides [ 2 ] + eKernel [ 2 ] - inSize [ 2 ] ) / 2 ; return outPad ; } | Get top and left padding for same mode only for 3d convolutions |
19,539 | public void purgeBuffers ( ) { log . info ( "Purging TAD buffers..." ) ; tadCache = new ArrayList < > ( ) ; int numDevices = Nd4j . getAffinityManager ( ) . getNumberOfDevices ( ) ; for ( int i = 0 ; i < numDevices ; i ++ ) { log . info ( "Resetting device: [{}]" , i ) ; tadCache . add ( i , new ConcurrentHashMap < TadDescriptor , Pair < DataBuffer , DataBuffer > > ( ) ) ; } super . purgeBuffers ( ) ; } | This method removes all cached shape buffers |
19,540 | public int getLayerSize ( ) { if ( lookupTable != null && lookupTable . getWeights ( ) != null ) { return lookupTable . getWeights ( ) . columns ( ) ; } else return layerSize ; } | This method returns word vector size |
19,541 | public INDArray getWordVectorMatrixNormalized ( String word ) { INDArray r = getWordVectorMatrix ( word ) ; if ( r == null ) return null ; return r . div ( Nd4j . getBlasWrapper ( ) . nrm2 ( r ) ) ; } | Returns the word vector divided by the norm2 of the array |
19,542 | protected void save ( Model model , String filename ) { try { ModelSerializer . writeModel ( model , filename , true ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | This method saves model |
19,543 | protected QuadTree findIndex ( INDArray coordinates ) { boolean left = ( coordinates . getDouble ( 0 ) <= ( boundary . getX ( ) + boundary . getHw ( ) / 2 ) ) ; boolean top = ( coordinates . getDouble ( 1 ) <= ( boundary . getY ( ) + boundary . getHh ( ) / 2 ) ) ; QuadTree index = getNorthWest ( ) ; if ( left ) { if ( ! top ) { index = getSouthWest ( ) ; } } else { if ( top ) { index = getNorthEast ( ) ; } else { index = getSouthEast ( ) ; } } return index ; } | Returns the cell of this element |
19,544 | public boolean insert ( int newIndex ) { INDArray point = data . slice ( newIndex ) ; if ( ! boundary . containsPoint ( point ) ) return false ; cumSize ++ ; double mult1 = ( double ) ( cumSize - 1 ) / ( double ) cumSize ; double mult2 = 1.0 / ( double ) cumSize ; centerOfMass . muli ( mult1 ) ; centerOfMass . addi ( point . mul ( mult2 ) ) ; if ( isLeaf ( ) && size < QT_NODE_CAPACITY ) { index [ size ] = newIndex ; size ++ ; return true ; } if ( size > 0 ) { for ( int i = 0 ; i < size ; i ++ ) { INDArray compPoint = data . slice ( index [ i ] ) ; if ( point . getDouble ( 0 ) == compPoint . getDouble ( 0 ) && point . getDouble ( 1 ) == compPoint . getDouble ( 1 ) ) return true ; } } if ( ! isLeaf ( ) ) { QuadTree index = findIndex ( point ) ; index . insert ( newIndex ) ; return true ; } if ( isLeaf ( ) ) subDivide ( ) ; boolean ret = insertIntoOneOf ( newIndex ) ; return ret ; } | Insert an index of the data in to the tree |
19,545 | public boolean isCorrect ( ) { for ( int n = 0 ; n < size ; n ++ ) { INDArray point = data . slice ( index [ n ] ) ; if ( ! boundary . containsPoint ( point ) ) return false ; } return isLeaf ( ) || northWest . isCorrect ( ) && northEast . isCorrect ( ) && southWest . isCorrect ( ) && southEast . isCorrect ( ) ; } | Returns whether the tree is consistent or not |
19,546 | public void subDivide ( ) { northWest = new QuadTree ( this , data , new Cell ( boundary . getX ( ) - .5 * boundary . getHw ( ) , boundary . getY ( ) - .5 * boundary . getHh ( ) , .5 * boundary . getHw ( ) , .5 * boundary . getHh ( ) ) ) ; northEast = new QuadTree ( this , data , new Cell ( boundary . getX ( ) + .5 * boundary . getHw ( ) , boundary . getY ( ) - .5 * boundary . getHh ( ) , .5 * boundary . getHw ( ) , .5 * boundary . getHh ( ) ) ) ; southWest = new QuadTree ( this , data , new Cell ( boundary . getX ( ) - .5 * boundary . getHw ( ) , boundary . getY ( ) + .5 * boundary . getHh ( ) , .5 * boundary . getHw ( ) , .5 * boundary . getHh ( ) ) ) ; southEast = new QuadTree ( this , data , new Cell ( boundary . getX ( ) + .5 * boundary . getHw ( ) , boundary . getY ( ) + .5 * boundary . getHh ( ) , .5 * boundary . getHw ( ) , .5 * boundary . getHh ( ) ) ) ; } | Create four children which fully divide this cell into four quads of equal area |
19,547 | public int depth ( ) { if ( isLeaf ( ) ) return 1 ; return 1 + max ( max ( northWest . depth ( ) , northEast . depth ( ) ) , max ( southWest . depth ( ) , southEast . depth ( ) ) ) ; } | The depth of the node |
19,548 | public static long [ ] getMaxShape ( INDArray ... inputs ) { if ( inputs == null ) return null ; else if ( inputs . length < 2 ) return inputs [ 0 ] . shape ( ) ; else { long [ ] currMax = inputs [ 0 ] . shape ( ) ; for ( int i = 1 ; i < inputs . length ; i ++ ) { if ( inputs [ i ] == null ) { continue ; } if ( ArrayUtil . prod ( currMax ) < inputs [ i ] . length ( ) ) { currMax = inputs [ i ] . shape ( ) ; } } return currMax ; } } | Return the shape of the largest length array based on the input |
19,549 | public static boolean isPlaceholderShape ( int [ ] shape ) { if ( shape == null ) return true ; else { for ( int i = 0 ; i < shape . length ; i ++ ) { if ( shape [ i ] < 0 ) return true ; } } return false ; } | Returns true if any shape has a - 1 or a null or empty array is passed in |
19,550 | public static long [ ] getReducedShape ( int [ ] wholeShape , int [ ] dimensions ) { if ( isWholeArray ( wholeShape , dimensions ) ) return new long [ ] { } ; else if ( dimensions . length == 1 && wholeShape . length == 2 ) { val ret = new long [ 2 ] ; if ( dimensions [ 0 ] == 1 ) { ret [ 0 ] = wholeShape [ 0 ] ; ret [ 1 ] = 1 ; } else if ( dimensions [ 0 ] == 0 ) { ret [ 0 ] = 1 ; ret [ 1 ] = wholeShape [ 1 ] ; } return ret ; } return ArrayUtil . toLongArray ( ArrayUtil . removeIndex ( wholeShape , dimensions ) ) ; } | Get the shape of the reduced array |
19,551 | public static int [ ] getMatrixMultiplyShape ( int [ ] left , int [ ] right ) { if ( Shape . shapeIsScalar ( left ) ) { return right ; } if ( Shape . shapeIsScalar ( right ) ) { return left ; } if ( left . length != 2 && right . length != 2 ) { throw new IllegalArgumentException ( "Illegal shapes for matrix multiply. Must be of length 2. Left shape: " + Arrays . toString ( left ) + ", right shape: " + Arrays . toString ( right ) ) ; } for ( int i = 0 ; i < left . length ; i ++ ) { if ( left [ i ] < 1 ) throw new ND4JIllegalStateException ( "Left shape contained value < 0 at index " + i + " - left shape " + Arrays . toString ( left ) ) ; } for ( int i = 0 ; i < right . length ; i ++ ) { if ( right [ i ] < 1 ) throw new ND4JIllegalStateException ( "Right shape contained value < 0 at index " + i + " - right shape " + Arrays . toString ( right ) ) ; } if ( left . length > 1 && left [ 1 ] != right [ 0 ] ) throw new IllegalArgumentException ( "Columns of left not equal to rows of right: left shape " + Arrays . toString ( left ) + ", right shape " + Arrays . toString ( right ) ) ; if ( left . length < right . length ) { if ( left [ 0 ] == right [ 0 ] ) { return new int [ ] { 1 , right [ 1 ] } ; } } int [ ] shape = { left [ 0 ] , right [ 1 ] } ; return shape ; } | Get the output shape of a matrix multiply |
19,552 | public static INDArray toOffsetZero ( INDArray arr ) { if ( arr . offset ( ) < 1 && arr . data ( ) . length ( ) == arr . length ( ) ) if ( arr . ordering ( ) == 'f' && arr . stride ( - 1 ) != 1 || arr . ordering ( ) == 'c' && arr . stride ( 0 ) != 1 ) return arr ; if ( arr . isRowVector ( ) ) { INDArray ret = Nd4j . create ( arr . shape ( ) ) ; for ( int i = 0 ; i < ret . length ( ) ; i ++ ) ret . putScalar ( i , arr . getDouble ( i ) ) ; return ret ; } INDArray ret = Nd4j . create ( arr . shape ( ) , arr . ordering ( ) ) ; ret . assign ( arr ) ; return ret ; } | Create a copy of the matrix where the new offset is zero |
19,553 | public static double getDouble ( INDArray arr , int [ ] indices ) { long offset = getOffset ( arr . shapeInfo ( ) , ArrayUtil . toLongArray ( indices ) ) ; return arr . data ( ) . getDouble ( offset ) ; } | Get a double based on the array and given indices |
19,554 | public static void iterate ( int dimension , int n , int [ ] size , int [ ] res , int dimension2 , int n2 , int [ ] size2 , int [ ] res2 , CoordinateFunction func ) { if ( dimension >= n || dimension2 >= n2 ) { func . process ( ArrayUtil . toLongArray ( res ) , ArrayUtil . toLongArray ( res2 ) ) ; return ; } if ( size2 . length != size . length ) { if ( dimension >= size . length ) return ; for ( int i = 0 ; i < size [ dimension ] ; i ++ ) { if ( dimension2 >= size2 . length ) break ; for ( int j = 0 ; j < size2 [ dimension2 ] ; j ++ ) { res [ dimension ] = i ; res2 [ dimension2 ] = j ; iterate ( dimension + 1 , n , size , res , dimension2 + 1 , n2 , size2 , res2 , func ) ; } } } else { if ( dimension >= size . length ) return ; for ( int i = 0 ; i < size [ dimension ] ; i ++ ) { for ( int j = 0 ; j < size2 [ dimension2 ] ; j ++ ) { if ( dimension2 >= size2 . length ) break ; res [ dimension ] = i ; res2 [ dimension2 ] = j ; iterate ( dimension + 1 , n , size , res , dimension2 + 1 , n2 , size2 , res2 , func ) ; } } } } | Iterate over a pair of coordinates |
19,555 | public static long getOffset ( long baseOffset , int [ ] shape , int [ ] stride , int ... indices ) { if ( shape . length != stride . length || indices . length != shape . length ) throw new IllegalArgumentException ( "Indexes, shape, and stride must be the same length" ) ; long offset = baseOffset ; for ( int i = 0 ; i < shape . length ; i ++ ) { if ( indices [ i ] >= shape [ i ] ) throw new IllegalArgumentException ( String . format ( "J: Index [%d] must not be >= shape[%d]=%d." , i , i , shape [ i ] ) ) ; if ( shape [ i ] != 1 ) { offset += indices [ i ] * stride [ i ] ; } } return offset ; } | Get an offset for retrieval from a data buffer based on the given shape stride and given indices |
19,556 | public static int [ ] sizeForAxes ( int [ ] axes , int [ ] shape ) { int [ ] ret = new int [ shape . length ] ; for ( int i = 0 ; i < axes . length ; i ++ ) { ret [ i ] = shape [ axes [ i ] ] ; } return ret ; } | Output an int array for a particular dimension |
19,557 | public static boolean shapeEquals ( int [ ] shape1 , int [ ] shape2 ) { if ( isColumnVectorShape ( shape1 ) && isColumnVectorShape ( shape2 ) ) { return Arrays . equals ( shape1 , shape2 ) ; } if ( isRowVectorShape ( shape1 ) && isRowVectorShape ( shape2 ) ) { int [ ] shape1Comp = squeeze ( shape1 ) ; int [ ] shape2Comp = squeeze ( shape2 ) ; return Arrays . equals ( shape1Comp , shape2Comp ) ; } if ( shape1 . length == 0 || shape2 . length == 0 ) { if ( shape1 . length == 0 && shapeIsScalar ( shape2 ) ) { return true ; } if ( shape2 . length == 0 && shapeIsScalar ( shape1 ) ) { return true ; } } shape1 = squeeze ( shape1 ) ; shape2 = squeeze ( shape2 ) ; return scalarEquals ( shape1 , shape2 ) || Arrays . equals ( shape1 , shape2 ) ; } | Returns whether 2 shapes are equals by checking for dimension semantics as well as array equality |
19,558 | public static char getOrder ( int [ ] shape , int [ ] stride , int elementStride ) { int sd ; int dim ; int i ; boolean cContiguous = true ; boolean isFortran = true ; sd = 1 ; for ( i = shape . length - 1 ; i >= 0 ; -- i ) { dim = shape [ i ] ; if ( stride [ i ] != sd ) { cContiguous = false ; break ; } if ( dim == 0 ) { break ; } sd *= dim ; } sd = elementStride ; for ( i = 0 ; i < shape . length ; ++ i ) { dim = shape [ i ] ; if ( stride [ i ] != sd ) { isFortran = false ; } if ( dim == 0 ) { break ; } sd *= dim ; } if ( isFortran && cContiguous ) return 'a' ; else if ( isFortran && ! cContiguous ) return 'f' ; else if ( ! isFortran && ! cContiguous ) return 'c' ; else return 'c' ; } | Infer order from |
19,559 | public static int [ ] ind2subC ( int [ ] shape , long index , long numIndices ) { long denom = numIndices ; int [ ] ret = new int [ shape . length ] ; for ( int i = 0 ; i < shape . length ; i ++ ) { denom /= shape [ i ] ; if ( index / denom >= Integer . MAX_VALUE ) throw new IllegalArgumentException ( "Dimension can not be >= Integer.MAX_VALUE" ) ; ret [ i ] = ( int ) ( index / denom ) ; index %= denom ; } return ret ; } | Convert a linear index to the equivalent nd index |
19,560 | public static IntBuffer stride ( IntBuffer buffer ) { int rank = rank ( buffer ) ; val buffer2 = ( Buffer ) buffer ; val ret = ( IntBuffer ) buffer2 . position ( 1 + rank ) ; return ret . slice ( ) ; } | Get the stride for the given shape information buffer |
19,561 | public static String shapeToString ( IntBuffer buffer ) { val shapeBuff = shapeOf ( buffer ) ; int rank = Shape . rank ( buffer ) ; val strideBuff = stride ( buffer ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Rank: " + rank + "," ) ; sb . append ( "Offset: " + Shape . offset ( buffer ) + "\n" ) ; sb . append ( " Order: " + Shape . order ( buffer ) ) ; sb . append ( " Shape: [" ) ; for ( int i = 0 ; i < rank ; i ++ ) { sb . append ( shapeBuff . get ( i ) ) ; if ( i < rank - 1 ) sb . append ( "," ) ; } sb . append ( "], " ) ; sb . append ( " stride: [" ) ; for ( int i = 0 ; i < rank ; i ++ ) { sb . append ( strideBuff . get ( i ) ) ; if ( i < rank - 1 ) sb . append ( "," ) ; } sb . append ( "]" ) ; return sb . toString ( ) ; } | Prints the shape for this shape information |
19,562 | public static DataBuffer createShapeInformation ( int [ ] shape , int [ ] stride , long offset , int elementWiseStride , char order ) { if ( shape . length != stride . length ) throw new IllegalStateException ( "Shape and stride must be the same length" ) ; int rank = shape . length ; int shapeBuffer [ ] = new int [ rank * 2 + 4 ] ; shapeBuffer [ 0 ] = rank ; int count = 1 ; for ( int e = 0 ; e < shape . length ; e ++ ) shapeBuffer [ count ++ ] = shape [ e ] ; for ( int e = 0 ; e < stride . length ; e ++ ) shapeBuffer [ count ++ ] = stride [ e ] ; shapeBuffer [ count ++ ] = ( int ) offset ; shapeBuffer [ count ++ ] = elementWiseStride ; shapeBuffer [ count ] = ( int ) order ; DataBuffer ret = Nd4j . createBufferDetached ( shapeBuffer ) ; ret . setConstant ( true ) ; return ret ; } | Creates the shape information buffer given the shape stride |
19,563 | public static IntBuffer toBuffer ( int ... arr ) { ByteBuffer directBuffer = ByteBuffer . allocateDirect ( arr . length * 4 ) . order ( ByteOrder . nativeOrder ( ) ) ; IntBuffer buffer = directBuffer . asIntBuffer ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) buffer . put ( i , arr [ i ] ) ; return buffer ; } | Convert an array to a byte buffer |
19,564 | public static boolean wholeArrayDimension ( int ... arr ) { return arr == null || arr . length == 0 || ( arr . length == 1 && arr [ 0 ] == Integer . MAX_VALUE ) ; } | Returns true if the given array is meant for the whole dimension |
19,565 | public static boolean isContiguousInBuffer ( INDArray in ) { long length = in . length ( ) ; long dLength = in . data ( ) . length ( ) ; if ( length == dLength ) return true ; char order = in . ordering ( ) ; long [ ] shape = in . shape ( ) ; long [ ] stridesIfContiguous ; if ( order == 'f' ) { stridesIfContiguous = ArrayUtil . calcStridesFortran ( shape ) ; } else if ( order == 'c' ) { stridesIfContiguous = ArrayUtil . calcStrides ( shape ) ; } else if ( order == 'a' ) { stridesIfContiguous = new long [ ] { 1 , 1 } ; } else { throw new RuntimeException ( "Invalid order: not c or f (is: " + order + ")" ) ; } return Arrays . equals ( in . stride ( ) , stridesIfContiguous ) ; } | Are the elements in the buffer contiguous for this NDArray? |
19,566 | public static INDArray toMmulCompatible ( INDArray input ) { if ( input . rank ( ) != 2 ) throw new IllegalArgumentException ( "Input must be rank 2 (matrix)" ) ; boolean doCopy = false ; if ( input . ordering ( ) == 'c' && ( input . stride ( 0 ) != input . size ( 1 ) || input . stride ( 1 ) != 1 ) ) doCopy = true ; else if ( input . ordering ( ) == 'f' && ( input . stride ( 0 ) != 1 || input . stride ( 1 ) != input . size ( 0 ) ) ) doCopy = true ; if ( doCopy ) return Shape . toOffsetZeroCopyAnyOrder ( input ) ; else return input ; } | This method is used in DL4J LSTM implementation |
19,567 | public static long [ ] reductionShape ( INDArray x , int [ ] dimension , boolean newFormat , boolean keepDims ) { boolean wholeArray = Shape . wholeArrayDimension ( dimension ) || dimension . length == x . rank ( ) ; long [ ] retShape ; if ( ! newFormat ) { retShape = wholeArray ? new long [ ] { 1 , 1 } : ArrayUtil . removeIndex ( x . shape ( ) , dimension ) ; if ( retShape . length == 1 ) { if ( dimension [ 0 ] == 0 ) retShape = new long [ ] { 1 , retShape [ 0 ] } ; else retShape = new long [ ] { retShape [ 0 ] , 1 } ; } else if ( retShape . length == 0 ) { retShape = new long [ ] { 1 , 1 } ; } } else { if ( keepDims ) { retShape = x . shape ( ) . clone ( ) ; if ( wholeArray ) { for ( int i = 0 ; i < retShape . length ; i ++ ) { retShape [ i ] = 1 ; } } else { for ( int d : dimension ) { retShape [ d ] = 1 ; } } } else { retShape = wholeArray ? new long [ 0 ] : ArrayUtil . removeIndex ( x . shape ( ) , dimension ) ; } } return retShape ; } | Calculate the shape of the returned array for a reduction along dimension |
19,568 | public static NavigableMap < String , Integer > loadVocab ( InputStream is ) throws IOException { final TreeMap < String , Integer > map = new TreeMap < > ( Collections . reverseOrder ( ) ) ; try ( final BufferedReader reader = new BufferedReader ( new InputStreamReader ( is ) ) ) { String token ; int i = 0 ; while ( ( token = reader . readLine ( ) ) != null ) { map . put ( token , i ++ ) ; } } return map ; } | The expected format is a \ n seperated list of tokens for examples |
19,569 | public static Nd4jBackend load ( ) throws NoAvailableBackendException { List < Nd4jBackend > backends = new ArrayList < > ( 1 ) ; ServiceLoader < Nd4jBackend > loader = ServiceLoader . load ( Nd4jBackend . class ) ; try { Iterator < Nd4jBackend > backendIterator = loader . iterator ( ) ; while ( backendIterator . hasNext ( ) ) backends . add ( backendIterator . next ( ) ) ; } catch ( ServiceConfigurationError serviceError ) { throw new RuntimeException ( "failed to process available backends" , serviceError ) ; } Collections . sort ( backends , new Comparator < Nd4jBackend > ( ) { public int compare ( Nd4jBackend o1 , Nd4jBackend o2 ) { return o2 . getPriority ( ) - o1 . getPriority ( ) ; } } ) ; for ( Nd4jBackend backend : backends ) { boolean available = false ; String error = null ; try { available = backend . isAvailable ( ) ; } catch ( Exception e ) { error = e . getMessage ( ) ; } if ( ! available ) { log . warn ( "Skipped [{}] backend (unavailable): {}" , backend . getClass ( ) . getSimpleName ( ) , error ) ; continue ; } try { Nd4jContext . getInstance ( ) . updateProperties ( backend . getConfigurationResource ( ) . getInputStream ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } log . info ( "Loaded [{}] backend" , backend . getClass ( ) . getSimpleName ( ) ) ; return backend ; } String [ ] jarUris ; if ( System . getProperties ( ) . containsKey ( ND4JSystemProperties . DYNAMIC_LOAD_CLASSPATH_PROPERTY ) && ! triedDynamicLoad ) { jarUris = System . getProperties ( ) . getProperty ( ND4JSystemProperties . DYNAMIC_LOAD_CLASSPATH_PROPERTY ) . split ( ";" ) ; } else if ( System . getenv ( ND4JEnvironmentVars . BACKEND_DYNAMIC_LOAD_CLASSPATH ) != null && ! triedDynamicLoad ) { jarUris = System . getenv ( ND4JEnvironmentVars . BACKEND_DYNAMIC_LOAD_CLASSPATH ) . split ( ";" ) ; } else throw new NoAvailableBackendException ( "Please ensure that you have an nd4j backend on your classpath. Please see: http://nd4j.org/getstarted.html" ) ; triedDynamicLoad = true ; for ( String uri : jarUris ) { loadLibrary ( new File ( uri ) ) ; } return load ( ) ; } | Loads the best available backend . |
19,570 | public static synchronized void loadLibrary ( File jar ) throws NoAvailableBackendException { try { java . net . URLClassLoader loader = ( java . net . URLClassLoader ) ClassLoader . getSystemClassLoader ( ) ; java . net . URL url = jar . toURI ( ) . toURL ( ) ; for ( java . net . URL it : java . util . Arrays . asList ( loader . getURLs ( ) ) ) { if ( it . equals ( url ) ) { return ; } } java . lang . reflect . Method method = java . net . URLClassLoader . class . getDeclaredMethod ( "addURL" , new Class [ ] { java . net . URL . class } ) ; method . setAccessible ( true ) ; method . invoke ( loader , new Object [ ] { url } ) ; } catch ( final java . lang . NoSuchMethodException | java . lang . IllegalAccessException | java . net . MalformedURLException | java . lang . reflect . InvocationTargetException e ) { throw new NoAvailableBackendException ( e ) ; } } | Adds the supplied Java Archive library to java . class . path . This is benign if the library is already loaded . |
19,571 | public double similarity ( Vertex < V > vertex1 , Vertex < V > vertex2 ) { return similarity ( vertex1 . vertexID ( ) , vertex2 . vertexID ( ) ) ; } | Returns the cosine similarity of the vector representations of two vertices in the graph |
19,572 | public double similarity ( int vertexIdx1 , int vertexIdx2 ) { if ( vertexIdx1 == vertexIdx2 ) return 1.0 ; INDArray vector = Transforms . unitVec ( getVertexVector ( vertexIdx1 ) ) ; INDArray vector2 = Transforms . unitVec ( getVertexVector ( vertexIdx2 ) ) ; return Nd4j . getBlasWrapper ( ) . dot ( vector , vector2 ) ; } | Returns the cosine similarity of the vector representations of two vertices in the graph given the indices of these verticies |
19,573 | private void locate ( double [ ] array , int left , int right , int index ) { int mid = ( left + right ) / 2 ; if ( right == left ) { return ; } if ( left < right ) { double s = array [ mid ] ; int i = left - 1 ; int j = right + 1 ; while ( true ) { while ( array [ ++ i ] < s ) ; while ( array [ -- j ] > s ) ; if ( i >= j ) break ; swap ( array , i , j ) ; } if ( i > index ) { locate ( array , left , i - 1 , index ) ; } else { locate ( array , j + 1 , right , index ) ; } } } | sort the partitions by quick sort and locate the target index |
19,574 | public long writeGraphStructure ( SameDiff sd ) throws IOException { Preconditions . checkState ( endStaticInfoOffset < 0 , "Cannot write graph structure - already wrote end of static info marker" ) ; Pair < Integer , FlatBufferBuilder > h = encodeStaticHeader ( UIInfoType . GRAPH_STRUCTURE ) ; FlatBufferBuilder fbb2 = new FlatBufferBuilder ( 0 ) ; int graphStructureOffset = encodeGraphStructure ( fbb2 , sd ) ; fbb2 . finish ( graphStructureOffset ) ; return append ( h . getSecond ( ) , fbb2 ) ; } | Write the graph structure |
19,575 | public long writeFinishStaticMarker ( ) throws IOException { Preconditions . checkState ( endStaticInfoOffset < 0 , "Wrote final static already information already" ) ; Pair < Integer , FlatBufferBuilder > encoded = encodeStaticHeader ( UIInfoType . START_EVENTS ) ; long out = append ( encoded . getSecond ( ) , null ) ; endStaticInfoOffset = file . length ( ) ; return out ; } | Write marker for final static data |
19,576 | public StaticInfo readStatic ( ) throws IOException { List < Pair < UIStaticInfoRecord , Table > > out = new ArrayList < > ( ) ; boolean allStaticRead = false ; try ( RandomAccessFile f = new RandomAccessFile ( file , "r" ) ; FileChannel fc = f . getChannel ( ) ) { f . seek ( 0 ) ; while ( ! allStaticRead ) { int lengthHeader = f . readInt ( ) ; int lengthContent = f . readInt ( ) ; ByteBuffer bb = ByteBuffer . allocate ( lengthHeader ) ; f . getChannel ( ) . read ( bb ) ; bb . flip ( ) ; UIStaticInfoRecord r = UIStaticInfoRecord . getRootAsUIStaticInfoRecord ( bb ) ; bb = ByteBuffer . allocate ( lengthContent ) ; f . getChannel ( ) . read ( bb ) ; bb . flip ( ) ; byte infoType = r . infoType ( ) ; Table t ; switch ( infoType ) { case UIInfoType . GRAPH_STRUCTURE : t = UIGraphStructure . getRootAsUIGraphStructure ( bb ) ; break ; case UIInfoType . SYTEM_INFO : t = UISystemInfo . getRootAsUISystemInfo ( bb ) ; break ; case UIInfoType . START_EVENTS : t = null ; break ; default : throw new RuntimeException ( "Unknown UI static info type: " + r . infoType ( ) ) ; } out . add ( new Pair < > ( r , t ) ) ; long pointer = f . getFilePointer ( ) ; long length = f . length ( ) ; { log . trace ( "File pointer = {}, file length = {}" , pointer , length ) ; if ( infoType == UIInfoType . START_EVENTS || pointer >= length ) { allStaticRead = true ; } } } StaticInfo s = new StaticInfo ( out , f . getFilePointer ( ) ) ; return s ; } } | Read all static information at the start of the file |
19,577 | public List < Pair < UIEvent , Table > > readEvents ( ) throws IOException { Preconditions . checkState ( endStaticInfoOffset >= 0 , "Cannot read events - have not written end of static info marker" ) ; return readEvents ( endStaticInfoOffset ) ; } | Read all of the events . |
19,578 | public List < Pair < UIEvent , Table > > readEvents ( long startOffset ) throws IOException { if ( endStaticInfoOffset >= file . length ( ) ) { return Collections . emptyList ( ) ; } List < Pair < UIEvent , Table > > out = new ArrayList < > ( ) ; try ( RandomAccessFile f = new RandomAccessFile ( file , "r" ) ; FileChannel fc = f . getChannel ( ) ) { f . seek ( startOffset ) ; while ( f . getFilePointer ( ) < f . length ( ) ) { int lengthHeader = f . readInt ( ) ; int lengthContent = f . readInt ( ) ; ByteBuffer bb = ByteBuffer . allocate ( lengthHeader ) ; f . getChannel ( ) . read ( bb ) ; bb . flip ( ) ; UIEvent e = UIEvent . getRootAsUIEvent ( bb ) ; bb = ByteBuffer . allocate ( lengthContent ) ; f . getChannel ( ) . read ( bb ) ; bb . flip ( ) ; byte infoType = e . eventType ( ) ; Table t ; switch ( infoType ) { case UIEventType . ADD_NAME : t = UIAddName . getRootAsUIAddName ( bb ) ; break ; case UIEventType . SCALAR : case UIEventType . ARRAY : t = FlatArray . getRootAsFlatArray ( bb ) ; break ; case UIEventType . ARRAY_LIST : case UIEventType . HISTOGRAM : case UIEventType . IMAGE : case UIEventType . SUMMARY_STATISTICS : case UIEventType . OP_TIMING : case UIEventType . HARDWARE_STATE : case UIEventType . GC_EVENT : default : throw new RuntimeException ( "Unknown or not yet implemented event type: " + e . eventType ( ) ) ; } out . add ( new Pair < > ( e , t ) ) ; } return out ; } } | Read all of the events starting at a specific file offset |
19,579 | public long registerEventName ( String name ) throws IOException { Preconditions . checkState ( endStaticInfoOffset >= 0 , "Cannot write name - have not written end of static info marker" ) ; FlatBufferBuilder fbb = new FlatBufferBuilder ( 0 ) ; long time = System . currentTimeMillis ( ) ; int offset = UIEvent . createUIEvent ( fbb , UIEventType . ADD_NAME , - 1 , time , 0 , 0 , ( short ) - 1 , 0 , 0 ) ; fbb . finish ( offset ) ; FlatBufferBuilder fbb2 = new FlatBufferBuilder ( 0 ) ; int idx = nameIndexCounter . getAndIncrement ( ) ; nameIndexMap . put ( idx , name ) ; indexNameMap . put ( name , idx ) ; int strOffset = fbb2 . createString ( name ) ; int offset2 = UIAddName . createUIAddName ( fbb2 , idx , strOffset ) ; fbb2 . finish ( offset2 ) ; long l = append ( fbb , fbb2 ) ; return l ; } | Register the event name - accuracy loss etc for later use in recording events . |
19,580 | public long writeScalarEvent ( String name , long time , int iteration , int epoch , Number scalar ) throws IOException { Preconditions . checkState ( indexNameMap . containsKey ( name ) , "Name \"%s\" not yet registered" , name ) ; int idx = indexNameMap . get ( name ) ; FlatBufferBuilder fbb = new FlatBufferBuilder ( 0 ) ; int offset = UIEvent . createUIEvent ( fbb , UIEventType . SCALAR , idx , time , iteration , epoch , ( short ) - 1 , 0 , 0 ) ; fbb . finish ( offset ) ; FlatBufferBuilder fbb2 = new FlatBufferBuilder ( 0 ) ; int offset2 = Nd4j . scalar ( scalar ) . toFlatArray ( fbb2 ) ; fbb2 . finish ( offset2 ) ; return append ( fbb , fbb2 ) ; } | Write a single scalar event to the file |
19,581 | public void initOldStream ( ) { if ( oldStream == null ) { oldStreamFromPool = false ; oldStream = new cudaStream_t ( nativeOps . createStream ( ) ) ; specialStream = new cudaStream_t ( nativeOps . createStream ( ) ) ; } } | Initializes the old stream |
19,582 | public static CudaContext getBlasContext ( ) { CudaContext context = ( CudaContext ) AtomicAllocator . getInstance ( ) . getDeviceContext ( ) . getContext ( ) ; return context ; } | Sets up a context with an old stream and a blas handle |
19,583 | public void receiveUpdate ( INDArray array ) { extCounter . getAndIncrement ( ) ; updatesLock . writeLock ( ) . lock ( ) ; if ( updates == null ) { try ( MemoryWorkspace workspace = Nd4j . getMemoryManager ( ) . scopeOutOfWorkspaces ( ) ) { updates = Nd4j . create ( array . shape ( ) , array . ordering ( ) ) ; } } hasSomething . compareAndSet ( false , true ) ; updates . addi ( array ) ; Nd4j . getExecutioner ( ) . commit ( ) ; updatesLock . writeLock ( ) . unlock ( ) ; } | This method accepts updates suitable for StepFunction and puts them to the queue which is used in backpropagation loop |
19,584 | public void defineInputs ( String ... inputNames ) { Preconditions . checkArgument ( inputNames != null && inputNames . length > 0 , "Input names must not be null, and must have length > 0: got %s" , inputNames ) ; this . inputs = Arrays . asList ( inputNames ) ; } | Define the inputs to the DL4J SameDiff Vertex with specific names |
19,585 | public void defineInputs ( int numInputs ) { Preconditions . checkArgument ( numInputs > 0 , "Number of inputs must be > 0: Got %s" , numInputs ) ; String [ ] inputNames = new String [ numInputs ] ; for ( int i = 0 ; i < numInputs ; i ++ ) { inputNames [ i ] = "input_" + i ; } } | Define the inputs to the DL4J SameDiff vertex with generated names . Names will have format input_0 input_1 etc |
19,586 | public static void registerKryoClasses ( SparkConf conf ) { List < Class < ? > > classes = Arrays . < Class < ? > > asList ( BooleanWritable . class , ByteWritable . class , DoubleWritable . class , FloatWritable . class , IntWritable . class , LongWritable . class , NullWritable . class , Text . class ) ; conf . registerKryoClasses ( ( Class < ? > [ ] ) classes . toArray ( ) ) ; } | Register the DataVec writable classes for Kryo |
19,587 | protected void initialize ( ) { log . info ( "Building Huffman tree for source graph..." ) ; int nVertices = sourceGraph . numVertices ( ) ; log . info ( "Transferring Huffman tree info to nodes..." ) ; for ( int i = 0 ; i < nVertices ; i ++ ) { T element = sourceGraph . getVertex ( i ) . getValue ( ) ; element . setElementFrequency ( sourceGraph . getConnectedVertices ( i ) . size ( ) ) ; if ( vocabCache != null ) vocabCache . addToken ( element ) ; } if ( vocabCache != null ) { Huffman huffman = new Huffman ( vocabCache . vocabWords ( ) ) ; huffman . build ( ) ; huffman . applyIndexes ( vocabCache ) ; } } | This method handles required initialization for GraphTransformer |
19,588 | public SameDiff importGraph ( GRAPH_TYPE tfGraph ) { return importGraph ( tfGraph , Collections . < String , OpImportOverride < GRAPH_TYPE , NODE_TYPE , ATTR_TYPE > > emptyMap ( ) , null ) ; } | This method converts given TF |
19,589 | public static INDArray buildFromData ( List < DataPoint > data ) { INDArray ret = Nd4j . create ( data . size ( ) , data . get ( 0 ) . getD ( ) ) ; for ( int i = 0 ; i < ret . slices ( ) ; i ++ ) ret . putSlice ( i , data . get ( i ) . getPoint ( ) ) ; return ret ; } | Create an ndarray from the datapoints |
19,590 | public SDVariable max ( String name , SDVariable x , int ... dimensions ) { return max ( name , x , false , dimensions ) ; } | Max array reduction operation optionally along specified dimensions |
19,591 | public SDVariable prod ( String name , SDVariable x , int ... dimensions ) { return prod ( name , x , false , dimensions ) ; } | Product array reduction operation optionally along specified dimensions |
19,592 | public SDVariable scalarSet ( SDVariable in , Number set ) { return scalarSet ( null , in , set ) ; } | Return an array with equal shape to the input but all elements set to value set |
19,593 | public SDVariable scalarSet ( String name , SDVariable in , Number set ) { SDVariable ret = f ( ) . scalarSet ( in , set ) ; return updateVariableNameAndReference ( ret , name ) ; } | Return a variable with equal shape to the input but all elements set to value set |
19,594 | public SDVariable shape ( String name , SDVariable input ) { SDVariable ret = f ( ) . shape ( input ) ; return updateVariableNameAndReference ( ret , name ) ; } | Returns the shape of the specified SDVariable as a 1D SDVariable |
19,595 | public SDVariable standardDeviation ( String name , SDVariable x , boolean biasCorrected , int ... dimensions ) { return standardDeviation ( name , x , biasCorrected , false , dimensions ) ; } | Stardard deviation array reduction operation optionally along specified dimensions |
19,596 | public SDVariable sum ( String name , SDVariable x , int ... dimensions ) { return sum ( name , x , false , dimensions ) ; } | Sum array reduction operation optionally along specified dimensions |
19,597 | public boolean columnCondition ( Writable writable ) { BooleanWritable booleanWritable = ( BooleanWritable ) writable ; return booleanWritable . get ( ) ; } | Returns whether the given element meets the condition set by this operation |
19,598 | public TimingStatistics add ( TimingStatistics timingStatistics ) { return TimingStatistics . builder ( ) . ndarrayCreationTimeNanos ( ndarrayCreationTimeNanos + timingStatistics . ndarrayCreationTimeNanos ) . bandwidthNanosHostToDevice ( bandwidthNanosHostToDevice + timingStatistics . bandwidthNanosHostToDevice ) . diskReadingTimeNanos ( diskReadingTimeNanos + timingStatistics . diskReadingTimeNanos ) . bandwidthDeviceToHost ( bandwidthDeviceToHost + timingStatistics . bandwidthDeviceToHost ) . build ( ) ; } | Accumulate the given statistics |
19,599 | public static long lengthPerSlice ( INDArray arr , int ... dimension ) { long [ ] remove = ArrayUtil . removeIndex ( arr . shape ( ) , dimension ) ; return ArrayUtil . prodLong ( remove ) ; } | The number of elements in a slice along a set of dimensions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.