kaldi Namespace Reference

This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for mispronunciations detection tasks, the reference: More...

Namespaces

 cu
 
 decoder
 
 differentiable_transform
 
 discriminative
 
 internal
 
 kws_internal
 
 nnet1
 
 nnet2
 
 nnet3
 
 sparse_vector_utils
 
 unittest
 

Classes

class  AccumAmDiagGmm
 
class  AccumDiagGmm
 
class  AccumFullGmm
 Class for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model. More...
 
class  AccumulateMultiThreadedClass
 
struct  AccumulateTreeStatsInfo
 
struct  AccumulateTreeStatsOptions
 
struct  ActivePath
 
class  AffineXformStats
 
class  AgglomerativeClusterer
 The AgglomerativeClusterer class contains the necessary mechanisms for the actual clustering algorithm. More...
 
struct  AhcCluster
 AhcCluster is the cluster object for the agglomerative clustering. More...
 
struct  AlignConfig
 
struct  AlignedTermsPair
 
class  AmDiagGmm
 
class  AmSgmm2
 Class for definition of the subspace Gmm acoustic model. More...
 
class  ArbitraryResample
 Class ArbitraryResample allows you to resample a signal (assumed zero outside the sample region, not periodic) at arbitrary specified time values, which don't have to be linearly spaced. More...
 
class  ArcPosteriorComputer
 
class  ArpaFileParser
 ArpaFileParser is an abstract base class for ARPA LM file conversion. More...
 
struct  ArpaLine
 
class  ArpaLmCompiler
 
class  ArpaLmCompilerImpl
 
class  ArpaLmCompilerImplInterface
 
struct  ArpaParseOptions
 Options that control ArpaFileParser. More...
 
class  basic_filebuf
 
class  basic_pipebuf
 
class  BasicHolder
 BasicHolder is valid for float, double, bool, and integer types. More...
 
class  BasicPairVectorHolder
 BasicPairVectorHolder is a Holder for a vector of pairs of a basic type, e.g. More...
 
class  BasicVectorHolder
 A Holder for a vector of basic types, e.g. More...
 
class  BasicVectorVectorHolder
 BasicVectorVectorHolder is a Holder for a vector of vector of a basic type, e.g. More...
 
class  BasisFmllrAccus
 Stats for fMLLR subspace estimation. More...
 
class  BasisFmllrEstimate
 Estimation functions for basis fMLLR. More...
 
struct  BasisFmllrOptions
 
class  BiglmFasterDecoder
 This is as FasterDecoder, but does online composition between HCLG and the "difference language model", which is a deterministic FST that represents the difference between the language model you want and the language model you compiled HCLG with. More...
 
struct  BiglmFasterDecoderOptions
 
class  BottomUpClusterer
 
struct  ClatRescoreTuple
 
class  Clusterable
 
struct  ClusterKMeansOptions
 
class  CompactLatticeHolder
 
class  CompactLatticeToKwsProductFstMapper
 
struct  CompareFirstMemberOfPair
 Comparator object for pairs that compares only the first pair. More...
 
struct  ComparePosteriorByPdfs
 
struct  CompareReverseSecond
 
class  CompartmentalizedBottomUpClusterer
 
struct  CompBotClustElem
 
struct  ComposeLatticePrunedOptions
 
class  CompressedAffineXformStats
 
class  CompressedMatrix
 
class  ComputeNormalizersClass
 
class  ConfigLine
 This class is responsible for parsing input like hi-there xx=yyy a=b c empty= f-oo=Append(bar, sss) ba_z=123 bing='a b c' baz="a b c d='a b' e" and giving you access to the fields, in this case. More...
 
class  ConstantEventMap
 
class  ConstArpaLm
 
class  ConstArpaLmBuilder
 
class  ConstArpaLmDeterministicFst
 This class wraps a ConstArpaLm format language model with the interface defined in DeterministicOnDemandFst. More...
 
class  ConstIntegerSet
 
class  ContextDependency
 
class  ContextDependencyInterface
 context-dep-itf.h provides a link between the tree-building code in ../tree/, and the FST code in ../fstext/ (particularly, ../fstext/context-dep.h). More...
 
struct  CountStats
 
class  CovarianceStats
 
struct  CuAllocatorOptions
 
class  CuArray
 Class CuArray represents a vector of an integer or struct of type T. More...
 
class  CuArrayBase
 Class CuArrayBase, CuSubArray and CuArray are analogues of classes CuVectorBase, CuSubVector and CuVector, except that they are intended to store things other than float/double: they are intended to store integers or small structs. More...
 
class  CuBlockMatrix
 The class CuBlockMatrix holds a vector of objects of type CuMatrix, say, M_1, M_2, . More...
 
class  CuCompressedMatrix
 Class CuCompressedMatrix, templated on an integer type (expected to be one of: int8, uint8, int16, uint16), this provides a way to approximate a CuMatrix in a more memory-efficient format. More...
 
class  CuCompressedMatrixBase
 Class CuCompressedMatrixBase is an abstract base class that allows you to compress a matrix of type CuMatrix<BaseFloat>. More...
 
class  CuMatrix
 This class represents a matrix that's stored on the GPU if we have one, and in memory if not. More...
 
class  CuMatrixBase
 Matrix for CUDA computing. More...
 
class  CuPackedMatrix
 Matrix for CUDA computing. More...
 
class  CuRand
 
class  CuSparseMatrix
 
class  CuSpMatrix
 
class  CuSubArray
 
class  CuSubMatrix
 This class is used for a piece of a CuMatrix. More...
 
class  CuSubVector
 
class  CuTpMatrix
 
class  CuValue
 The following class is used to simulate non-const references to Real, e.g. More...
 
class  CuVector
 
class  CuVectorBase
 Vector for CUDA computing. More...
 
class  DecisionTreeSplitter
 
class  DecodableAmDiagGmm
 
class  DecodableAmDiagGmmRegtreeFmllr
 
class  DecodableAmDiagGmmRegtreeMllr
 
class  DecodableAmDiagGmmScaled
 
class  DecodableAmDiagGmmUnmapped
 DecodableAmDiagGmmUnmapped is a decodable object that takes indices that correspond to pdf-id's plus one. More...
 
class  DecodableAmSgmm2
 
class  DecodableAmSgmm2Scaled
 
class  DecodableDiagGmmScaledOnline
 
class  DecodableInterface
 DecodableInterface provides a link between the (acoustic-modeling and feature-processing) code and the decoder. More...
 
class  DecodableMapped
 
class  DecodableMatrixMapped
 This is like DecodableMatrixScaledMapped, but it doesn't support an acoustic scale, and it does support a frame offset, whereby you can state that the first row of 'likes' is actually the n'th row of the matrix of available log-likelihoods. More...
 
class  DecodableMatrixMappedOffset
 This decodable class returns log-likes stored in a matrix; it supports repeatedly writing to the matrix and setting a time-offset representing the frame-index of the first row of the matrix. More...
 
class  DecodableMatrixScaled
 
class  DecodableMatrixScaledMapped
 
class  DecodableSum
 
class  DecodableSumScaled
 
class  DecodeUtteranceLatticeFasterClass
 This class basically does the same job as the function DecodeUtteranceLatticeFaster, but in a way that allows us to build a multi-threaded command line program more easily. More...
 
class  DeltaFeatures
 
struct  DeltaFeaturesOptions
 
class  DeterminizeLatticeTask
 
class  DiagGmm
 Definition for Gaussian Mixture Model with diagonal covariances. More...
 
class  DiagGmmNormal
 Definition for Gaussian Mixture Model with diagonal covariances in normal mode: where the parameters are stored as means and variances (instead of the exponential form that the DiagGmm class is stored as). More...
 
struct  DummyOptions
 
struct  EbwAmSgmm2Options
 This header implements a form of Extended Baum-Welch training for SGMMs. More...
 
class  EbwAmSgmm2Updater
 
struct  EbwOptions
 
class  EbwUpdatePhoneVectorsClass
 
struct  EbwWeightOptions
 
class  EigenvalueDecomposition
 
struct  error_stats
 
class  EventMap
 A class that is capable of representing a generic mapping from EventType (which is a vector of (key, value) pairs) to EventAnswerType which is just an integer. More...
 
struct  EventMapVectorEqual
 
struct  EventMapVectorHash
 
class  ExampleClass
 
class  ExampleFeatureComputer
 This class is only added for documentation, it is not intended to ever be used. More...
 
struct  ExampleFeatureComputerOptions
 This class is only added for documentation, it is not intended to ever be used. More...
 
class  FasterDecoder
 
struct  FasterDecoderOptions
 
class  FbankComputer
 Class for computing mel-filterbank features; see Computing MFCC features for more information. More...
 
struct  FbankOptions
 FbankOptions contains basic options for computing filterbank features. More...
 
class  FeatureTransformEstimate
 Class for computing a feature transform used for preconditioning of the training data in neural-networks. More...
 
class  FeatureTransformEstimateMulti
 
struct  FeatureTransformEstimateOptions
 
struct  FeatureWindowFunction
 
class  FileInputImpl
 
class  FileOutputImpl
 
class  FmllrDiagGmmAccs
 This does not work with multiple feature transforms. More...
 
struct  FmllrOptions
 
class  FmllrRawAccs
 
struct  FmllrRawOptions
 
class  FmllrSgmm2Accs
 Class for computing the accumulators needed for the maximum-likelihood estimate of FMLLR transforms for a subspace GMM acoustic model. More...
 
class  Fmpe
 
struct  FmpeOptions
 
struct  FmpeStats
 
struct  FmpeUpdateOptions
 
struct  FrameExtractionOptions
 
class  FullGmm
 Definition for Gaussian Mixture Model with full covariances. More...
 
class  FullGmmNormal
 Definition for Gaussian Mixture Model with full covariances in normal mode: where the parameters are stored as means and variances (instead of the exponential form that the FullGmm class is stored as). More...
 
class  GaussClusterable
 GaussClusterable wraps Gaussian statistics in a form accessible to generic clustering algorithms. More...
 
struct  GaussInfo
 
class  GaussPostHolder
 
class  GeneralMatrix
 This class is a wrapper that enables you to store a matrix in one of three forms: either as a Matrix<BaseFloat>, or a CompressedMatrix, or a SparseMatrix<BaseFloat>. More...
 
class  GenericHolder
 GenericHolder serves to document the requirements of the Holder interface; it's not intended to be used. More...
 
class  HashList
 
struct  HmmCacheHash
 
class  HmmTopology
 A class for storing topology information for phones. More...
 
struct  HtkHeader
 A structure containing the HTK header. More...
 
class  HtkMatrixHolder
 
struct  HTransducerConfig
 Configuration class for the GetHTransducer() function; see The HTransducerConfig configuration class for context. More...
 
class  Input
 
class  InputImplBase
 
union  Int32AndFloat
 
struct  Int32IsZero
 
class  Interval
 
struct  IvectorEstimationOptions
 
class  IvectorExtractor
 
class  IvectorExtractorComputeDerivedVarsClass
 
struct  IvectorExtractorEstimationOptions
 Options for training the IvectorExtractor, e.g. variance flooring. More...
 
struct  IvectorExtractorOptions
 
class  IvectorExtractorStats
 IvectorExtractorStats is a class used to update the parameters of the ivector extractor. More...
 
struct  IvectorExtractorStatsOptions
 Options for IvectorExtractorStats, which is used to update the parameters of IvectorExtractor. More...
 
class  IvectorExtractorUpdateProjectionClass
 
class  IvectorExtractorUpdateWeightClass
 
class  IvectorExtractorUtteranceStats
 These are the stats for a particular utterance, i.e. More...
 
class  IvectorExtractTask
 
class  IvectorTask
 
class  KaldiFatalError
 Kaldi fatal runtime error exception. More...
 
class  KaldiObjectHolder
 KaldiObjectHolder works for Kaldi objects that have the "standard" Read and Write functions, and a copy constructor. More...
 
class  KaldiRnnlmWrapper
 
struct  KaldiRnnlmWrapperOpts
 
class  KwsAlignment
 
class  KwsProductFstToKwsLexicographicFstMapper
 
class  KwsTerm
 
class  KwsTermsAligner
 
struct  KwsTermsAlignerOptions
 
struct  LatticeArcRecord
 This is used in CompactLatticeLimitDepth. More...
 
class  LatticeBiglmFasterDecoder
 This is as LatticeFasterDecoder, but does online composition between HCLG and the "difference language model", which is a deterministic FST that represents the difference between the language model you want and the language model you compiled HCLG with. More...
 
struct  LatticeFasterDecoderConfig
 
class  LatticeFasterDecoderTpl
 This is the "normal" lattice-generating decoder. More...
 
class  LatticeFasterOnlineDecoderTpl
 LatticeFasterOnlineDecoderTpl is as LatticeFasterDecoderTpl but also supports an efficient way to get the best path (see the function BestPathEnd()), which is useful in endpointing and in situations where you might want to frequently access the best path. More...
 
class  LatticeHolder
 
struct  LatticeIncrementalDecoderConfig
 The normal decoder, lattice-faster-decoder.h, sometimes has an issue when doing real-time applications with long utterances, that each time you get the lattice the lattice determinization can take a considerable amount of time; this introduces latency. More...
 
class  LatticeIncrementalDecoderTpl
 This is an extention to the "normal" lattice-generating decoder. More...
 
class  LatticeIncrementalDeterminizer
 This class is used inside LatticeIncrementalDecoderTpl; it handles some of the details of incremental determinization. More...
 
class  LatticeIncrementalOnlineDecoderTpl
 LatticeIncrementalOnlineDecoderTpl is as LatticeIncrementalDecoderTpl but also supports an efficient way to get the best path (see the function BestPathEnd()), which is useful in endpointing and in situations where you might want to frequently access the best path. More...
 
class  LatticeLexiconWordAligner
 
class  LatticePhoneAligner
 
class  LatticeReader
 LatticeReader provides (static) functions for reading both Lattice and CompactLattice, in text form. More...
 
class  LatticeSimpleDecoder
 Simplest possible decoder, included largely for didactic purposes and as a means to debug more highly optimized decoders. More...
 
struct  LatticeSimpleDecoderConfig
 
class  LatticeWordAligner
 
struct  LbfgsOptions
 This is an implementation of L-BFGS. More...
 
class  LdaEstimate
 Class for computing linear discriminant analysis (LDA) transform. More...
 
struct  LdaEstimateOptions
 
struct  LinearCgdOptions
 
class  LinearResample
 LinearResample is a special case of ArbitraryResample, where we want to resample a signal at linearly spaced intervals (this means we want to upsample or downsample the signal). More...
 
class  LinearVtln
 
class  LmState
 
class  LogisticRegression
 
struct  LogisticRegressionConfig
 
struct  LogMessageEnvelope
 Log message severity and source location info. More...
 
struct  MapDiagGmmOptions
 Configuration variables for Maximum A Posteriori (MAP) update. More...
 
struct  MapTransitionUpdateConfig
 
class  Matrix
 A class for storing matrices. More...
 
class  MatrixBase
 Base class which provides matrix operations not involving resizing or allocation. More...
 
class  MelBanks
 
struct  MelBanksOptions
 
class  MessageLogger
 
class  MfccComputer
 
struct  MfccOptions
 MfccOptions contains basic options for computing MFCC features. More...
 
class  MinimumBayesRisk
 This class does the word-level Minimum Bayes Risk computation, and gives you either the 1-best MBR output together with the expected Bayes Risk, or a sausage-like structure. More...
 
struct  MinimumBayesRiskOptions
 The implementation of the Minimum Bayes Risk decoding method described in "Minimum Bayes Risk decoding and system combination based on a recursion for edit distance", Haihua Xu, Daniel Povey, Lidia Mangu and Jie Zhu, Computer Speech and Language, 2011 This is a slightly more principled way to do Minimum Bayes Risk (MBR) decoding than the standard "Confusion Network" method. More...
 
class  MleAmSgmm2Accs
 Class for the accumulators associated with the phonetic-subspace model parameters. More...
 
struct  MleAmSgmm2Options
 Configuration variables needed in the SGMM estimation process. More...
 
class  MleAmSgmm2Updater
 
struct  MleDiagGmmOptions
 Configuration variables like variance floor, minimum occupancy, etc. More...
 
struct  MleFullGmmOptions
 Configuration variables like variance floor, minimum occupancy, etc. More...
 
class  MleSgmm2SpeakerAccs
 Class for the accumulators required to update the speaker vectors v_s. More...
 
struct  MleTransitionUpdateConfig
 
class  MlltAccs
 A class for estimating Maximum Likelihood Linear Transform, also known as global Semi-tied Covariance (STC), for GMMs. More...
 
class  MultiThreadable
 
class  MultiThreader
 
class  MyTaskClass
 
class  MyThreadClass
 
struct  NccfInfo
 
struct  NGram
 A parsed n-gram from ARPA LM file. More...
 
class  NumberIstream
 
class  OfflineFeatureTpl
 This templated class is intended for offline feature extraction, i.e. More...
 
class  OffsetFileInputImpl
 
class  OnlineAppendFeature
 This online-feature class implements combination of two feature streams (such as pitch, plp) into one stream. More...
 
class  OnlineAudioSourceItf
 
class  OnlineBaseFeature
 Add a virtual class for "source" features such as MFCC or PLP or pitch features. More...
 
class  OnlineCacheFeature
 This feature type can be used to cache its input, to avoid repetition of computation in a multi-pass decoding context. More...
 
class  OnlineCacheInput
 
class  OnlineCmnInput
 
class  OnlineCmvn
 This class does an online version of the cepstral mean and [optionally] variance, but note that this is not equivalent to the offline version. More...
 
struct  OnlineCmvnOptions
 
struct  OnlineCmvnState
 Struct OnlineCmvnState stores the state of CMVN adaptation between utterances (but not the state of the computation within an utterance). More...
 
class  OnlineDecodableDiagGmmScaled
 
class  OnlineDeltaFeature
 
class  OnlineDeltaInput
 
struct  OnlineEndpointConfig
 
struct  OnlineEndpointRule
 This header contains a simple facility for endpointing, that should be used in conjunction with the "online2" online decoding code; see ../online2bin/online2-wav-gmm-latgen-faster-endpoint.cc. More...
 
class  OnlineFasterDecoder
 
struct  OnlineFasterDecoderOpts
 
class  OnlineFeatInputItf
 
class  OnlineFeatureInterface
 OnlineFeatureInterface is an interface for online feature processing (it is also usable in the offline setting, but currently we're not using it for that). More...
 
class  OnlineFeatureMatrix
 
struct  OnlineFeatureMatrixOptions
 
class  OnlineFeaturePipeline
 OnlineFeaturePipeline is a class that's responsible for putting together the various stages of the feature-processing pipeline, in an online setting. More...
 
struct  OnlineFeaturePipelineCommandLineConfig
 This configuration class is to set up OnlineFeaturePipelineConfig, which in turn is the configuration class for OnlineFeaturePipeline. More...
 
struct  OnlineFeaturePipelineConfig
 This configuration class is responsible for storing the configuration options for OnlineFeaturePipeline, but it does not set them. More...
 
class  OnlineFeInput
 
class  OnlineGenericBaseFeature
 This is a templated class for online feature extraction; it's templated on a class like MfccComputer or PlpComputer that does the basic feature extraction. More...
 
struct  OnlineGmmAdaptationState
 
struct  OnlineGmmDecodingAdaptationPolicyConfig
 This configuration class controls when to re-estimate the basis-fMLLR during online decoding. More...
 
struct  OnlineGmmDecodingConfig
 
class  OnlineGmmDecodingModels
 This class is used to read, store and give access to the models used for 3 phases of decoding (first-pass with online-CMN features; the ML models used for estimating transforms; and the discriminatively trained models). More...
 
class  OnlineIvectorEstimationStats
 This class helps us to efficiently estimate iVectors in situations where the data is coming in frame by frame. More...
 
struct  OnlineIvectorExtractionConfig
 This class includes configuration variables relating to the online iVector extraction, but not including configuration for the "base feature", i.e. More...
 
struct  OnlineIvectorExtractionInfo
 This struct contains various things that are needed (as const references) by class OnlineIvectorExtractor. More...
 
struct  OnlineIvectorExtractorAdaptationState
 This class stores the adaptation state from the online iVector extractor, which can help you to initialize the adaptation state for the next utterance of the same speaker in a more informed way. More...
 
class  OnlineIvectorFeature
 OnlineIvectorFeature is an online feature-extraction class that's responsible for extracting iVectors from raw features such as MFCC, PLP or filterbank. More...
 
class  OnlineLdaInput
 
class  OnlineMatrixFeature
 This class takes a Matrix<BaseFloat> and wraps it as an OnlineFeatureInterface: this can be useful where some earlier stage of feature processing has been done offline but you want to use part of the online pipeline. More...
 
class  OnlineMatrixInput
 
struct  OnlineNnet2DecodingConfig
 
struct  OnlineNnet2DecodingThreadedConfig
 
class  OnlineNnet2FeaturePipeline
 OnlineNnet2FeaturePipeline is a class that's responsible for putting together the various parts of the feature-processing pipeline for neural networks, in an online setting. More...
 
struct  OnlineNnet2FeaturePipelineConfig
 This configuration class is to set up OnlineNnet2FeaturePipelineInfo, which in turn is the configuration class for OnlineNnet2FeaturePipeline. More...
 
struct  OnlineNnet2FeaturePipelineInfo
 This class is responsible for storing configuration variables, objects and options for OnlineNnet2FeaturePipeline (including the actual LDA and CMVN-stats matrices, and the iVector extractor, which is a member of ivector_extractor_info. More...
 
class  OnlinePaSource
 
class  OnlinePitchFeature
 
class  OnlinePitchFeatureImpl
 
class  OnlineProcessPitch
 This online-feature class implements post processing of pitch features. More...
 
class  OnlineSilenceWeighting
 
struct  OnlineSilenceWeightingConfig
 
class  OnlineSpeexDecoder
 
class  OnlineSpeexEncoder
 
class  OnlineSpliceFrames
 
struct  OnlineSpliceOptions
 
class  OnlineTcpVectorSource
 
class  OnlineTimer
 class OnlineTimer is used to test real-time decoding algorithms and evaluate how long the decoding of a particular utterance would take. More...
 
class  OnlineTimingStats
 class OnlineTimingStats stores statistics from timing of online decoding, which will enable the Print() function to print out the average real-time factor and average delay per utterance. More...
 
class  OnlineTransform
 This online-feature class implements any affine or linear transform. More...
 
class  OnlineUdpInput
 
class  OnlineVectorSource
 
class  OptimizableInterface
 OptimizableInterface provides a virtual class for optimizable objects. More...
 
class  OptimizeLbfgs
 
class  OptionsItf
 
class  OtherReal
 This class provides a way for switching between double and float types. More...
 
class  OtherReal< double >
 A specialized class for switching from double to float. More...
 
class  OtherReal< float >
 A specialized class for switching from float to double. More...
 
class  Output
 
class  OutputImplBase
 
class  PackedMatrix
 Packed matrix: base class for triangular and symmetric matrices. More...
 
struct  PairHasher
 A hashing function-object for pairs of ints. More...
 
class  ParseOptions
 The class ParseOptions is for parsing command-line options; see Parsing command-line options for more documentation. More...
 
struct  PhoneAlignLatticeOptions
 
class  PipeInputImpl
 
class  PipeOutputImpl
 
struct  PitchExtractionOptions
 
class  PitchFrameInfo
 
class  PitchInterpolator
 
struct  PitchInterpolatorOptions
 
struct  PitchInterpolatorStats
 
class  Plda
 
struct  PldaConfig
 
struct  PldaEstimationConfig
 
class  PldaEstimator
 
class  PldaStats
 
class  PldaUnsupervisedAdaptor
 This class takes unlabeled iVectors from the domain of interest and uses their mean and variance to adapt your PLDA matrices to a new domain. More...
 
struct  PldaUnsupervisedAdaptorConfig
 
class  PlpComputer
 This is the new-style interface to the PLP computation. More...
 
struct  PlpOptions
 PlpOptions contains basic options for computing PLP features. More...
 
class  PosteriorHolder
 
struct  ProcessPitchOptions
 
class  Profiler
 
class  ProfileStats
 
class  PrunedCompactLatticeComposer
 PrunedCompactLatticeComposer implements an algorithm for pruned composition. More...
 
class  Questions
 This class defines, for each EventKeyType, a set of initial questions that it tries and also a number of iterations for which to refine the questions to increase likelihood. More...
 
struct  QuestionsForKey
 QuestionsForKey is a class used to define the questions for a key, and also options that allow us to refine the question during tree-building (i.e. More...
 
class  RandomAccessTableReader
 Allows random access to a collection of objects in an archive or script file; see The Table concept. More...
 
class  RandomAccessTableReaderArchiveImplBase
 
class  RandomAccessTableReaderDSortedArchiveImpl
 
class  RandomAccessTableReaderImplBase
 
class  RandomAccessTableReaderMapped
 This class is for when you are reading something in random access, but it may actually be stored per-speaker (or something similar) but the keys you're using are per utterance. More...
 
class  RandomAccessTableReaderScriptImpl
 
class  RandomAccessTableReaderSortedArchiveImpl
 
class  RandomAccessTableReaderUnsortedArchiveImpl
 
struct  RandomState
 
struct  RecognizedWord
 
class  RecyclingVector
 This class serves as a storage for feature vectors with an option to limit the memory usage by removing old elements. More...
 
class  RefineClusterer
 
struct  RefineClustersOptions
 
class  RegressionTree
 A regression tree is a clustering of Gaussian densities in an acoustic model, such that the group of Gaussians at each node of the tree are transformed by the same transform. More...
 
class  RegtreeFmllrDiagGmm
 An FMLLR (feature-space MLLR) transformation, also called CMLLR (constrained MLLR) is an affine transformation of the feature vectors. More...
 
class  RegtreeFmllrDiagGmmAccs
 Class for computing the accumulators needed for the maximum-likelihood estimate of FMLLR transforms for an acoustic model that uses diagonal Gaussian mixture models as emission densities. More...
 
struct  RegtreeFmllrOptions
 Configuration variables for FMLLR transforms. More...
 
class  RegtreeMllrDiagGmm
 An MLLR mean transformation is an affine transformation of Gaussian means. More...
 
class  RegtreeMllrDiagGmmAccs
 Class for computing the maximum-likelihood estimates of the parameters of an acoustic model that uses diagonal Gaussian mixture models as emission densities. More...
 
struct  RegtreeMllrOptions
 Configuration variables for FMLLR transforms. More...
 
class  RnnlmDeterministicFst
 
struct  RspecifierOptions
 
class  ScalarClusterable
 ScalarClusterable clusters scalars with x^2 loss. More...
 
class  Semaphore
 
class  SequentialTableReader
 A templated class for reading objects sequentially from an archive or script file; see The Table concept. More...
 
class  SequentialTableReaderArchiveImpl
 
class  SequentialTableReaderBackgroundImpl
 
class  SequentialTableReaderImplBase
 
class  SequentialTableReaderScriptImpl
 
struct  Sgmm2FmllrConfig
 Configuration variables needed in the estimation of FMLLR for SGMMs. More...
 
class  Sgmm2FmllrGlobalParams
 Global adaptation parameters. More...
 
class  Sgmm2GauPost
 indexed by time. More...
 
struct  Sgmm2GauPostElement
 This is the entry for a single time. More...
 
struct  Sgmm2GselectConfig
 
struct  Sgmm2LikelihoodCache
 Sgmm2LikelihoodCache caches SGMM likelihoods at two levels: the final pdf likelihoods, and the sub-state level likelihoods, which means that with the SCTM system we can avoid redundant computation. More...
 
struct  Sgmm2PerFrameDerivedVars
 Holds the per-frame precomputed quantities x(t), x_{i}(t), z_{i}(t), and n_{i}(t) (cf. More...
 
class  Sgmm2PerSpkDerivedVars
 
class  Sgmm2Project
 
struct  Sgmm2SplitSubstatesConfig
 
class  ShiftedDeltaFeatures
 
struct  ShiftedDeltaFeaturesOptions
 
class  SimpleDecoder
 Simplest possible decoder, included largely for didactic purposes and as a means to debug more highly optimized decoders. More...
 
class  SimpleOptions
 The class SimpleOptions is an implementation of OptionsItf that allows setting and getting option values programmatically, i.e., via getter and setter methods. More...
 
class  SingleUtteranceGmmDecoder
 You will instantiate this class when you want to decode a single utterance using the online-decoding setup. More...
 
class  SingleUtteranceNnet2Decoder
 You will instantiate this class when you want to decode a single utterance using the online-decoding setup for neural nets. More...
 
class  SingleUtteranceNnet2DecoderThreaded
 You will instantiate this class when you want to decode a single utterance using the online-decoding setup for neural nets. More...
 
class  SingleUtteranceNnet3DecoderTpl
 You will instantiate this class when you want to decode a single utterance using the online-decoding setup for neural nets. More...
 
class  SingleUtteranceNnet3IncrementalDecoderTpl
 You will instantiate this class when you want to decode a single utterance using the online-decoding setup for neural nets. More...
 
struct  SlidingWindowCmnOptions
 
struct  SolverOptions
 This class describes the options for maximizing various quadratic objective functions. More...
 
class  SparseMatrix
 
class  SparseVector
 
class  SpectrogramComputer
 Class for computing spectrogram features. More...
 
struct  SpectrogramOptions
 SpectrogramOptions contains basic options for computing spectrogram features. More...
 
struct  SpeexOptions
 
class  SphinxMatrixHolder
 A class for reading/writing Sphinx format matrices. More...
 
class  SplitEventMap
 
class  SplitRadixComplexFft
 
class  SplitRadixRealFft
 
class  SpMatrix
 Packed symetric matrix class. More...
 
class  StandardInputImpl
 
class  StandardOutputImpl
 
struct  StringHasher
 A hashing function object for strings. More...
 
class  SubMatrix
 Sub-matrix representation. More...
 
class  SubVector
 Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vector [or as the row of a matrix]. More...
 
class  TableEventMap
 
class  TableWriter
 A templated class for writing objects to an archive or script file; see The Table concept. More...
 
class  TableWriterArchiveImpl
 
class  TableWriterBothImpl
 
class  TableWriterImplBase
 
class  TableWriterScriptImpl
 
class  TaskSequencer
 
struct  TaskSequencerConfig
 
class  TcpServer
 
class  ThreadSynchronizer
 class ThreadSynchronizer acts to guard an arbitrary type of buffer between a producing and a consuming thread (note: it's all symmetric between the two thread types). More...
 
class  TidToTstateMapper
 
class  Timer
 
class  TokenHolder
 
class  TokenVectorHolder
 
class  TpMatrix
 Packed symetric matrix class. More...
 
class  TrainingGraphCompiler
 
struct  TrainingGraphCompilerOptions
 
class  TransitionModel
 
class  TreeClusterer
 
struct  TreeClusterOptions
 
class  TreeRenderer
 
class  TwvMetrics
 
struct  TwvMetricsOptions
 
class  TwvMetricsStats
 
struct  UbmClusteringOptions
 
class  UpdatePhoneVectorsClass
 
class  UpdateWClass
 
struct  VadEnergyOptions
 
class  Vector
 A class representing a vector. More...
 
class  VectorBase
 Provides a vector abstraction class. More...
 
class  VectorClusterable
 VectorClusterable wraps vectors in a form accessible to generic clustering algorithms. More...
 
class  VectorFstToKwsLexicographicFstMapper
 
struct  VectorHasher
 A hashing function-object for vectors. More...
 
class  WaveData
 This class's purpose is to read in Wave files. More...
 
struct  WaveHeaderReadGofer
 
class  WaveHolder
 
class  WaveInfo
 This class reads and hold wave file header information. More...
 
class  WaveInfoHolder
 
class  WordAlignedLatticeTester
 
class  WordAlignLatticeLexiconInfo
 This class extracts some information from the lexicon and stores it in a suitable form for the word-alignment code to use. More...
 
struct  WordAlignLatticeLexiconOpts
 
struct  WordBoundaryInfo
 
struct  WordBoundaryInfoNewOpts
 
struct  WordBoundaryInfoOpts
 
struct  WspecifierOptions
 

Typedefs

typedef void(* LogHandler) (const LogMessageEnvelope &envelope, const char *message)
 Type of third-party logging function. More...
 
typedef float BaseFloat
 
typedef float float32
 
typedef double double64
 
typedef int32 MatrixIndexT
 
typedef int32 SignedMatrixIndexT
 
typedef uint32 UnsignedMatrixIndexT
 
typedef basic_pipebuf< char > PipebufType
 
typedef std::vector< std::string > KeyList
 
typedef TableWriter< KaldiObjectHolder< MatrixBase< BaseFloat > > > BaseFloatMatrixWriter
 
typedef SequentialTableReader< KaldiObjectHolder< Matrix< BaseFloat > > > SequentialBaseFloatMatrixReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< Matrix< BaseFloat > > > RandomAccessBaseFloatMatrixReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< Matrix< BaseFloat > > > RandomAccessBaseFloatMatrixReaderMapped
 
typedef TableWriter< KaldiObjectHolder< MatrixBase< double > > > DoubleMatrixWriter
 
typedef SequentialTableReader< KaldiObjectHolder< Matrix< double > > > SequentialDoubleMatrixReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< Matrix< double > > > RandomAccessDoubleMatrixReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< Matrix< double > > > RandomAccessDoubleMatrixReaderMapped
 
typedef TableWriter< KaldiObjectHolder< CompressedMatrix > > CompressedMatrixWriter
 
typedef TableWriter< KaldiObjectHolder< VectorBase< BaseFloat > > > BaseFloatVectorWriter
 
typedef SequentialTableReader< KaldiObjectHolder< Vector< BaseFloat > > > SequentialBaseFloatVectorReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< Vector< BaseFloat > > > RandomAccessBaseFloatVectorReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< Vector< BaseFloat > > > RandomAccessBaseFloatVectorReaderMapped
 
typedef TableWriter< KaldiObjectHolder< VectorBase< double > > > DoubleVectorWriter
 
typedef SequentialTableReader< KaldiObjectHolder< Vector< double > > > SequentialDoubleVectorReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< Vector< double > > > RandomAccessDoubleVectorReader
 
typedef TableWriter< KaldiObjectHolder< CuMatrix< BaseFloat > > > BaseFloatCuMatrixWriter
 
typedef SequentialTableReader< KaldiObjectHolder< CuMatrix< BaseFloat > > > SequentialBaseFloatCuMatrixReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< CuMatrix< BaseFloat > > > RandomAccessBaseFloatCuMatrixReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< CuMatrix< BaseFloat > > > RandomAccessBaseFloatCuMatrixReaderMapped
 
typedef TableWriter< KaldiObjectHolder< CuMatrix< double > > > DoubleCuMatrixWriter
 
typedef SequentialTableReader< KaldiObjectHolder< CuMatrix< double > > > SequentialDoubleCuMatrixReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< CuMatrix< double > > > RandomAccessDoubleCuMatrixReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< CuMatrix< double > > > RandomAccessDoubleCuMatrixReaderMapped
 
typedef TableWriter< KaldiObjectHolder< CuVector< BaseFloat > > > BaseFloatCuVectorWriter
 
typedef SequentialTableReader< KaldiObjectHolder< CuVector< BaseFloat > > > SequentialBaseFloatCuVectorReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< CuVector< BaseFloat > > > RandomAccessBaseFloatCuVectorReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< CuVector< BaseFloat > > > RandomAccessBaseFloatCuVectorReaderMapped
 
typedef TableWriter< KaldiObjectHolder< CuVector< double > > > DoubleCuVectorWriter
 
typedef SequentialTableReader< KaldiObjectHolder< CuVector< double > > > SequentialDoubleCuVectorReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< CuVector< double > > > RandomAccessDoubleCuVectorReader
 
typedef TableWriter< BasicHolder< int32 > > Int32Writer
 
typedef SequentialTableReader< BasicHolder< int32 > > SequentialInt32Reader
 
typedef RandomAccessTableReader< BasicHolder< int32 > > RandomAccessInt32Reader
 
typedef TableWriter< BasicVectorHolder< int32 > > Int32VectorWriter
 
typedef SequentialTableReader< BasicVectorHolder< int32 > > SequentialInt32VectorReader
 
typedef RandomAccessTableReader< BasicVectorHolder< int32 > > RandomAccessInt32VectorReader
 
typedef TableWriter< BasicVectorVectorHolder< int32 > > Int32VectorVectorWriter
 
typedef SequentialTableReader< BasicVectorVectorHolder< int32 > > SequentialInt32VectorVectorReader
 
typedef RandomAccessTableReader< BasicVectorVectorHolder< int32 > > RandomAccessInt32VectorVectorReader
 
typedef TableWriter< BasicPairVectorHolder< int32 > > Int32PairVectorWriter
 
typedef SequentialTableReader< BasicPairVectorHolder< int32 > > SequentialInt32PairVectorReader
 
typedef RandomAccessTableReader< BasicPairVectorHolder< int32 > > RandomAccessInt32PairVectorReader
 
typedef TableWriter< BasicPairVectorHolder< BaseFloat > > BaseFloatPairVectorWriter
 
typedef SequentialTableReader< BasicPairVectorHolder< BaseFloat > > SequentialBaseFloatPairVectorReader
 
typedef RandomAccessTableReader< BasicPairVectorHolder< BaseFloat > > RandomAccessBaseFloatPairVectorReader
 
typedef TableWriter< BasicHolder< BaseFloat > > BaseFloatWriter
 
typedef SequentialTableReader< BasicHolder< BaseFloat > > SequentialBaseFloatReader
 
typedef RandomAccessTableReader< BasicHolder< BaseFloat > > RandomAccessBaseFloatReader
 
typedef RandomAccessTableReaderMapped< BasicHolder< BaseFloat > > RandomAccessBaseFloatReaderMapped
 
typedef TableWriter< BasicHolder< double > > DoubleWriter
 
typedef SequentialTableReader< BasicHolder< double > > SequentialDoubleReader
 
typedef RandomAccessTableReader< BasicHolder< double > > RandomAccessDoubleReader
 
typedef TableWriter< BasicHolder< bool > > BoolWriter
 
typedef SequentialTableReader< BasicHolder< bool > > SequentialBoolReader
 
typedef RandomAccessTableReader< BasicHolder< bool > > RandomAccessBoolReader
 
typedef TableWriter< TokenHolderTokenWriter
 TokenWriter is a writer specialized for std::string where the strings are nonempty and whitespace-free. More...
 
typedef SequentialTableReader< TokenHolderSequentialTokenReader
 
typedef RandomAccessTableReader< TokenHolderRandomAccessTokenReader
 
typedef TableWriter< TokenVectorHolderTokenVectorWriter
 TokenVectorWriter is a writer specialized for sequences of std::string where the strings are nonempty and whitespace-free. More...
 
typedef SequentialTableReader< TokenVectorHolderSequentialTokenVectorReader
 
typedef RandomAccessTableReader< TokenVectorHolderRandomAccessTokenVectorReader
 
typedef TableWriter< KaldiObjectHolder< GeneralMatrix > > GeneralMatrixWriter
 
typedef SequentialTableReader< KaldiObjectHolder< GeneralMatrix > > SequentialGeneralMatrixReader
 
typedef RandomAccessTableReader< KaldiObjectHolder< GeneralMatrix > > RandomAccessGeneralMatrixReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< GeneralMatrix > > RandomAccessGeneralMatrixReaderMapped
 
typedef OfflineFeatureTpl< FbankComputerFbank
 
typedef OfflineFeatureTpl< MfccComputerMfcc
 
typedef OfflineFeatureTpl< PlpComputerPlp
 
typedef OfflineFeatureTpl< SpectrogramComputerSpectrogram
 
typedef OnlineGenericBaseFeature< MfccComputerOnlineMfcc
 
typedef OnlineGenericBaseFeature< PlpComputerOnlinePlp
 
typedef OnlineGenericBaseFeature< FbankComputerOnlineFbank
 
typedef std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
 
typedef uint16 uint_smaller
 
typedef int16 int_smaller
 
typedef int32 EventKeyType
 Things of type EventKeyType can take any value. More...
 
typedef int32 EventValueType
 Given current code, things of type EventValueType should generally be nonnegative and in a reasonably small range (e.g. More...
 
typedef int32 EventAnswerType
 As far as the event-map code itself is concerned, things of type EventAnswerType may take any value except kNoAnswer (== -1). More...
 
typedef std::vector< std::pair< EventKeyType, EventValueType > > EventType
 
typedef TableWriter< KaldiObjectHolder< AmDiagGmm > > MapAmDiagGmmWriter
 
typedef RandomAccessTableReader< KaldiObjectHolder< AmDiagGmm > > RandomAccessMapAmDiagGmmReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< AmDiagGmm > > RandomAccessMapAmDiagGmmReaderMapped
 
typedef SequentialTableReader< KaldiObjectHolder< AmDiagGmm > > MapAmDiagGmmSeqReader
 
typedef uint16 GmmFlagsType
 Bitwise OR of the above flags. More...
 
typedef uint16 SgmmUpdateFlagsType
 Bitwise OR of the above flags. More...
 
typedef uint16 SgmmWriteFlagsType
 Bitwise OR of the above flags. More...
 
typedef TableWriter< KaldiObjectHolder< RegtreeFmllrDiagGmm > > RegtreeFmllrDiagGmmWriter
 
typedef RandomAccessTableReader< KaldiObjectHolder< RegtreeFmllrDiagGmm > > RandomAccessRegtreeFmllrDiagGmmReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< RegtreeFmllrDiagGmm > > RandomAccessRegtreeFmllrDiagGmmReaderMapped
 
typedef SequentialTableReader< KaldiObjectHolder< RegtreeFmllrDiagGmm > > RegtreeFmllrDiagGmmSeqReader
 
typedef TableWriter< KaldiObjectHolder< RegtreeMllrDiagGmm > > RegtreeMllrDiagGmmWriter
 
typedef RandomAccessTableReader< KaldiObjectHolder< RegtreeMllrDiagGmm > > RandomAccessRegtreeMllrDiagGmmReader
 
typedef RandomAccessTableReaderMapped< KaldiObjectHolder< RegtreeMllrDiagGmm > > RandomAccessRegtreeMllrDiagGmmReaderMapped
 
typedef SequentialTableReader< KaldiObjectHolder< RegtreeMllrDiagGmm > > RegtreeMllrDiagGmmSeqReader
 
typedef unordered_map< std::pair< int32, std::vector< int32 > >, fst::VectorFst< fst::StdArc > *, HmmCacheHashHmmCacheType
 HmmCacheType is a map from (central-phone, sequence of pdf-ids) to FST, used as cache in GetHmmAsFsa, as an optimization. More...
 
typedef std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
 Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an utterance. More...
 
typedef std::vector< std::vector< std::pair< int32, Vector< BaseFloat > > > > GaussPost
 GaussPost is a typedef for storing Gaussian-level posteriors for an utterance. More...
 
typedef TableWriter< PosteriorHolderPosteriorWriter
 
typedef SequentialTableReader< PosteriorHolderSequentialPosteriorReader
 
typedef RandomAccessTableReader< PosteriorHolderRandomAccessPosteriorReader
 
typedef TableWriter< GaussPostHolderGaussPostWriter
 
typedef SequentialTableReader< GaussPostHolderSequentialGaussPostReader
 
typedef RandomAccessTableReader< GaussPostHolderRandomAccessGaussPostReader
 
typedef LatticeFasterDecoderConfig LatticeBiglmFasterDecoderConfig
 
typedef LatticeFasterDecoderTpl< fst::StdFst, decoder::StdTokenLatticeFasterDecoder
 
typedef LatticeFasterOnlineDecoderTpl< fst::StdFst > LatticeFasterOnlineDecoder
 
typedef LatticeIncrementalDecoderTpl< fst::StdFst, decoder::StdTokenLatticeIncrementalDecoder
 
typedef LatticeIncrementalOnlineDecoderTpl< fst::StdFst > LatticeIncrementalOnlineDecoder
 
typedef fst::LatticeWeightTpl< BaseFloatLatticeWeight
 
typedef fst::CompactLatticeWeightTpl< LatticeWeight, int32CompactLatticeWeight
 
typedef fst::CompactLatticeWeightCommonDivisorTpl< LatticeWeight, int32CompactLatticeWeightCommonDivisor
 
typedef fst::ArcTpl< LatticeWeightLatticeArc
 
typedef fst::ArcTpl< CompactLatticeWeightCompactLatticeArc
 
typedef fst::VectorFst< LatticeArcLattice
 
typedef fst::VectorFst< CompactLatticeArcCompactLattice
 
typedef TableWriter< LatticeHolderLatticeWriter
 
typedef SequentialTableReader< LatticeHolderSequentialLatticeReader
 
typedef RandomAccessTableReader< LatticeHolderRandomAccessLatticeReader
 
typedef TableWriter< CompactLatticeHolderCompactLatticeWriter
 
typedef SequentialTableReader< CompactLatticeHolderSequentialCompactLatticeReader
 
typedef RandomAccessTableReader< CompactLatticeHolderRandomAccessCompactLatticeReader
 
typedef Lattice::StateId StateId
 
typedef Lattice::Arc Arc
 
typedef fst::StdArc::Label Label
 
typedef std::vector< std::pair< Label, Label > > LabelPairVector
 
typedef KaldiObjectHolder< Sgmm2GauPostSgmm2GauPostHolder
 
typedef RandomAccessTableReader< Sgmm2GauPostHolderRandomAccessSgmm2GauPostReader
 
typedef SequentialTableReader< Sgmm2GauPostHolderSequentialSgmm2GauPostReader
 
typedef TableWriter< Sgmm2GauPostHolderSgmm2GauPostWriter
 
typedef fst::LexicographicWeight< TropicalWeight, TropicalWeight > StdLStdWeight
 
typedef fst::LexicographicWeight< TropicalWeight, StdLStdWeightStdLStdLStdWeight
 
typedef fst::ArcTpl< StdLStdLStdWeightStdLStdLStdArc
 
typedef fst::ProductWeight< TropicalWeight, ArcticWeightStdXStdprimeWeight
 
typedef fst::ProductWeight< LogWeight, StdXStdprimeWeightLogXStdXStdprimeWeight
 
typedef fst::ArcTpl< LogXStdXStdprimeWeightLogXStdXStdprimeArc
 
typedef StdLStdLStdWeight KwsLexicographicWeight
 
typedef StdLStdLStdArc KwsLexicographicArc
 
typedef fst::VectorFst< KwsLexicographicArcKwsLexicographicFst
 
typedef LogXStdXStdprimeWeight KwsProductWeight
 
typedef LogXStdXStdprimeArc KwsProductArc
 
typedef fst::VectorFst< KwsProductArcKwsProductFst
 
typedef Arc::Weight Weight
 
typedef kaldi::int32 int32
 
typedef SingleUtteranceNnet3DecoderTpl< fst::Fst< fst::StdArc > > SingleUtteranceNnet3Decoder
 
typedef SingleUtteranceNnet3IncrementalDecoderTpl< fst::Fst< fst::StdArc > > SingleUtteranceNnet3IncrementalDecoder
 

Enumerations

enum  CompressionMethod {
  kAutomaticMethod = 1, kSpeechFeature = 2, kTwoByteAuto = 3, kTwoByteSignedInteger = 4,
  kOneByteAuto = 5, kOneByteUnsignedInteger = 6, kOneByteZeroOne = 7
}
 
enum  MatrixTransposeType { kTrans = 112, kNoTrans = 111 }
 
enum  MatrixResizeType { kSetZero, kUndefined, kCopyData }
 
enum  MatrixStrideType { kDefaultStride, kStrideEqualNumCols }
 
enum  SpCopyType { kTakeLower, kTakeUpper, kTakeMean, kTakeMeanAndCheck }
 
enum  GeneralMatrixType { kFullMatrix, kCompressedMatrix, kSparseMatrix }
 
enum  OutputType { kNoOutput, kFileOutput, kStandardOutput, kPipeOutput }
 
enum  InputType {
  kNoInput, kFileInput, kStandardInput, kOffsetFileInput,
  kPipeInput
}
 
enum  WspecifierType { kNoWspecifier, kArchiveWspecifier, kScriptWspecifier, kBothWspecifier }
 
enum  RspecifierType { kNoRspecifier, kArchiveRspecifier, kScriptRspecifier }
 
enum  ShellType { kBash = 0 }
 
enum  AllKeysType { kAllKeysInsistIdentical, kAllKeysIntersection, kAllKeysUnion }
 Typedef used when we get "all keys" from a set of stats– used in specifying which kinds of questions to ask. More...
 
enum  GmmUpdateFlags {
  kGmmMeans = 0x001, kGmmVariances = 0x002, kGmmWeights = 0x004, kGmmTransitions = 0x008,
  kGmmAll = 0x00F
}
 
enum  SgmmUpdateFlags {
  kSgmmPhoneVectors = 0x001, kSgmmPhoneProjections = 0x002, kSgmmPhoneWeightProjections = 0x004, kSgmmCovarianceMatrix = 0x008,
  kSgmmSubstateWeights = 0x010, kSgmmSpeakerProjections = 0x020, kSgmmTransitions = 0x040, kSgmmSpeakerWeightProjections = 0x080,
  kSgmmAll = 0x0FF
}
 
enum  SgmmWriteFlags {
  kSgmmGlobalParams = 0x001, kSgmmStateParams = 0x002, kSgmmNormalizers = 0x004, kSgmmBackgroundGmms = 0x008,
  kSgmmWriteAll = 0x00F
}
 
enum  cova_type { full, diag }
 Generate features for a certain covariance type covariance_type == 0: full covariance covariance_type == 1: diagonal covariance. More...
 
enum  { kEps = 0, kDisambig, kBos, kEos }
 
enum  CuCompressedMatrixType { kCompressedMatrixInt8 = 1, kCompressedMatrixUint8 = 2, kCompressedMatrixInt16 = 3, kCompressedMatrixUint16 = 4 }
 
enum  DetectionDecision {
  kKwsFalseAlarm, kKwsMiss, kKwsCorr, kKwsCorrUndetected,
  kKwsUnseen
}
 

Functions

template<class T >
void WriteBasicType (std::ostream &os, bool binary, T t)
 WriteBasicType is the name of the write function for bool, integer types, and floating-point types. More...
 
template<class T >
void ReadBasicType (std::istream &is, bool binary, T *t)
 ReadBasicType is the name of the read function for bool, integer types, and floating-point types. More...
 
template<class T >
void WriteIntegerPairVector (std::ostream &os, bool binary, const std::vector< std::pair< T, T > > &v)
 Function for writing STL vectors of pairs of integer types. More...
 
template<class T >
void ReadIntegerPairVector (std::istream &is, bool binary, std::vector< std::pair< T, T > > *v)
 Function for reading STL vector of pairs of integer types. More...
 
template<class T >
void WriteIntegerVector (std::ostream &os, bool binary, const std::vector< T > &v)
 Function for writing STL vectors of integer types. More...
 
template<class T >
void ReadIntegerVector (std::istream &is, bool binary, std::vector< T > *v)
 Function for reading STL vector of integer types. More...
 
void InitKaldiOutputStream (std::ostream &os, bool binary)
 InitKaldiOutputStream initializes an opened stream for writing by writing an optional binary header and modifying the floating-point precision; it will typically not be called by users directly. More...
 
bool InitKaldiInputStream (std::istream &is, bool *binary)
 Initialize an opened stream for reading by detecting the binary header and. More...
 
void UnitTestIo (bool binary)
 
template<>
void WriteBasicType< bool > (std::ostream &os, bool binary, bool b)
 
template<>
void ReadBasicType< bool > (std::istream &is, bool binary, bool *b)
 
template<>
void WriteBasicType< float > (std::ostream &os, bool binary, float f)
 
template<>
void WriteBasicType< double > (std::ostream &os, bool binary, double f)
 
template<>
void ReadBasicType< float > (std::istream &is, bool binary, float *f)
 
template<>
void ReadBasicType< double > (std::istream &is, bool binary, double *d)
 
void CheckToken (const char *token)
 
void WriteToken (std::ostream &os, bool binary, const char *token)
 The WriteToken functions are for writing nonempty sequences of non-space characters. More...
 
int Peek (std::istream &is, bool binary)
 Peek consumes whitespace (if binary == false) and then returns the peek() value of the stream. More...
 
void WriteToken (std::ostream &os, bool binary, const std::string &token)
 
void ReadToken (std::istream &is, bool binary, std::string *token)
 ReadToken gets the next token and puts it in str (exception on failure). More...
 
int PeekToken (std::istream &is, bool binary)
 PeekToken will return the first character of the next token, or -1 if end of file. More...
 
void ExpectToken (std::istream &is, bool binary, const char *token)
 ExpectToken tries to read in the given token, and throws an exception on failure. More...
 
void ExpectToken (std::istream &is, bool binary, const std::string &token)
 
template<class T >
void ReadBasicType (std::istream &is, bool binary, T *t, bool add)
 
void ExpectPretty (std::istream &is, bool binary, const char *token)
 ExpectPretty attempts to read the text in "token", but only in non-binary mode. More...
 
void ExpectPretty (std::istream &is, bool binary, const std::string &token)
 
void MyFunction2 ()
 
void MyFunction1 ()
 
void UnitTestError ()
 
void VerifySymbolRange (const std::string &trace, const bool want_found, const std::string &want_symbol)
 
void TestLocateSymbolRange ()
 
void SetProgramName (const char *basename)
 Called by ParseOptions to set base name (no directory) of the executing program. More...
 
static const char * GetShortFileName (const char *path)
 
static std::string KaldiGetStackTrace ()
 
void KaldiAssertFailure_ (const char *func, const char *file, int32 line, const char *cond_str)
 
LogHandler SetLogHandler (LogHandler)
 Set logging handler. More...
 
int32 GetVerboseLevel ()
 Get verbosity level, usually set via command line '–verbose=' switch. More...
 
void SetVerboseLevel (int32 i)
 This should be rarely used, except by programs using Kaldi as library; command-line programs set the verbose level automatically from ParseOptions. More...
 
template<class I >
void UnitTestGcdLcmTpl ()
 
void UnitTestRoundUpToNearestPowerOfTwo ()
 
void UnitTestDivideRoundingDown ()
 
void UnitTestGcdLcm ()
 
void UnitTestRand ()
 
void UnitTestLogAddSub ()
 
void UnitTestDefines ()
 
void UnitTestAssertFunc ()
 
template<class I >
void UnitTestFactorizeTpl ()
 
void UnitTestFactorize ()
 
void UnitTestApproxEqual ()
 
template<class Real >
void UnitTestExpSpeed ()
 
template<class Real >
void UnitTestLogSpeed ()
 
int32 RoundUpToNearestPowerOfTwo (int32 n)
 
int Rand (struct RandomState *state)
 
bool WithProb (BaseFloat prob, struct RandomState *state)
 
int32 RandInt (int32 min_val, int32 max_val, struct RandomState *state)
 
int32 RandPoisson (float lambda, struct RandomState *state)
 
void RandGauss2 (float *a, float *b, RandomState *state)
 
void RandGauss2 (double *a, double *b, RandomState *state)
 
double Exp (double x)
 
float Exp (float x)
 
double Log (double x)
 
float Log (float x)
 
double Log1p (double x)
 
float Log1p (float x)
 
float RandUniform (struct RandomState *state=NULL)
 Returns a random number strictly between 0 and 1. More...
 
float RandGauss (struct RandomState *state=NULL)
 
template<class Float >
Float RandPrune (Float post, BaseFloat prune_thresh, struct RandomState *state=NULL)
 
double LogAdd (double x, double y)
 
float LogAdd (float x, float y)
 
double LogSub (double x, double y)
 
float LogSub (float x, float y)
 
static bool ApproxEqual (float a, float b, float relative_tolerance=0.001)
 return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)). More...
 
static void AssertEqual (float a, float b, float relative_tolerance=0.001)
 assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b)) More...
 
static int32 DivideRoundingDown (int32 a, int32 b)
 Returns a / b, rounding towards negative infinity in all cases. More...
 
template<class I >
Gcd (I m, I n)
 
template<class I >
Lcm (I m, I n)
 Returns the least common multiple of two integers. More...
 
template<class I >
void Factorize (I m, std::vector< I > *factors)
 
double Hypot (double x, double y)
 
float Hypot (float x, float y)
 
std::string CharToString (const char &c)
 
void Sleep (float seconds)
 
int MachineIsLittleEndian ()
 
void TimerTest ()
 
void cblas_Xcopy (const int N, const float *X, const int incX, float *Y, const int incY)
 
void cblas_Xcopy (const int N, const double *X, const int incX, double *Y, const int incY)
 
float cblas_Xasum (const int N, const float *X, const int incX)
 
double cblas_Xasum (const int N, const double *X, const int incX)
 
void cblas_Xrot (const int N, float *X, const int incX, float *Y, const int incY, const float c, const float s)
 
void cblas_Xrot (const int N, double *X, const int incX, double *Y, const int incY, const double c, const double s)
 
float cblas_Xdot (const int N, const float *const X, const int incX, const float *const Y, const int incY)
 
double cblas_Xdot (const int N, const double *const X, const int incX, const double *const Y, const int incY)
 
void cblas_Xaxpy (const int N, const float alpha, const float *X, const int incX, float *Y, const int incY)
 
void cblas_Xaxpy (const int N, const double alpha, const double *X, const int incX, double *Y, const int incY)
 
void cblas_Xscal (const int N, const float alpha, float *data, const int inc)
 
void cblas_Xscal (const int N, const double alpha, double *data, const int inc)
 
void cblas_Xspmv (const float alpha, const int num_rows, const float *Mdata, const float *v, const int v_inc, const float beta, float *y, const int y_inc)
 
void cblas_Xspmv (const double alpha, const int num_rows, const double *Mdata, const double *v, const int v_inc, const double beta, double *y, const int y_inc)
 
void cblas_Xtpmv (MatrixTransposeType trans, const float *Mdata, const int num_rows, float *y, const int y_inc)
 
void cblas_Xtpmv (MatrixTransposeType trans, const double *Mdata, const int num_rows, double *y, const int y_inc)
 
void cblas_Xtpsv (MatrixTransposeType trans, const float *Mdata, const int num_rows, float *y, const int y_inc)
 
void cblas_Xtpsv (MatrixTransposeType trans, const double *Mdata, const int num_rows, double *y, const int y_inc)
 
void cblas_Xspmv (MatrixIndexT dim, float alpha, const float *Mdata, const float *ydata, MatrixIndexT ystride, float beta, float *xdata, MatrixIndexT xstride)
 
void cblas_Xspmv (MatrixIndexT dim, double alpha, const double *Mdata, const double *ydata, MatrixIndexT ystride, double beta, double *xdata, MatrixIndexT xstride)
 
void cblas_Xspr2 (MatrixIndexT dim, float alpha, const float *Xdata, MatrixIndexT incX, const float *Ydata, MatrixIndexT incY, float *Adata)
 
void cblas_Xspr2 (MatrixIndexT dim, double alpha, const double *Xdata, MatrixIndexT incX, const double *Ydata, MatrixIndexT incY, double *Adata)
 
void cblas_Xspr (MatrixIndexT dim, float alpha, const float *Xdata, MatrixIndexT incX, float *Adata)
 
void cblas_Xspr (MatrixIndexT dim, double alpha, const double *Xdata, MatrixIndexT incX, double *Adata)
 
void cblas_Xgemv (MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, float alpha, const float *Mdata, MatrixIndexT stride, const float *xdata, MatrixIndexT incX, float beta, float *ydata, MatrixIndexT incY)
 
void cblas_Xgemv (MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, double alpha, const double *Mdata, MatrixIndexT stride, const double *xdata, MatrixIndexT incX, double beta, double *ydata, MatrixIndexT incY)
 
void cblas_Xgbmv (MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, MatrixIndexT num_below, MatrixIndexT num_above, float alpha, const float *Mdata, MatrixIndexT stride, const float *xdata, MatrixIndexT incX, float beta, float *ydata, MatrixIndexT incY)
 
void cblas_Xgbmv (MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, MatrixIndexT num_below, MatrixIndexT num_above, double alpha, const double *Mdata, MatrixIndexT stride, const double *xdata, MatrixIndexT incX, double beta, double *ydata, MatrixIndexT incY)
 
template<typename Real >
void Xgemv_sparsevec (MatrixTransposeType trans, MatrixIndexT num_rows, MatrixIndexT num_cols, Real alpha, const Real *Mdata, MatrixIndexT stride, const Real *xdata, MatrixIndexT incX, Real beta, Real *ydata, MatrixIndexT incY)
 
void cblas_Xgemm (const float alpha, MatrixTransposeType transA, const float *Adata, MatrixIndexT a_num_rows, MatrixIndexT a_num_cols, MatrixIndexT a_stride, MatrixTransposeType transB, const float *Bdata, MatrixIndexT b_stride, const float beta, float *Mdata, MatrixIndexT num_rows, MatrixIndexT num_cols, MatrixIndexT stride)
 
void cblas_Xgemm (const double alpha, MatrixTransposeType transA, const double *Adata, MatrixIndexT a_num_rows, MatrixIndexT a_num_cols, MatrixIndexT a_stride, MatrixTransposeType transB, const double *Bdata, MatrixIndexT b_stride, const double beta, double *Mdata, MatrixIndexT num_rows, MatrixIndexT num_cols, MatrixIndexT stride)
 
void cblas_Xsymm (const float alpha, MatrixIndexT sz, const float *Adata, MatrixIndexT a_stride, const float *Bdata, MatrixIndexT b_stride, const float beta, float *Mdata, MatrixIndexT stride)
 
void cblas_Xsymm (const double alpha, MatrixIndexT sz, const double *Adata, MatrixIndexT a_stride, const double *Bdata, MatrixIndexT b_stride, const double beta, double *Mdata, MatrixIndexT stride)
 
void cblas_Xger (MatrixIndexT num_rows, MatrixIndexT num_cols, float alpha, const float *xdata, MatrixIndexT incX, const float *ydata, MatrixIndexT incY, float *Mdata, MatrixIndexT stride)
 
void cblas_Xger (MatrixIndexT num_rows, MatrixIndexT num_cols, double alpha, const double *xdata, MatrixIndexT incX, const double *ydata, MatrixIndexT incY, double *Mdata, MatrixIndexT stride)
 
void cblas_Xsyrk (const MatrixTransposeType trans, const MatrixIndexT dim_c, const MatrixIndexT other_dim_a, const float alpha, const float *A, const MatrixIndexT a_stride, const float beta, float *C, const MatrixIndexT c_stride)
 
void cblas_Xsyrk (const MatrixTransposeType trans, const MatrixIndexT dim_c, const MatrixIndexT other_dim_a, const double alpha, const double *A, const MatrixIndexT a_stride, const double beta, double *C, const MatrixIndexT c_stride)
 
void cblas_Xsbmv1 (const MatrixIndexT dim, const double *A, const double alpha, const double *x, const double beta, double *y)
 matrix-vector multiply using a banded matrix; we always call this with b = 1 meaning we're multiplying by a diagonal matrix. More...
 
void cblas_Xsbmv1 (const MatrixIndexT dim, const float *A, const float alpha, const float *x, const float beta, float *y)
 
void mul_elements (const MatrixIndexT dim, const double *a, double *b)
 This is not really a wrapper for CBLAS as CBLAS does not have this; in future we could extend this somehow. More...
 
void mul_elements (const MatrixIndexT dim, const float *a, float *b)
 
void clapack_Xtptri (KaldiBlasInt *num_rows, float *Mdata, KaldiBlasInt *result)
 
void clapack_Xtptri (KaldiBlasInt *num_rows, double *Mdata, KaldiBlasInt *result)
 
void clapack_Xgetrf2 (KaldiBlasInt *num_rows, KaldiBlasInt *num_cols, float *Mdata, KaldiBlasInt *stride, KaldiBlasInt *pivot, KaldiBlasInt *result)
 
void clapack_Xgetrf2 (KaldiBlasInt *num_rows, KaldiBlasInt *num_cols, double *Mdata, KaldiBlasInt *stride, KaldiBlasInt *pivot, KaldiBlasInt *result)
 
void clapack_Xgetri2 (KaldiBlasInt *num_rows, float *Mdata, KaldiBlasInt *stride, KaldiBlasInt *pivot, float *p_work, KaldiBlasInt *l_work, KaldiBlasInt *result)
 
void clapack_Xgetri2 (KaldiBlasInt *num_rows, double *Mdata, KaldiBlasInt *stride, KaldiBlasInt *pivot, double *p_work, KaldiBlasInt *l_work, KaldiBlasInt *result)
 
void clapack_Xgesvd (char *v, char *u, KaldiBlasInt *num_cols, KaldiBlasInt *num_rows, float *Mdata, KaldiBlasInt *stride, float *sv, float *Vdata, KaldiBlasInt *vstride, float *Udata, KaldiBlasInt *ustride, float *p_work, KaldiBlasInt *l_work, KaldiBlasInt *result)
 
void clapack_Xgesvd (char *v, char *u, KaldiBlasInt *num_cols, KaldiBlasInt *num_rows, double *Mdata, KaldiBlasInt *stride, double *sv, double *Vdata, KaldiBlasInt *vstride, double *Udata, KaldiBlasInt *ustride, double *p_work, KaldiBlasInt *l_work, KaldiBlasInt *result)
 
void clapack_Xsptri (KaldiBlasInt *num_rows, float *Mdata, KaldiBlasInt *ipiv, float *work, KaldiBlasInt *result)
 
void clapack_Xsptri (KaldiBlasInt *num_rows, double *Mdata, KaldiBlasInt *ipiv, double *work, KaldiBlasInt *result)
 
void clapack_Xsptrf (KaldiBlasInt *num_rows, float *Mdata, KaldiBlasInt *ipiv, KaldiBlasInt *result)
 
void clapack_Xsptrf (KaldiBlasInt *num_rows, double *Mdata, KaldiBlasInt *ipiv, KaldiBlasInt *result)
 
template<typename Real >
std::ostream & operator<< (std::ostream &os, const MatrixBase< Real > &M)
 
template<typename Real >
std::istream & operator>> (std::istream &is, Matrix< Real > &M)
 
template<typename Real >
std::istream & operator>> (std::istream &is, MatrixBase< Real > &M)
 
template<typename Real >
bool ReadHtk (std::istream &is, Matrix< Real > *M_ptr, HtkHeader *header_ptr)
 Extension of the HTK header. More...
 
template bool ReadHtk (std::istream &is, Matrix< float > *M, HtkHeader *header_ptr)
 
template bool ReadHtk (std::istream &is, Matrix< double > *M, HtkHeader *header_ptr)
 
template<typename Real >
bool WriteHtk (std::ostream &os, const MatrixBase< Real > &M, HtkHeader htk_hdr)
 
template bool WriteHtk (std::ostream &os, const MatrixBase< float > &M, HtkHeader htk_hdr)
 
template bool WriteHtk (std::ostream &os, const MatrixBase< double > &M, HtkHeader htk_hdr)
 
template<class Real >
bool WriteSphinx (std::ostream &os, const MatrixBase< Real > &M)
 
template bool WriteSphinx (std::ostream &os, const MatrixBase< float > &M)
 
template bool WriteSphinx (std::ostream &os, const MatrixBase< double > &M)
 
template<typename Real >
Real TraceMatMatMat (const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const MatrixBase< Real > &C, MatrixTransposeType transC)
 Returns tr(A B C) More...
 
template float TraceMatMatMat (const MatrixBase< float > &A, MatrixTransposeType transA, const MatrixBase< float > &B, MatrixTransposeType transB, const MatrixBase< float > &C, MatrixTransposeType transC)
 
template double TraceMatMatMat (const MatrixBase< double > &A, MatrixTransposeType transA, const MatrixBase< double > &B, MatrixTransposeType transB, const MatrixBase< double > &C, MatrixTransposeType transC)
 
template<typename Real >
Real TraceMatMatMatMat (const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const MatrixBase< Real > &C, MatrixTransposeType transC, const MatrixBase< Real > &D, MatrixTransposeType transD)
 Returns tr(A B C D) More...
 
template float TraceMatMatMatMat (const MatrixBase< float > &A, MatrixTransposeType transA, const MatrixBase< float > &B, MatrixTransposeType transB, const MatrixBase< float > &C, MatrixTransposeType transC, const MatrixBase< float > &D, MatrixTransposeType transD)
 
template double TraceMatMatMatMat (const MatrixBase< double > &A, MatrixTransposeType transA, const MatrixBase< double > &B, MatrixTransposeType transB, const MatrixBase< double > &C, MatrixTransposeType transC, const MatrixBase< double > &D, MatrixTransposeType transD)
 
template<typename Real >
void SortSvd (VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt=NULL, bool sort_on_absolute_value=true)
 Function to ensure that SVD is sorted. More...
 
template void SortSvd (VectorBase< float > *s, MatrixBase< float > *U, MatrixBase< float > *Vt, bool)
 
template void SortSvd (VectorBase< double > *s, MatrixBase< double > *U, MatrixBase< double > *Vt, bool)
 
template<typename Real >
void CreateEigenvalueMatrix (const VectorBase< Real > &real, const VectorBase< Real > &imag, MatrixBase< Real > *D)
 Creates the eigenvalue matrix D that is part of the decomposition used Matrix::Eig. More...
 
template void CreateEigenvalueMatrix (const VectorBase< float > &re, const VectorBase< float > &im, MatrixBase< float > *D)
 
template void CreateEigenvalueMatrix (const VectorBase< double > &re, const VectorBase< double > &im, MatrixBase< double > *D)
 
template<typename Real >
bool AttemptComplexPower (Real *x_re, Real *x_im, Real power)
 The following function is used in Matrix::Power, and separately tested, so we declare it here mainly for the testing code to see. More...
 
template bool AttemptComplexPower (float *x_re, float *x_im, float power)
 
template bool AttemptComplexPower (double *x_re, double *x_im, double power)
 
template float TraceMatMat (const MatrixBase< float > &A, const MatrixBase< float > &B, MatrixTransposeType trans)
 
template double TraceMatMat (const MatrixBase< double > &A, const MatrixBase< double > &B, MatrixTransposeType trans)
 
template<typename Real >
bool ApproxEqual (const MatrixBase< Real > &A, const MatrixBase< Real > &B, Real tol=0.01)
 
template<typename Real >
void AssertEqual (const MatrixBase< Real > &A, const MatrixBase< Real > &B, float tol=0.01)
 
template<typename Real >
double TraceMat (const MatrixBase< Real > &A)
 Returns trace of matrix. More...
 
template<typename Real >
bool SameDim (const MatrixBase< Real > &M, const MatrixBase< Real > &N)
 
template<typename Real >
std::ostream & operator<< (std::ostream &os, const VectorBase< Real > &rv)
 
template<typename Real >
std::istream & operator>> (std::istream &in, VectorBase< Real > &v)
 Input from a C++ stream. More...
 
template<typename Real >
std::istream & operator>> (std::istream &in, Vector< Real > &v)
 Input from a C++ stream. More...
 
template<typename Real >
Real VecVec (const VectorBase< Real > &v1, const VectorBase< Real > &v2)
 Returns dot product between v1 and v2. More...
 
template float VecVec (const VectorBase< float > &a, const VectorBase< float > &b)
 
template double VecVec (const VectorBase< double > &a, const VectorBase< double > &b)
 
template<typename Real , typename OtherReal >
Real VecVec (const VectorBase< Real > &ra, const VectorBase< OtherReal > &rb)
 
template float VecVec (const VectorBase< float > &ra, const VectorBase< double > &rb)
 
template double VecVec (const VectorBase< double > &ra, const VectorBase< float > &rb)
 
template<typename Real >
Real VecMatVec (const VectorBase< Real > &v1, const MatrixBase< Real > &M, const VectorBase< Real > &v2)
 Returns $ v_1^T M v_2 $ . More...
 
template float VecMatVec (const VectorBase< float > &v1, const MatrixBase< float > &M, const VectorBase< float > &v2)
 
template double VecMatVec (const VectorBase< double > &v1, const MatrixBase< double > &M, const VectorBase< double > &v2)
 
template<typename Real >
bool ApproxEqual (const VectorBase< Real > &a, const VectorBase< Real > &b, Real tol=0.01)
 
template<typename Real >
void AssertEqual (VectorBase< Real > &a, VectorBase< Real > &b, float tol=0.01)
 
template<typename Real >
void ComplexMul (const Real &a_re, const Real &a_im, Real *b_re, Real *b_im)
 ComplexMul implements, inline, the complex multiplication b *= a. More...
 
template<typename Real >
void ComplexAddProduct (const Real &a_re, const Real &a_im, const Real &b_re, const Real &b_im, Real *c_re, Real *c_im)
 ComplexMul implements, inline, the complex operation c += (a * b). More...
 
template<typename Real >
void ComplexImExp (Real x, Real *a_re, Real *a_im)
 ComplexImExp implements a <– exp(i x), inline. More...
 
template<typename Real >
void ComplexFt (const VectorBase< Real > &in, VectorBase< Real > *out, bool forward)
 ComplexFt is the same as ComplexFft but it implements the Fourier transform in an inefficient way. More...
 
template void ComplexFt (const VectorBase< float > &in, VectorBase< float > *out, bool forward)
 
template void ComplexFt (const VectorBase< double > &in, VectorBase< double > *out, bool forward)
 
template<typename Real >
void ComplexFftRecursive (Real *data, int nffts, int N, const int *factor_begin, const int *factor_end, bool forward, Vector< Real > *tmp_vec)
 ComplexFftRecursive is a recursive function that computes the complex FFT of size N. More...
 
template<typename Real >
void ComplexFft (VectorBase< Real > *v, bool forward, Vector< Real > *tmp_work=NULL)
 The function ComplexFft does an Fft on the vector argument v. More...
 
template<typename Real >
void RealFftInefficient (VectorBase< Real > *v, bool forward)
 Inefficient version of Fourier transform, for testing purposes. More...
 
template void RealFftInefficient (VectorBase< float > *v, bool forward)
 
template void RealFftInefficient (VectorBase< double > *v, bool forward)
 
template void ComplexFft (VectorBase< float > *v, bool forward, Vector< float > *tmp_in)
 
template void ComplexFft (VectorBase< double > *v, bool forward, Vector< double > *tmp_in)
 
template<typename Real >
void RealFft (VectorBase< Real > *v, bool forward)
 RealFft is a fourier transform of real inputs. More...
 
template void RealFft (VectorBase< float > *v, bool forward)
 
template void RealFft (VectorBase< double > *v, bool forward)
 
template<typename Real >
void ComputeDctMatrix (Matrix< Real > *M)
 ComputeDctMatrix computes a matrix corresponding to the DCT, such that M * v equals the DCT of vector v. More...
 
template void ComputeDctMatrix (Matrix< float > *M)
 
template void ComputeDctMatrix (Matrix< double > *M)
 
template<typename Real >
void ComputePca (const MatrixBase< Real > &X, MatrixBase< Real > *U, MatrixBase< Real > *A, bool print_eigs=false, bool exact=true)
 ComputePCA does a PCA computation, using either outer products or inner products, whichever is more efficient. More...
 
template void ComputePca (const MatrixBase< float > &X, MatrixBase< float > *U, MatrixBase< float > *A, bool print_eigs, bool exact)
 
template void ComputePca (const MatrixBase< double > &X, MatrixBase< double > *U, MatrixBase< double > *A, bool print_eigs, bool exact)
 
template<typename Real >
void AddOuterProductPlusMinus (Real alpha, const VectorBase< Real > &a, const VectorBase< Real > &b, MatrixBase< Real > *plus, MatrixBase< Real > *minus)
 
template void AddOuterProductPlusMinus< float > (float alpha, const VectorBase< float > &a, const VectorBase< float > &b, MatrixBase< float > *plus, MatrixBase< float > *minus)
 
template void AddOuterProductPlusMinus< double > (double alpha, const VectorBase< double > &a, const VectorBase< double > &b, MatrixBase< double > *plus, MatrixBase< double > *minus)
 
template<typename Real1 , typename Real2 >
void AssertSameDim (const MatrixBase< Real1 > &mat1, const MatrixBase< Real2 > &mat2)
 
template<typename Real >
std::string NameOf ()
 
template<typename Real >
static void CsvResult (std::string test, int dim, BaseFloat measure, std::string units)
 
template<typename Real >
static void UnitTestRealFftSpeed ()
 
template<typename Real >
static void UnitTestSplitRadixRealFftSpeed ()
 
template<typename Real >
static void UnitTestSvdSpeed ()
 
template<typename Real >
static void UnitTestAddMatMatSpeed ()
 
template<typename Real >
static void UnitTestAddRowSumMatSpeed ()
 
template<typename Real >
static void UnitTestAddColSumMatSpeed ()
 
template<typename Real >
static void UnitTestAddVecToRowsSpeed ()
 
template<typename Real >
static void UnitTestAddVecToColsSpeed ()
 
template<typename Real >
static void MatrixUnitSpeedTest ()
 
template<typename Real >
void RandPosdefSpMatrix (MatrixIndexT dim, SpMatrix< Real > *matrix)
 
template<typename Real >
static void InitRandNonsingular (MatrixBase< Real > *M)
 
template<typename Real >
static void InitRandNonsingular (SpMatrix< Real > *M)
 
template<typename Real >
static void CholeskyUnitTestTr ()
 
template<typename Real >
static void SlowMatMul ()
 
template<typename Real >
static void UnitTestAddToDiagMatrix ()
 
template<typename Real >
static void UnitTestAddDiagVecMat ()
 
template<typename Real >
static void UnitTestAddMatDiagVec ()
 
template<typename Real >
static void UnitTestAddMatMatElements ()
 
template<typename Real >
static void UnitTestAddSp ()
 
template<typename Real , typename OtherReal >
static void UnitTestSpAddDiagVec ()
 
template<typename Real >
static void UnitTestSpAddVecVec ()
 
template<typename Real >
static void UnitTestCopyRowsAndCols ()
 
template<typename Real >
static void UnitTestSpliceRows ()
 
template<typename Real >
static void UnitTestRemoveRow ()
 
template<typename Real >
static void UnitTestSubvector ()
 
static int32 DoubleFactorial (int32 i)
 
template<typename Real >
static void UnitTestSetRandn ()
 
template<typename Real >
static void UnitTestSetRandUniform ()
 
template<typename Real >
static void UnitTestSimpleForVec ()
 
template<typename Real >
static void UnitTestVectorMax ()
 
template<typename Real >
static void UnitTestVectorMin ()
 
template<typename Real >
static void UnitTestReplaceValue ()
 
template<typename Real >
static void UnitTestNorm ()
 
template<typename Real >
static void UnitTestCopyRows ()
 
template<typename Real >
static void UnitTestCopyToRows ()
 
template<typename Real >
static void UnitTestAddRows ()
 
template<typename Real >
static void UnitTestAddToRows ()
 
template<typename Real >
static void UnitTestCopyCols ()
 
template<typename Real >
static void UnitTestSimpleForMat ()
 
template<typename Real >
static void UnitTestRow ()
 
template<typename Real >
static void UnitTestAxpy ()
 
template<typename Real >
static void UnitTestCopySp ()
 
template<typename Real >
static void UnitTestPower ()
 
template<typename Real >
static void UnitTestPowerAbs ()
 
template<typename Real >
static void UnitTestHeaviside ()
 
template<typename Real >
static void UnitTestAddOuterProductPlusMinus ()
 
template<typename Real >
static void UnitTestSger ()
 
template<typename Real >
static void UnitTestDeterminant ()
 
template<typename Real >
static void UnitTestDeterminantSign ()
 
template<typename Real >
static void UnitTestSpVec ()
 
template<typename Real >
static void UnitTestTraceProduct ()
 
template<typename Real >
static void UnitTestSvd ()
 
template<typename Real >
static void UnitTestSvdBad ()
 
template<typename Real >
static void UnitTestSvdZero ()
 
template<typename Real >
static void UnitTestSvdNodestroy ()
 
template<typename Real >
static void UnitTestSvdJustvec ()
 
template<typename Real >
static void UnitTestEigSymmetric ()
 
template<typename Real >
static void UnitTestEig ()
 
template<typename Real >
static void UnitTestEigSp ()
 
template<typename Real >
static Real NonOrthogonality (const MatrixBase< Real > &M, MatrixTransposeType transM)
 
template<typename Real >
static Real NonDiagonalness (const SpMatrix< Real > &S)
 
template<typename Real >
static Real NonUnitness (const SpMatrix< Real > &S)
 
template<typename Real >
static void UnitTestTridiagonalize ()
 
template<typename Real >
static void UnitTestTridiagonalizeAndQr ()
 
template<typename Real >
static void UnitTestMmul ()
 
template<typename Real >
static void UnitTestMmulSym ()
 
template<typename Real >
static void UnitTestAddVecVec ()
 
template<typename Real >
static void UnitTestVecmul ()
 
template<typename Real >
static void UnitTestInverse ()
 
template<typename Real >
static void UnitTestMulElements ()
 
template<typename Real >
static void UnitTestDotprod ()
 
template<class Real >
void PlaceNansInGaps (Matrix< Real > *mat)
 
template<typename Real >
static void UnitTestResizeCopyDataDifferentStrideType ()
 Make sure that when Resize() is called with resize_type = kCopyData and a stride_type different from this's stride_type, the resized matrix is equivalent to the original matrix (modulo the stride). More...
 
template<typename Real >
static void UnitTestResize ()
 
template<typename Real >
static void UnitTestTp2Sp ()
 
template<typename Real >
static void UnitTestTp2 ()
 
template<typename Real >
static void UnitTestAddDiagMat2 ()
 
template<typename Real >
static void UnitTestAddDiagMatMat ()
 
template<typename Real >
static void UnitTestOrthogonalizeRows ()
 
template<typename Real >
static void UnitTestTransposeScatter ()
 
template<typename Real >
static void UnitTestRankNUpdate ()
 
template<typename Real >
static void UnitTestSpInvert ()
 
template<typename Real >
static void UnitTestTpInvert ()
 
template<typename Real >
static void UnitTestLimitCondInvert ()
 
template<typename Real >
static void UnitTestFloorChol ()
 
template<typename Real >
static void UnitTestFloorUnit ()
 
template<typename Real >
static void UnitTestFloorCeiling ()
 
template<typename Real >
static void UnitTestMat2Vec ()
 
template<typename Real >
static void UnitTestLimitCond ()
 
template<typename Real >
static void UnitTestTanh ()
 
template<typename Real >
static void UnitTestSigmoid ()
 
template<typename Real >
static void UnitTestSoftHinge ()
 
template<typename Real >
static void UnitTestSimple ()
 
template<typename Real >
static void UnitTestIo ()
 
template<typename Real >
static void UnitTestIoCross ()
 
template<typename Real >
static void UnitTestHtkIo ()
 
template<typename Real >
static void UnitTestRange ()
 
template<typename Real >
static void UnitTestScale ()
 
template<typename Real >
static void UnitTestMul ()
 
template<typename Real >
static void UnitTestApplyExpSpecial ()
 
template<typename Real >
static void UnitTestInnerProd ()
 
template<typename Real >
static void UnitTestAddToDiag ()
 
template<typename Real >
static void UnitTestScaleDiag ()
 
template<typename Real >
static void UnitTestSetDiag ()
 
template<typename Real >
static void UnitTestTraceSpSpLower ()
 
template<typename Real >
static void UnitTestAddMatSmat ()
 
template<typename Real >
static void UnitTestAddMat2Sp ()
 
template<typename Real >
static void UnitTestAddMatSelf ()
 
template<typename Real >
static void UnitTestAddMat2 ()
 
template<typename Real >
static void UnitTestSymAddMat2 ()
 
template<typename Real >
static void UnitTestSolve ()
 
template<typename Real >
static void UnitTestMax2 ()
 
template<typename Real >
static void UnitTestMaxAbsEig ()
 
template<typename Real >
static void UnitTestLbfgs ()
 
template<typename Real >
static void UnitTestLinearCgd ()
 
template<typename Real >
static void UnitTestMaxMin ()
 
template<typename Real >
static bool approx_equal (Real a, Real b)
 
template<typename Real >
static void UnitTestTrace ()
 
template<typename Real >
static void UnitTestComplexFt ()
 
template<typename Real >
static void UnitTestDct ()
 
template<typename Real >
static void UnitTestComplexFft ()
 
template<typename Real >
static void UnitTestSplitRadixComplexFft ()
 
template<typename Real >
static void UnitTestTranspose ()
 
template<typename Real >
static void UnitTestAddVecToRows ()
 
template<typename Real >
static void UnitTestAddVec2Sp ()
 
template<typename Real >
static void UnitTestAddVecToCols ()
 
template<typename Real >
static void UnitTestComplexFft2 ()
 
template<typename Real >
static void UnitTestSplitRadixComplexFft2 ()
 
template<typename Real >
static void UnitTestRealFft ()
 
template<typename Real >
static void UnitTestSplitRadixRealFft ()
 
template<typename Real >
static void UnitTestRealFftSpeed ()
 
template<typename Real >
static void UnitTestSplitRadixRealFftSpeed ()
 
template<typename Real >
void UnitTestComplexPower ()
 
template<typename Real >
void UnitTestNonsymmetricPower ()
 
void UnitTestAddVecCross ()
 
template<typename Real >
static void UnitTestPca (bool full_test)
 
template<typename Real >
static void UnitTestPca2 (bool full_test)
 
template<typename Real >
static void UnitTestSvdSpeed ()
 
template<typename Real >
static void UnitTestCompressedMatrix2 ()
 
template<typename Real >
static void UnitTestCompressedMatrix ()
 
template<typename Real >
static void UnitTestGeneralMatrix ()
 
template<typename Real >
static void UnitTestExtractCompressedMatrix ()
 
template<typename Real >
static void UnitTestTridiag ()
 
template<typename Real >
static void UnitTestRandCategorical ()
 
template<class Real >
static void UnitTestAddMatMatNans ()
 
template<class Real >
static void UnitTestTopEigs ()
 
template<typename Real >
static void UnitTestTriVecSolver ()
 
template<typename Real >
static void MatrixUnitTest (bool full_test)
 
template<class Real >
int32 LinearCgd (const LinearCgdOptions &opts, const SpMatrix< Real > &A, const VectorBase< Real > &b, VectorBase< Real > *x)
 
template int32 LinearCgd< float > (const LinearCgdOptions &opts, const SpMatrix< float > &A, const VectorBase< float > &b, VectorBase< float > *x)
 
template int32 LinearCgd< double > (const LinearCgdOptions &opts, const SpMatrix< double > &A, const VectorBase< double > &b, VectorBase< double > *x)
 
template<typename Real >
std::ostream & operator<< (std::ostream &out, const PackedMatrix< Real > &M)
 
template<typename Real >
std::istream & operator>> (std::istream &is, PackedMatrix< Real > &M)
 
template<typename Real >
void HouseBackward (MatrixIndexT dim, const Real *x, Real *v, Real *beta)
 
template<typename Real >
void Givens (Real a, Real b, Real *c, Real *s)
 Create Givens rotations, as in Golub and Van Loan 3rd ed., page 216. More...
 
template<typename Real >
void QrStep (MatrixIndexT n, Real *diag, Real *off_diag, MatrixBase< Real > *Q)
 
template<typename Real >
void QrInternal (MatrixIndexT n, Real *diag, Real *off_diag, MatrixBase< Real > *Q)
 
template<>
double SolveQuadraticProblem (const SpMatrix< double > &H, const VectorBase< double > &g, const SolverOptions &opts, VectorBase< double > *x)
 
template<>
float SolveQuadraticProblem (const SpMatrix< float > &H, const VectorBase< float > &g, const SolverOptions &opts, VectorBase< float > *x)
 
double TraceSpSp (const SpMatrix< double > &A, const SpMatrix< double > &B)
 
float TraceSpSp (const SpMatrix< float > &A, const SpMatrix< float > &B)
 Returns tr(A B). More...
 
template<typename Real , typename OtherReal >
Real TraceSpSp (const SpMatrix< Real > &A, const SpMatrix< OtherReal > &B)
 Returns tr(A B). More...
 
template float TraceSpSp< float, double > (const SpMatrix< float > &A, const SpMatrix< double > &B)
 
template double TraceSpSp< double, float > (const SpMatrix< double > &A, const SpMatrix< float > &B)
 
template<typename Real >
Real TraceSpMat (const SpMatrix< Real > &A, const MatrixBase< Real > &B)
 Returns tr(A B). More...
 
template float TraceSpMat (const SpMatrix< float > &A, const MatrixBase< float > &B)
 
template double TraceSpMat (const SpMatrix< double > &A, const MatrixBase< double > &B)
 
template<typename Real >
Real TraceMatSpMat (const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const MatrixBase< Real > &C, MatrixTransposeType transC)
 Returns tr(A B C) (A and C may be transposed as specified by transA and transC). More...
 
template float TraceMatSpMat (const MatrixBase< float > &A, MatrixTransposeType transA, const SpMatrix< float > &B, const MatrixBase< float > &C, MatrixTransposeType transC)
 
template double TraceMatSpMat (const MatrixBase< double > &A, MatrixTransposeType transA, const SpMatrix< double > &B, const MatrixBase< double > &C, MatrixTransposeType transC)
 
template<typename Real >
Real TraceMatSpMatSp (const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const MatrixBase< Real > &C, MatrixTransposeType transC, const SpMatrix< Real > &D)
 Returns tr (A B C D) (A and C may be transposed as specified by transA and transB). More...
 
template float TraceMatSpMatSp (const MatrixBase< float > &A, MatrixTransposeType transA, const SpMatrix< float > &B, const MatrixBase< float > &C, MatrixTransposeType transC, const SpMatrix< float > &D)
 
template double TraceMatSpMatSp (const MatrixBase< double > &A, MatrixTransposeType transA, const SpMatrix< double > &B, const MatrixBase< double > &C, MatrixTransposeType transC, const SpMatrix< double > &D)
 
template<typename Real >
Real SolveQuadraticMatrixProblem (const SpMatrix< Real > &Q, const MatrixBase< Real > &Y, const SpMatrix< Real > &P, const SolverOptions &opts, MatrixBase< Real > *M)
 Maximizes the auxiliary function :

\[ Q(x) = tr(M^T P Y) - 0.5 tr(P M Q M^T) \]

Like a numerically stable version of $ M := Y Q^{-1} $. More...

 
template<typename Real >
Real SolveDoubleQuadraticMatrixProblem (const MatrixBase< Real > &G, const SpMatrix< Real > &P1, const SpMatrix< Real > &P2, const SpMatrix< Real > &Q1, const SpMatrix< Real > &Q2, const SolverOptions &opts, MatrixBase< Real > *M)
 Maximizes the auxiliary function :

\[ Q(M) = tr(M^T G) -0.5 tr(P_1 M Q_1 M^T) -0.5 tr(P_2 M Q_2 M^T). \]

Encountered in matrix update with a prior. More...

 
template<typename Real >
Real VecSpVec (const VectorBase< Real > &v1, const SpMatrix< Real > &M, const VectorBase< Real > &v2)
 Computes v1^T * M * v2. More...
 
template float VecSpVec (const VectorBase< float > &v1, const SpMatrix< float > &M, const VectorBase< float > &v2)
 
template double VecSpVec (const VectorBase< double > &v1, const SpMatrix< double > &M, const VectorBase< double > &v2)
 
template<typename Real >
Real TraceSpSpLower (const SpMatrix< Real > &A, const SpMatrix< Real > &B)
 
template double TraceSpSpLower (const SpMatrix< double > &A, const SpMatrix< double > &B)
 
template float TraceSpSpLower (const SpMatrix< float > &A, const SpMatrix< float > &B)
 
template float SolveQuadraticMatrixProblem (const SpMatrix< float > &Q, const MatrixBase< float > &Y, const SpMatrix< float > &SigmaInv, const SolverOptions &opts, MatrixBase< float > *M)
 
template double SolveQuadraticMatrixProblem (const SpMatrix< double > &Q, const MatrixBase< double > &Y, const SpMatrix< double > &SigmaInv, const SolverOptions &opts, MatrixBase< double > *M)
 
template float SolveDoubleQuadraticMatrixProblem (const MatrixBase< float > &G, const SpMatrix< float > &P1, const SpMatrix< float > &P2, const SpMatrix< float > &Q1, const SpMatrix< float > &Q2, const SolverOptions &opts, MatrixBase< float > *M)
 
template double SolveDoubleQuadraticMatrixProblem (const MatrixBase< double > &G, const SpMatrix< double > &P1, const SpMatrix< double > &P2, const SpMatrix< double > &Q1, const SpMatrix< double > &Q2, const SolverOptions &opts, MatrixBase< double > *M)
 
template<typename Real >
bool ApproxEqual (const SpMatrix< Real > &A, const SpMatrix< Real > &B, Real tol=0.01)
 
template<typename Real >
void AssertEqual (const SpMatrix< Real > &A, const SpMatrix< Real > &B, Real tol=0.01)
 
template<typename Real >
Real SolveQuadraticProblem (const SpMatrix< Real > &H, const VectorBase< Real > &g, const SolverOptions &opts, VectorBase< Real > *x)
 Maximizes the auxiliary function

\[ Q(x) = x.g - 0.5 x^T H x \]

using a numerically stable method. More...

 
template<typename Real >
void UnitTestSparseVectorSum ()
 
template<typename Real >
void UnitTestSparseVectorAddToVec ()
 
template<typename Real >
void UnitTestSparseVectorMax ()
 
template<typename Real >
void UnitTestSparseVectorVecSvec ()
 
template<typename Real >
void UnitTestSparseMatrixSum ()
 
template<typename Real >
void UnitTestSparseMatrixFrobeniusNorm ()
 
template<typename Real >
void UnitTestSparseMatrixAddToMat ()
 
template<typename Real >
void UnitTestSparseMatrixConstructor ()
 
template<typename Real >
void UnitTestSparseMatrixTraceMatSmat ()
 
template<typename Real >
void UnitTestMatrixAddMatSmat ()
 
template<typename Real >
void UnitTestMatrixAddSmatMat ()
 
template<typename Real >
void SparseMatrixUnitTest ()
 
template<typename Real >
Real VecSvec (const VectorBase< Real > &vec, const SparseVector< Real > &svec)
 
template float VecSvec (const VectorBase< float > &vec, const SparseVector< float > &svec)
 
template double VecSvec (const VectorBase< double > &vec, const SparseVector< double > &svec)
 
template<typename Real >
Real TraceMatSmat (const MatrixBase< Real > &A, const SparseMatrix< Real > &B, MatrixTransposeType trans)
 
template float TraceMatSmat (const MatrixBase< float > &A, const SparseMatrix< float > &B, MatrixTransposeType trans)
 
template double TraceMatSmat (const MatrixBase< double > &A, const SparseMatrix< double > &B, MatrixTransposeType trans)
 
void AppendGeneralMatrixRows (const std::vector< const GeneralMatrix * > &src, GeneralMatrix *mat)
 Appends all the matrix rows of a list of GeneralMatrixes, to get a single GeneralMatrix. More...
 
void FilterCompressedMatrixRows (const CompressedMatrix &in, const std::vector< bool > &keep_rows, Matrix< BaseFloat > *out)
 Outputs a Matrix<Real> containing only the rows r of "in" such that keep_rows[r] == true. More...
 
template<typename Real >
void FilterMatrixRows (const Matrix< Real > &in, const std::vector< bool > &keep_rows, Matrix< Real > *out)
 Outputs a Matrix<Real> containing only the rows r of "in" such that keep_keep_rows[r] == true. More...
 
template void FilterMatrixRows (const Matrix< float > &in, const std::vector< bool > &keep_rows, Matrix< float > *out)
 
template void FilterMatrixRows (const Matrix< double > &in, const std::vector< bool > &keep_rows, Matrix< double > *out)
 
template<typename Real >
void FilterSparseMatrixRows (const SparseMatrix< Real > &in, const std::vector< bool > &keep_rows, SparseMatrix< Real > *out)
 Outputs a SparseMatrix<Real> containing only the rows r of "in" such that keep_rows[r] == true. More...
 
template void FilterSparseMatrixRows (const SparseMatrix< float > &in, const std::vector< bool > &keep_rows, SparseMatrix< float > *out)
 
template void FilterSparseMatrixRows (const SparseMatrix< double > &in, const std::vector< bool > &keep_rows, SparseMatrix< double > *out)
 
void FilterGeneralMatrixRows (const GeneralMatrix &in, const std::vector< bool > &keep_rows, GeneralMatrix *out)
 Outputs a GeneralMatrix containing only the rows r of "in" such that keep_rows[r] == true. More...
 
void ExtractRowRangeWithPadding (const GeneralMatrix &in, int32 row_offset, int32 num_rows, GeneralMatrix *out)
 This function extracts a row-range of a GeneralMatrix and writes as a GeneralMatrix containing the same type of underlying matrix. More...
 
template<class CharT , class Traits >
void swap (basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
 
template<class Int >
void TestSetOfNumbers (bool binary)
 
template<class T >
int32 LevenshteinEditDistance (const std::vector< T > &a, const std::vector< T > &b)
 
template<class T >
int32 LevenshteinEditDistance (const std::vector< T > &ref, const std::vector< T > &hyp, int32 *ins, int32 *del, int32 *sub)
 
template<class T >
int32 LevenshteinAlignment (const std::vector< T > &a, const std::vector< T > &b, T eps_symbol, std::vector< std::pair< T, T > > *output)
 
void TestEditDistance ()
 
void TestEditDistanceString ()
 
void TestEditDistance2 ()
 
void TestEditDistance2String ()
 
void TestLevenshteinAlignment ()
 
template<class Int , class T >
void TestHashList ()
 
static bool prefixp (const std::string &pfx, const std::string &str)
 
static std::string cygprefix ("/cygdrive/")
 
static std::string MapCygwinPathNoTmp (const std::string &filename)
 
std::string MapCygwinPath (const std::string &filename)
 
static FILE * CygwinCompatPopen (const char *command, const char *mode)
 
bool ParseMatrixRangeSpecifier (const std::string &range, const int rows, const int cols, std::vector< int32 > *row_range, std::vector< int32 > *col_range)
 
bool ExtractObjectRange (const GeneralMatrix &input, const std::string &range, GeneralMatrix *output)
 GeneralMatrix is always of type BaseFloat. More...
 
template<class Real >
bool ExtractObjectRange (const CompressedMatrix &input, const std::string &range, Matrix< Real > *output)
 CompressedMatrix is always of the type BaseFloat but it is more efficient to provide template as it uses CompressedMatrix's own conversion to Matrix<Real> More...
 
template bool ExtractObjectRange (const CompressedMatrix &, const std::string &, Matrix< float > *)
 
template bool ExtractObjectRange (const CompressedMatrix &, const std::string &, Matrix< double > *)
 
template<class Real >
bool ExtractObjectRange (const Matrix< Real > &input, const std::string &range, Matrix< Real > *output)
 The template is specialized with a version that actually does something, for types Matrix<float> and Matrix<double>. More...
 
template bool ExtractObjectRange (const Matrix< double > &, const std::string &, Matrix< double > *)
 
template bool ExtractObjectRange (const Matrix< float > &, const std::string &, Matrix< float > *)
 
template<class Real >
bool ExtractObjectRange (const Vector< Real > &input, const std::string &range, Vector< Real > *output)
 The template is specialized types Vector<float> and Vector<double>. More...
 
template bool ExtractObjectRange (const Vector< double > &, const std::string &, Vector< double > *)
 
template bool ExtractObjectRange (const Vector< float > &, const std::string &, Vector< float > *)
 
bool ExtractRangeSpecifier (const std::string &rxfilename_with_range, std::string *data_rxfilename, std::string *range)
 
template<class T >
bool ExtractObjectRange (const T &input, const std::string &range, T *output)
 This templated function exists so that we can write .scp files with 'object ranges' specified: the canonical example is a [first:last] range of rows of a matrix, or [first-row:last-row,first-column,last-column] of a matrix. More...
 
void UnitTestClassifyRxfilename ()
 
void UnitTestClassifyWxfilename ()
 
void UnitTestIoNew (bool binary)
 
void UnitTestIoPipe (bool binary)
 
void UnitTestIoStandard ()
 
void UnitTestNativeFilename ()
 
std::string PrintableRxfilename (const std::string &rxfilename)
 PrintableRxfilename turns the rxfilename into a more human-readable form for error reporting, i.e. More...
 
std::string PrintableWxfilename (const std::string &wxfilename)
 PrintableWxfilename turns the wxfilename into a more human-readable form for error reporting, i.e. More...
 
OutputType ClassifyWxfilename (const std::string &wxfilename)
 ClassifyWxfilename interprets filenames as follows: More...
 
InputType ClassifyRxfilename (const std::string &rxfilename)
 ClassifyRxfilenames interprets filenames for reading as follows: More...
 
template<>
void ReadKaldiObject (const std::string &filename, Matrix< float > *m)
 
template<>
void ReadKaldiObject (const std::string &filename, Matrix< double > *m)
 
template<class C >
void ReadKaldiObject (const std::string &filename, C *c)
 
template<class C >
void WriteKaldiObject (const C &c, const std::string &filename, bool binary)
 
void UnitTestReadScriptFile ()
 
void UnitTestClassifyWspecifier ()
 
void UnitTestClassifyRspecifier ()
 
void UnitTestTableSequentialInt32 (bool binary)
 
void UnitTestTableSequentialBool (bool binary)
 
void UnitTestTableSequentialDouble (bool binary)
 
void UnitTestTableSequentialDoubleBoth (bool binary, bool read_scp)
 
void UnitTestTableSequentialInt32VectorBoth (bool binary, bool read_scp)
 
void UnitTestTableSequentialInt32PairVectorBoth (bool binary, bool read_scp)
 
void UnitTestTableSequentialInt32VectorVectorBoth (bool binary, bool read_scp)
 
void UnitTestTableSequentialInt32Script (bool binary)
 
void UnitTestTableSequentialDoubleMatrixBoth (bool binary, bool read_scp)
 
void UnitTestTableSequentialBaseFloatVectorBoth (bool binary, bool read_scp)
 
template<class T >
void RandomizeVector (std::vector< T > *v)
 
void UnitTestTableRandomBothDouble (bool binary, bool read_scp, bool sorted, bool called_sorted, bool once)
 
void UnitTestRangesMatrix (bool binary)
 
void UnitTestTableRandomBothDoubleMatrix (bool binary, bool read_scp, bool sorted, bool called_sorted, bool once)
 
bool ReadScriptFile (const std::string &rxfilename, bool warn, std::vector< std::pair< std::string, std::string > > *script_out)
 
bool ReadScriptFile (std::istream &is, bool warn, std::vector< std::pair< std::string, std::string > > *script_out)
 
bool WriteScriptFile (std::ostream &os, const std::vector< std::pair< std::string, std::string > > &script)
 
bool WriteScriptFile (const std::string &wxfilename, const std::vector< std::pair< std::string, std::string > > &script)
 
WspecifierType ClassifyWspecifier (const std::string &wspecifier, std::string *archive_wxfilename, std::string *script_wxfilename, WspecifierOptions *opts)
 
RspecifierType ClassifyRspecifier (const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
 
void TestThreads ()
 
void TestTaskSequencer ()
 
template<class C >
void RunMultiThreaded (const C &c_in)
 Here, class C should inherit from MultiThreadable. More...
 
void UnitTestParseOptions ()
 
static bool MustBeQuoted (const std::string &str, ShellType st)
 
static std::string QuoteAndEscape (const std::string &str, ShellType st)
 
template<class C >
void ReadConfigFromFile (const std::string &config_filename, C *c)
 This template is provided for convenience in reading config classes from files; this is not the standard way to read configuration options, but may occasionally be needed. More...
 
template<class C1 , class C2 >
void ReadConfigsFromFile (const std::string &conf, C1 *c1, C2 *c2)
 This variant of the template ReadConfigFromFile is for if you need to read two config classes from the same file. More...
 
bool WriteIntegerVectorSimple (const std::string &wxfilename, const std::vector< int32 > &v)
 WriteToList attempts to write this list of integers, one per line, to the given file, in text format. More...
 
bool ReadIntegerVectorSimple (const std::string &rxfilename, std::vector< int32 > *v)
 ReadFromList attempts to read this list of integers, one per line, from the given file, in text format. More...
 
bool WriteIntegerVectorVectorSimple (const std::string &wxfilename, const std::vector< std::vector< int32 > > &list)
 
bool ReadIntegerVectorVectorSimple (const std::string &rxfilename, std::vector< std::vector< int32 > > *list)
 
void UnitTestSimpleOptions ()
 
template<typename T >
static bool SetOptionImpl (const std::string &key, const T &value, std::map< std::string, T *> &some_map)
 
template<typename T >
static bool GetOptionImpl (const std::string &key, T *value, std::map< std::string, T *> &some_map)
 
static void TestIsSorted ()
 
static void TestIsSortedAndUniq ()
 
static void TestUniq ()
 
static void TestSortAndUniq ()
 
void TestCopySetToVector ()
 
void TestCopyMapToVector ()
 
void TestCopyMapKeysToVector ()
 
void TestCopyMapValuesToVector ()
 
void TestCopyMapKeysToSet ()
 
void TestCopyMapValuesToSet ()
 
void TestContainsNullPointers ()
 
void TestReverseVector ()
 
void TestMergePairVectorSumming ()
 
template<typename T >
void SortAndUniq (std::vector< T > *vec)
 Sorts and uniq's (removes duplicates) from a vector. More...
 
template<typename T >
bool IsSorted (const std::vector< T > &vec)
 Returns true if the vector is sorted. More...
 
template<typename T >
bool IsSortedAndUniq (const std::vector< T > &vec)
 Returns true if the vector is sorted and contains each element only once. More...
 
template<typename T >
void Uniq (std::vector< T > *vec)
 Removes duplicate elements from a sorted list. More...
 
template<class T >
void CopySetToVector (const std::set< T > &s, std::vector< T > *v)
 Copies the elements of a set to a vector. More...
 
template<class T >
void CopySetToVector (const unordered_set< T > &s, std::vector< T > *v)
 
template<class A , class B >
void CopyMapToVector (const std::map< A, B > &m, std::vector< std::pair< A, B > > *v)
 Copies the (key, value) pairs in a map to a vector of pairs. More...
 
template<class A , class B >
void CopyMapKeysToVector (const std::map< A, B > &m, std::vector< A > *v)
 Copies the keys in a map to a vector. More...
 
template<class A , class B >
void CopyMapValuesToVector (const std::map< A, B > &m, std::vector< B > *v)
 Copies the values in a map to a vector. More...
 
template<class A , class B >
void CopyMapKeysToSet (const std::map< A, B > &m, std::set< A > *s)
 Copies the keys in a map to a set. More...
 
template<class A , class B >
void CopyMapValuesToSet (const std::map< A, B > &m, std::set< B > *s)
 Copies the values in a map to a set. More...
 
template<class A >
void CopyVectorToSet (const std::vector< A > &v, std::set< A > *s)
 Copies the contents of a vector to a set. More...
 
template<class A >
void DeletePointers (std::vector< A *> *v)
 Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL. More...
 
template<class A >
bool ContainsNullPointers (const std::vector< A *> &v)
 Returns true if the vector of pointers contains NULL pointers. More...
 
template<typename A , typename B >
void CopyVectorToVector (const std::vector< A > &vec_in, std::vector< B > *vec_out)
 Copies the contents a vector of one type to a vector of another type. More...
 
template<typename T >
void ReverseVector (std::vector< T > *vec)
 Reverses the contents of a vector. More...
 
template<typename I , typename F >
void MergePairVectorSumming (std::vector< std::pair< I, F > > *vec)
 For a vector of pair<I, F> where I is an integer and F a floating-point or integer type, this function sorts a vector of type vector<pair<I, F> > on the I value and then merges elements with equal I values, summing these over the F component and then removing any F component with zero value. More...
 
char GetRandChar ()
 
char GetRandDelim ()
 
void TestSplitStringToVector ()
 
void TestSplitStringToIntegers ()
 
void TestSplitStringToFloats ()
 
void TestConvertStringToInteger ()
 
template<class Real >
void TestConvertStringToReal ()
 
template<class Real >
void TestNan ()
 
template<class Real >
void TestInf ()
 
std::string TrimTmp (std::string s)
 
void TestTrim ()
 
void TestSplitStringOnFirstSpace ()
 
void TestIsToken ()
 
void TestIsLine ()
 
void TestStringsApproxEqual ()
 
void UnitTestConfigLineParse ()
 
void UnitTestReadConfig ()
 
template<class F >
bool SplitStringToFloats (const std::string &full, const char *delim, bool omit_empty_strings, std::vector< F > *out)
 
template bool SplitStringToFloats (const std::string &full, const char *delim, bool omit_empty_strings, std::vector< float > *out)
 
template bool SplitStringToFloats (const std::string &full, const char *delim, bool omit_empty_strings, std::vector< double > *out)
 
void SplitStringToVector (const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
 Split a string using any of the single character delimiters. More...
 
void JoinVectorToString (const std::vector< std::string > &vec_in, const char *delim, bool omit_empty_strings, std::string *str_out)
 Joins the elements of a vector of strings into a single string using "delim" as the delimiter. More...
 
void Trim (std::string *str)
 Removes the beginning and trailing whitespaces from a string. More...
 
bool IsToken (const std::string &token)
 Returns true if "token" is nonempty, and all characters are printable and whitespace-free. More...
 
void SplitStringOnFirstSpace (const std::string &line, std::string *first, std::string *rest)
 Removes leading and trailing white space from the string, then splits on the first section of whitespace found (if present), putting the part before the whitespace in "first" and the rest in "rest". More...
 
bool IsLine (const std::string &line)
 Returns true if "line" is free of
characters and unprintable characters, and does not contain leading or trailing whitespace. More...
 
template<typename T >
bool ConvertStringToReal (const std::string &str, T *out)
 ConvertStringToReal converts a string into either float or double and returns false if there was any kind of problem (i.e. More...
 
template bool ConvertStringToReal (const std::string &str, float *out)
 
template bool ConvertStringToReal (const std::string &str, double *out)
 
bool StringsApproxEqualInternal (const char *a, const char *b, int32 decimal_places_tolerance, int32 places_into_number)
 
bool StringsApproxEqual (const std::string &a, const std::string &b, int32 decimal_places_check=2)
 This function returns true when two text strings are approximately equal, and false when they are not. More...
 
void ExpectOneOrTwoTokens (std::istream &is, bool binary, const std::string &token1, const std::string &token2)
 This function is like ExpectToken but for two tokens, and it will either accept token1 and then token2, or just token2. More...
 
bool IsValidName (const std::string &name)
 Returns true if 'name' would be a valid name for a component or node in a nnet3Nnet. More...
 
void ReadConfigLines (std::istream &is, std::vector< std::string > *lines)
 This function reads in a config file and *appends* its contents to a vector of lines; it is responsible for removing comments (anything after '#') and stripping out any lines that contain only whitespace after comment removal. More...
 
void ParseConfigLines (const std::vector< std::string > &lines, std::vector< ConfigLine > *config_lines)
 This function converts config-lines from a simple sequence of strings as output by ReadConfigLines(), into a sequence of first-tokens and name-value pairs. More...
 
template<class I >
bool SplitStringToIntegers (const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
 Split a string (e.g. More...
 
template<class Int >
bool ConvertStringToInteger (const std::string &str, Int *out)
 Converts a string into an integer via strtoll and returns false if there was any kind of problem (i.e. More...
 
void UnitTestOnlineCmvn ()
 
void ComputePowerSpectrum (VectorBase< BaseFloat > *waveform)
 
void ComputeDeltas (const DeltaFeaturesOptions &delta_opts, const MatrixBase< BaseFloat > &input_features, Matrix< BaseFloat > *output_features)
 
void ComputeShiftedDeltas (const ShiftedDeltaFeaturesOptions &delta_opts, const MatrixBase< BaseFloat > &input_features, Matrix< BaseFloat > *output_features)
 
void InitIdftBases (int32 n_bases, int32 dimension, Matrix< BaseFloat > *mat_out)
 
void SpliceFrames (const MatrixBase< BaseFloat > &input_features, int32 left_context, int32 right_context, Matrix< BaseFloat > *output_features)
 
void ReverseFrames (const MatrixBase< BaseFloat > &input_features, Matrix< BaseFloat > *output_features)
 
void SlidingWindowCmnInternal (const SlidingWindowCmnOptions &opts, const MatrixBase< double > &input, MatrixBase< double > *output)
 
void SlidingWindowCmn (const SlidingWindowCmnOptions &opts, const MatrixBase< BaseFloat > &input, MatrixBase< BaseFloat > *output)
 Applies sliding-window cepstral mean and/or variance normalization. More...
 
int64 FirstSampleOfFrame (int32 frame, const FrameExtractionOptions &opts)
 
int32 NumFrames (int64 num_samples, const FrameExtractionOptions &opts, bool flush=true)
 This function returns the number of frames that we can extract from a wave file with the given number of samples in it (assumed to have the same sampling rate as specified in 'opts'). More...
 
void Dither (VectorBase< BaseFloat > *waveform, BaseFloat dither_value)
 
void Preemphasize (VectorBase< BaseFloat > *waveform, BaseFloat preemph_coeff)
 
void ProcessWindow (const FrameExtractionOptions &opts, const FeatureWindowFunction &window_function, VectorBase< BaseFloat > *window, BaseFloat *log_energy_pre_window=NULL)
 This function does all the windowing steps after actually extracting the windowed signal: depending on the configuration, it does dithering, dc offset removal, preemphasis, and multiplication by the windowing function. More...
 
void ExtractWindow (int64 sample_offset, const VectorBase< BaseFloat > &wave, int32 f, const FrameExtractionOptions &opts, const FeatureWindowFunction &window_function, Vector< BaseFloat > *window, BaseFloat *log_energy_pre_window)
 
void ComputeLifterCoeffs (BaseFloat Q, VectorBase< BaseFloat > *coeffs)
 
BaseFloat Durbin (int n, const BaseFloat *pAC, BaseFloat *pLP, BaseFloat *pTmp)
 
void Lpc2Cepstrum (int n, const BaseFloat *pLPC, BaseFloat *pCepst)
 
void GetEqualLoudnessVector (const MelBanks &mel_banks, Vector< BaseFloat > *ans)
 
BaseFloat ComputeLpc (const VectorBase< BaseFloat > &autocorr_in, Vector< BaseFloat > *lpc_out)
 
void GetOutput (OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
 
bool RandomSplit (int32 wav_dim, std::vector< int32 > *piece_dim, int32 num_pieces, int32 trials=5)
 
void TestOnlineMatrixCacheFeature ()
 
void TestOnlineDeltaFeature ()
 
void TestOnlineSpliceFrames ()
 
void TestOnlineMfcc ()
 
void TestOnlinePlp ()
 
void TestOnlineTransform ()
 
void TestOnlineAppendFeature ()
 
void TestRecyclingVector ()
 
std::string ConvertIntToString (const int &number)
 
bool DirExist (const std::string &dirname)
 
static void UnitTestSimple ()
 
static void UnitTestSnipEdges ()
 
static void UnitTestPieces ()
 
static void UnitTestDelay ()
 
static void UnitTestSearch ()
 
static void UnitTestComputeGPE ()
 
static void UnitTestKeele ()
 
static void UnitTestPenaltyFactor ()
 
static void UnitTestKeeleNccfBallast ()
 
static void UnitTestPitchExtractionSpeed ()
 
static void UnitTestPitchExtractorCompareKeele ()
 
void UnitTestDiffSampleRate ()
 
void UnitTestProcess ()
 
static void UnitTestFeatNoKeele ()
 
static void UnitTestFeatWithKeele ()
 
BaseFloat NccfToPovFeature (BaseFloat n)
 This function processes the NCCF n to a POV feature f by applying the formula f = (1.0001 - n)^0.15 - 1.0 This is a nonlinear function designed to make the output reasonably Gaussian distributed. More...
 
BaseFloat NccfToPov (BaseFloat n)
 This function processes the NCCF n to a reasonably accurate probability of voicing p by applying the formula: More...
 
void ComputeCorrelation (const VectorBase< BaseFloat > &wave, int32 first_lag, int32 last_lag, int32 nccf_window_size, VectorBase< BaseFloat > *inner_prod, VectorBase< BaseFloat > *norm_prod)
 This function computes some dot products that are required while computing the NCCF. More...
 
void ComputeNccf (const VectorBase< BaseFloat > &inner_prod, const VectorBase< BaseFloat > &norm_prod, BaseFloat nccf_ballast, VectorBase< BaseFloat > *nccf_vec)
 Computes the NCCF as a fraction of the numerator term (a dot product between two vectors) and a denominator term which equals sqrt(e1*e2 + nccf_ballast) where e1 and e2 are both dot-products of bits of the wave with themselves, and e1*e2 is supplied as "norm_prod". More...
 
void SelectLags (const PitchExtractionOptions &opts, Vector< BaseFloat > *lags)
 This function selects the lags at which we measure the NCCF: we need to select lags from 1/max_f0 to 1/min_f0, in a geometric progression with ratio 1 + d. More...
 
void ComputeLocalCost (const VectorBase< BaseFloat > &nccf_pitch, const VectorBase< BaseFloat > &lags, const PitchExtractionOptions &opts, VectorBase< BaseFloat > *local_cost)
 This function computes the local-cost for the Viterbi computation, see eq. More...
 
void ComputeKaldiPitchFirstPass (const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
 This function is called from ComputeKaldiPitch when the user specifies opts.simulate_first_pass_online == true. More...
 
void ComputeKaldiPitch (const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
 This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pitch Extraction Algorithm Tuned for Automatic Speech Recognition", Pegah Ghahremani, Bagher BabaAli, Daniel Povey, Korbinian Riedhammer, Jan Trmal and Sanjeev Khudanpur, ICASSP 2014. More...
 
template<typename Real >
void AppendVector (const VectorBase< Real > &src, Vector< Real > *dst)
 
void ProcessPitch (const ProcessPitchOptions &opts, const MatrixBase< BaseFloat > &input, Matrix< BaseFloat > *output)
 This function processes the raw (NCCF, pitch) quantities computed by ComputeKaldiPitch, and processes them into features. More...
 
void ComputeAndProcessKaldiPitch (const PitchExtractionOptions &pitch_opts, const ProcessPitchOptions &process_opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
 This function combines ComputeKaldiPitch and ProcessPitch. More...
 
void ResampleWaveform (BaseFloat orig_freq, const VectorBase< BaseFloat > &wave, BaseFloat new_freq, Vector< BaseFloat > *new_wave)
 Downsample or upsample a waveform. More...
 
void DownsampleWaveForm (BaseFloat orig_freq, const VectorBase< BaseFloat > &wave, BaseFloat new_freq, Vector< BaseFloat > *new_wave)
 This function is deprecated. More...
 
void UnitTestFFTbasedBlockConvolution ()
 
void UnitTestFFTbasedConvolution ()
 
void ElementwiseProductOfFft (const Vector< BaseFloat > &a, Vector< BaseFloat > *b)
 
void ConvolveSignals (const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
 
void FFTbasedConvolveSignals (const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
 
void FFTbasedBlockConvolveSignals (const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
 
static void WriteUint32 (std::ostream &os, int32 i)
 
static void WriteUint16 (std::ostream &os, int16 i)
 
void TestGenRandStats ()
 
void TestBuildTree ()
 
void TestTrivialTree ()
 
void TestPossibleValues ()
 
void TestConvertStats ()
 
void TestSplitStatsByKey ()
 
void TestFindAllKeys ()
 
void TestDoTableSplit ()
 
void TestClusterEventMapGetMappingAndRenumberEventMap ()
 
void TestClusterEventMapGetMappingAndRenumberEventMap2 ()
 
void TestClusterEventMap ()
 
void TestClusterEventMapRestricted ()
 
void TestShareEventMapLeaves ()
 
void TestQuestionsInitRand ()
 
void TestSplitDecisionTree ()
 
void TestBuildTreeStatsIo (bool binary)
 
void WriteBuildTreeStats (std::ostream &os, bool binary, const BuildTreeStatsType &stats)
 Writes BuildTreeStats object. This works even if pointers are NULL. More...
 
void ReadBuildTreeStats (std::istream &is, bool binary, const Clusterable &example, BuildTreeStatsType *stats)
 Reads BuildTreeStats object. More...
 
bool PossibleValues (EventKeyType key, const BuildTreeStatsType &stats, std::vector< EventValueType > *ans)
 Convenience function e.g. More...
 
static void GetEventKeys (const EventType &vec, std::vector< EventKeyType > *keys)
 
void FindAllKeys (const BuildTreeStatsType &stats, AllKeysType keys_type, std::vector< EventKeyType > *keys)
 FindAllKeys puts in *keys the (sorted, unique) list of all key identities in the stats. More...
 
EventMapDoTableSplit (const EventMap &orig, EventKeyType key, const BuildTreeStatsType &stats, int32 *num_leaves)
 DoTableSplit does a complete split on this key (e.g. More...
 
EventMapDoTableSplitMultiple (const EventMap &orig, const std::vector< EventKeyType > &keys, const BuildTreeStatsType &stats, int32 *num_leaves)
 DoTableSplitMultiple does a complete split on all the keys, in order from keys[0], keys[1] and so on. More...
 
void SplitStatsByMap (const BuildTreeStatsType &stats_in, const EventMap &e, std::vector< BuildTreeStatsType > *stats_out)
 Splits stats according to the EventMap, indexing them at output by the leaf type. More...
 
void SplitStatsByKey (const BuildTreeStatsType &stats_in, EventKeyType key, std::vector< BuildTreeStatsType > *stats_out)
 SplitStatsByKey splits stats up according to the value of a particular key, which must be always defined and nonnegative. More...
 
void FilterStatsByKey (const BuildTreeStatsType &stats_in, EventKeyType key, std::vector< EventValueType > &values, bool include_if_present, BuildTreeStatsType *stats_out)
 FilterStatsByKey filters the stats according the value of a specified key. More...
 
ClusterableSumStats (const BuildTreeStatsType &stats_in)
 Sums stats, or returns NULL stats_in has no non-NULL stats. More...
 
BaseFloat SumNormalizer (const BuildTreeStatsType &stats_in)
 Sums the normalizer [typically, data-count] over the stats. More...
 
BaseFloat SumObjf (const BuildTreeStatsType &stats_in)
 Sums the objective function over the stats. More...
 
void SumStatsVec (const std::vector< BuildTreeStatsType > &stats_in, std::vector< Clusterable * > *stats_out)
 Sum a vector of stats. More...
 
BaseFloat ObjfGivenMap (const BuildTreeStatsType &stats_in, const EventMap &e)
 Cluster the stats given the event map return the total objf given those clusters. More...
 
BaseFloat ComputeInitialSplit (const std::vector< Clusterable *> &summed_stats, const Questions &q_opts, EventKeyType key, std::vector< EventValueType > *yes_set)
 
BaseFloat FindBestSplitForKey (const BuildTreeStatsType &stats, const Questions &qcfg, EventKeyType key, std::vector< EventValueType > *yes_set)
 FindBestSplitForKey is a function used in DoDecisionTreeSplit. More...
 
EventMapSplitDecisionTree (const EventMap &orig, const BuildTreeStatsType &stats, Questions &qcfg, BaseFloat thresh, int32 max_leaves, int32 *num_leaves, BaseFloat *objf_impr_out, BaseFloat *smallest_split_change_out)
 Does a decision-tree split at the leaves of an EventMap. More...
 
int ClusterEventMapGetMapping (const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, std::vector< EventMap * > *mapping)
 "ClusterEventMapGetMapping" clusters the leaves of the EventMap, with "thresh" a delta-likelihood threshold to control how many leaves we combine (might be the same as the delta-like threshold used in splitting. More...
 
EventMapRenumberEventMap (const EventMap &e_in, int32 *num_leaves)
 RenumberEventMap [intended to be used after calling ClusterEventMap] renumbers an EventMap so its leaves are consecutive. More...
 
EventMapMapEventMapLeaves (const EventMap &e_in, const std::vector< int32 > &mapping)
 This function remaps the event-map leaves using this mapping, indexed by the number at leaf. More...
 
EventMapClusterEventMap (const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, int32 *num_removed)
 This is as ClusterEventMapGetMapping but a more convenient interface that exposes less of the internals. More...
 
EventMapShareEventMapLeaves (const EventMap &e_in, EventKeyType key, std::vector< std::vector< EventValueType > > &values, int32 *num_leaves)
 ShareEventMapLeaves performs a quite specific function that allows us to generate trees where, for a certain list of phones, and for all states in the phone, all the pdf's are shared. More...
 
void DeleteBuildTreeStats (BuildTreeStatsType *stats)
 This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL. More...
 
EventMapGetToLengthMap (const BuildTreeStatsType &stats, int32 P, const std::vector< EventValueType > *phones, int32 default_length)
 
static int32 ClusterEventMapRestrictedHelper (const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, std::vector< EventKeyType > keys, std::vector< EventMap *> *leaf_mapping)
 
EventMapClusterEventMapRestrictedByKeys (const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, const std::vector< EventKeyType > &keys, int32 *num_removed)
 This is as ClusterEventMap, but first splits the stats on the keys specified in "keys" (e.g. More...
 
EventMapClusterEventMapRestrictedByMap (const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, const EventMap &e_restrict, int32 *num_removed)
 This version of ClusterEventMapRestricted restricts the clustering to only allow things that "e_restrict" maps to the same value to be clustered together. More...
 
EventMapClusterEventMapToNClustersRestrictedByMap (const EventMap &e_in, const BuildTreeStatsType &stats, int32 num_clusters, const EventMap &e_restrict, int32 *num_removed)
 This version of ClusterEventMapRestrictedByMap clusters to get a specific number of clusters as specified by 'num_clusters'. More...
 
EventMapGetStubMap (int32 P, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, int32 *num_leaves)
 GetStubMap is used in tree-building functions to get the initial to-states map, before the decision-tree-building process. More...
 
bool ConvertStats (int32 oldN, int32 oldP, int32 newN, int32 newP, BuildTreeStatsType *stats)
 Converts stats from a given context-window (N) and central-position (P) to a different N and P, by possibly reducing context. More...
 
EventMapTrivialTree (int32 *num_leaves)
 Returns a tree with just one node. More...
 
void CreateRandomQuestions (const BuildTreeStatsType &stats, int32 num_quest, Questions *cfg_out)
 CreateRandomQuestions will initialize a Questions randomly, in a reasonable way [for testing purposes, or when hand-designed questions are not available]. More...
 
void GenRandStats (int32 dim, int32 num_stats, int32 N, int32 P, const std::vector< int32 > &phone_ids, const std::vector< int32 > &hmm_lengths, const std::vector< bool > &is_ctx_dep, bool ensure_all_phones_covered, BuildTreeStatsType *stats_out)
 GenRandStats generates random statistics of the form used by BuildTree. More...
 
EventMapBuildTree (Questions &qopts, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, const std::vector< bool > &do_split, const BuildTreeStatsType &stats, BaseFloat thresh, int32 max_leaves, BaseFloat cluster_thresh, int32 P, bool round_num_leaves=true)
 BuildTree is the normal way to build a set of decision trees. More...
 
static void ComputeTreeMapping (const EventMap &small_tree, const EventMap &big_tree, const BuildTreeStatsType &stats, std::vector< int32 > *leaf_map)
 
EventMapBuildTreeTwoLevel (Questions &qopts, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, const std::vector< bool > &do_split, const BuildTreeStatsType &stats, int32 max_leaves_first, int32 max_leaves_second, bool cluster_leaves, int32 P, std::vector< int32 > *leaf_map)
 BuildTreeTwoLevel builds a two-level tree, useful for example in building tied mixture systems with multiple codebooks. More...
 
void ReadSymbolTableAsIntegers (std::string filename, bool include_eps, std::vector< int32 > *syms)
 included here because it's used in some tree-building calling code. More...
 
static void RemoveDuplicates (std::vector< std::vector< int32 > > *vecs)
 
static void ObtainSetsOfPhones (const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &assignments, const std::vector< int32 > &clust_assignments, int32 num_leaves, std::vector< std::vector< int32 > > *sets_out)
 ObtainSetsOfPhones is called by AutomaticallyObtainQuestions. More...
 
void AutomaticallyObtainQuestions (BuildTreeStatsType &stats, const std::vector< std::vector< int32 > > &phone_sets_in, const std::vector< int32 > &all_pdf_classes_in, int32 P, std::vector< std::vector< int32 > > *questions_out)
 Outputs sets of phones that are reasonable for questions to ask in the tree-building algorithm. More...
 
void KMeansClusterPhones (BuildTreeStatsType &stats, const std::vector< std::vector< int32 > > &phone_sets_in, const std::vector< int32 > &all_pdf_classes_in, int32 P, int32 num_classes, std::vector< std::vector< int32 > > *sets_out)
 This function clusters the phones (or some initially specified sets of phones) into sets of phones, using a k-means algorithm. More...
 
void ReadRootsFile (std::istream &is, std::vector< std::vector< int32 > > *phone_sets, std::vector< bool > *is_shared_root, std::vector< bool > *is_split_root)
 Reads the roots file (throws on error). More...
 
static void TestClusterUtils ()
 
static void TestClusterUtilsVector ()
 
static void TestObjfPlus ()
 
static void TestObjfMinus ()
 
static void TestDistance ()
 
static void TestSumObjfAndSumNormalizer ()
 
static void TestSum ()
 
static void TestEnsureClusterableVectorNotNull ()
 
static void TestAddToClusters ()
 
static void TestAddToClustersOptimized ()
 
static void TestClusterBottomUp ()
 
static void TestRefineClusters ()
 
static void TestClusterKMeans ()
 
static void TestClusterKMeansVector ()
 
static void TestTreeCluster ()
 
static void TestClusterTopDown ()
 
BaseFloat SumClusterableObjf (const std::vector< Clusterable * > &vec)
 Returns the total objective function after adding up all the statistics in the vector (pointers may be NULL). More...
 
BaseFloat SumClusterableNormalizer (const std::vector< Clusterable * > &vec)
 Returns the total normalizer (usually count) of the cluster (pointers may be NULL). More...
 
ClusterableSumClusterable (const std::vector< Clusterable * > &vec)
 Sums stats (ptrs may be NULL). Returns NULL if no non-NULL stats present. More...
 
void EnsureClusterableVectorNotNull (std::vector< Clusterable * > *stats)
 Fills in any (NULL) holes in "stats" vector, with empty stats, because certain algorithms require non-NULL stats. More...
 
void AddToClusters (const std::vector< Clusterable * > &stats, const std::vector< int32 > &assignments, std::vector< Clusterable * > *clusters)
 Given stats and a vector "assignments" of the same size (that maps to cluster indices), sums the stats up into "clusters." It will add to any stats already present in "clusters" (although typically "clusters" will be empty when called), and it will extend with NULL pointers for any unseen indices. More...
 
void AddToClustersOptimized (const std::vector< Clusterable * > &stats, const std::vector< int32 > &assignments, const Clusterable &total, std::vector< Clusterable * > *clusters)
 AddToClustersOptimized does the same as AddToClusters (it sums up the stats within each cluster, except it uses the sum of all the stats ("total") to optimize the computation for speed, if possible. More...
 
BaseFloat ClusterBottomUp (const std::vector< Clusterable * > &points, BaseFloat thresh, int32 min_clust, std::vector< Clusterable * > *clusters_out, std::vector< int32 > *assignments_out)
 A bottom-up clustering algorithm. More...
 
bool operator> (const CompBotClustElem &a, const CompBotClustElem &b)
 
BaseFloat ClusterBottomUpCompartmentalized (const std::vector< std::vector< Clusterable * > > &points, BaseFloat thresh, int32 min_clust, std::vector< std::vector< Clusterable * > > *clusters_out, std::vector< std::vector< int32 > > *assignments_out)
 This is a bottom-up clustering where the points are pre-clustered in a set of compartments, such that only points in the same compartment are clustered together. More...
 
BaseFloat RefineClusters (const std::vector< Clusterable * > &points, std::vector< Clusterable * > *clusters, std::vector< int32 > *assignments, RefineClustersOptions cfg=RefineClustersOptions())
 RefineClusters is mainly used internally by other clustering algorithms. More...
 
BaseFloat ClusterKMeansOnce (const std::vector< Clusterable *> &points, int32 num_clust, std::vector< Clusterable *> *clusters_out, std::vector< int32 > *assignments_out, ClusterKMeansOptions &cfg)
 ClusterKMeansOnce is called internally by ClusterKMeans; it is equivalent to calling ClusterKMeans with cfg.num_tries == 1. More...
 
BaseFloat ClusterKMeans (const std::vector< Clusterable * > &points, int32 num_clust, std::vector< Clusterable * > *clusters_out, std::vector< int32 > *assignments_out, ClusterKMeansOptions cfg=ClusterKMeansOptions())
 ClusterKMeans is a K-means-like clustering algorithm. More...
 
BaseFloat TreeCluster (const std::vector< Clusterable * > &points, int32 max_clust, std::vector< Clusterable * > *clusters_out, std::vector< int32 > *assignments_out, std::vector< int32 > *clust_assignments_out, int32 *num_leaves_out, TreeClusterOptions cfg=TreeClusterOptions())
 TreeCluster is a top-down clustering algorithm, using a binary tree (not necessarily balanced). More...
 
BaseFloat ClusterTopDown (const std::vector< Clusterable * > &points, int32 max_clust, std::vector< Clusterable * > *clusters_out, std::vector< int32 > *assignments_out, TreeClusterOptions cfg=TreeClusterOptions())
 A clustering algorithm that internally uses TreeCluster, but does not give you the information about the structure of the tree. More...
 
void TestContextDep ()
 
void TestMonophoneContextDependency ()
 
void TestGenRandContextDependency ()
 
ContextDependencyGenRandContextDependency (const std::vector< int32 > &phones, bool ensure_all_covered, std::vector< int32 > *num_pdf_classes)
 GenRandContextDependency is mainly of use for debugging. More...
 
ContextDependencyGenRandContextDependencyLarge (const std::vector< int32 > &phones, int N, int P, bool ensure_all_covered, std::vector< int32 > *num_pdf_classes)
 GenRandContextDependencyLarge is like GenRandContextDependency but generates a larger tree with specified N and P for use in "one-time" larger-scale tests. More...
 
ContextDependencyMonophoneContextDependency (const std::vector< int32 > &phones, const std::vector< int32 > &phone2num_pdf_classes)
 
ContextDependencyMonophoneContextDependencyShared (const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes)
 
void TestEventMap ()
 
void TestEventTypeIo (bool binary)
 
EventMapRandomEventMap (const std::vector< EventKeyType > &keys)
 
void TestEventMapIo (bool binary)
 
void TestEventMapPrune ()
 
void TestEventMapMapValues ()
 
void WriteEventType (std::ostream &os, bool binary, const EventType &evec)
 
void ReadEventType (std::istream &is, bool binary, EventType *evec)
 
std::string EventTypeToString (const EventType &evec)
 
static bool IsLeafNode (const EventMap *e)
 
static bool GetTreeStructureInternal (const EventMap &map, std::vector< const EventMap *> *nonleaf_nodes, std::map< const EventMap *, const EventMap *> *nonleaf_parents, std::vector< const EventMap *> *leaf_parents)
 
bool GetTreeStructure (const EventMap &map, int32 *num_leaves, std::vector< int32 > *parents)
 This function gets the tree structure of the EventMap "map" in a convenient form. More...
 
std::pair< EventKeyType, EventValueTypeMakeEventPair (EventKeyType k, EventValueType v)
 
void ClusterGaussiansToUbm (const AmDiagGmm &am, const Vector< BaseFloat > &state_occs, UbmClusteringOptions opts, DiagGmm *ubm_out)
 Clusters the Gaussians in an acoustic model to a single GMM with specified number of components. More...
 
void InitRandomGmm (DiagGmm *gmm_in)
 
void UnitTestDiagGmmGenerate ()
 
void UnitTestDiagGmm ()
 
std::ostream & operator<< (std::ostream &os, const kaldi::DiagGmm &gmm)
 ostream operator that calls DiagGMM::Write() More...
 
std::istream & operator>> (std::istream &is, kaldi::DiagGmm &gmm)
 istream operator that calls DiagGMM::Read() More...
 
void UnitTestEstimateMmieDiagGmm ()
 
static bool EBWUpdateGaussian (BaseFloat D, GmmFlagsType flags, const VectorBase< double > &orig_mean, const VectorBase< double > &orig_var, const VectorBase< double > &x_stats, const VectorBase< double > &x2_stats, double occ, VectorBase< double > *mean, VectorBase< double > *var, double *auxf_impr)
 
void UpdateEbwDiagGmm (const AccumDiagGmm &num_stats, const AccumDiagGmm &den_stats, GmmFlagsType flags, const EbwOptions &opts, DiagGmm *gmm, BaseFloat *auxf_change_out, BaseFloat *count_out, int32 *num_floored_out)
 
void UpdateEbwWeightsDiagGmm (const AccumDiagGmm &num_stats, const AccumDiagGmm &den_stats, const EbwWeightOptions &opts, DiagGmm *gmm, BaseFloat *auxf_change_out, BaseFloat *count_out)
 
void UpdateEbwAmDiagGmm (const AccumAmDiagGmm &num_stats, const AccumAmDiagGmm &den_stats, GmmFlagsType flags, const EbwOptions &opts, AmDiagGmm *am_gmm, BaseFloat *auxf_change_out, BaseFloat *count_out, int32 *num_floored_out)
 
void UpdateEbwWeightsAmDiagGmm (const AccumAmDiagGmm &num_stats, const AccumAmDiagGmm &den_stats, const EbwWeightOptions &opts, AmDiagGmm *am_gmm, BaseFloat *auxf_change_out, BaseFloat *count_out)
 
void IsmoothStatsDiagGmm (const AccumDiagGmm &src_stats, double tau, AccumDiagGmm *dst_stats)
 I-Smooth the stats. src_stats and dst_stats do not have to be different. More...
 
void DiagGmmToStats (const DiagGmm &gmm, GmmFlagsType flags, double state_occ, AccumDiagGmm *dst_stats)
 Creates stats from the GMM. Resizes them as needed. More...
 
void IsmoothStatsAmDiagGmm (const AccumAmDiagGmm &src_stats, double tau, AccumAmDiagGmm *dst_stats)
 Smooth "dst_stats" with "src_stats". More...
 
void IsmoothStatsAmDiagGmmFromModel (const AmDiagGmm &src_model, double tau, AccumAmDiagGmm *dst_stats)
 This version of the I-smoothing function takes a model as input. More...
 
std::ostream & operator<< (std::ostream &rOut, const kaldi::FullGmm &gmm)
 ostream operator that calls FullGmm::Write() More...
 
std::istream & operator>> (std::istream &rIn, kaldi::FullGmm &gmm)
 istream operator that calls FullGmm::Read() More...
 
void GetSingleStatsDerivative (double ml_count, double ml_x_stats, double ml_x2_stats, double disc_count, double disc_x_stats, double disc_x2_stats, double model_mean, double model_var, BaseFloat min_variance, double *ml_x_stats_deriv, double *ml_x2_stats_deriv)
 
void GetStatsDerivative (const DiagGmm &gmm, const AccumDiagGmm &num_acc, const AccumDiagGmm &den_acc, const AccumDiagGmm &ml_acc, BaseFloat min_variance, BaseFloat min_gaussian_occupancy, AccumDiagGmm *out_accs)
 
void GetStatsDerivative (const AmDiagGmm &gmm, const AccumAmDiagGmm &num_accs, const AccumAmDiagGmm &den_accs, const AccumAmDiagGmm &ml_accs, BaseFloat min_variance, BaseFloat min_gaussian_occupancy, AccumAmDiagGmm *out_accs)
 
void DoRescalingUpdate (const AccumDiagGmm &old_ml_acc, const AccumDiagGmm &new_ml_acc, BaseFloat min_variance, BaseFloat min_gaussian_occupancy, DiagGmm *gmm, double *tot_count, double *tot_divergence)
 
void DoRescalingUpdate (const AccumAmDiagGmm &old_ml_accs, const AccumAmDiagGmm &new_ml_accs, BaseFloat min_variance, BaseFloat min_gaussian_occupancy, AmDiagGmm *am_gmm)
 
void ResizeModel (int32 dim, AmDiagGmm *am_gmm)
 
void MleAmDiagGmmUpdate (const MleDiagGmmOptions &config, const AccumAmDiagGmm &amdiaggmm_acc, GmmFlagsType flags, AmDiagGmm *am_gmm, BaseFloat *obj_change_out, BaseFloat *count_out)
 for computing the maximum-likelihood estimates of the parameters of an acoustic model that uses diagonal Gaussian mixture models as emission densities. More...
 
void MapAmDiagGmmUpdate (const MapDiagGmmOptions &config, const AccumAmDiagGmm &diag_gmm_acc, GmmFlagsType flags, AmDiagGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out)
 Maximum A Posteriori update. More...
 
BaseFloat MlObjective (const DiagGmm &gmm, const AccumDiagGmm &diaggmm_acc)
 Calc using the DiagGMM exponential form. More...
 
void MleDiagGmmUpdate (const MleDiagGmmOptions &config, const AccumDiagGmm &diag_gmm_acc, GmmFlagsType flags, DiagGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out, int32 *floored_elements_out=NULL, int32 *floored_gauss_out=NULL, int32 *removed_gauss_out=NULL)
 for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model. More...
 
void MapDiagGmmUpdate (const MapDiagGmmOptions &config, const AccumDiagGmm &diag_gmm_acc, GmmFlagsType flags, DiagGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out)
 Maximum A Posteriori estimation of the model. More...
 
GmmFlagsType AugmentGmmFlags (GmmFlagsType f)
 Returns "augmented" version of flags: e.g. More...
 
BaseFloat MlObjective (const FullGmm &gmm, const AccumFullGmm &fullgmm_acc)
 Calc using the DiagGMM exponential form. More...
 
void MleFullGmmUpdate (const MleFullGmmOptions &config, const AccumFullGmm &fullgmm_acc, GmmFlagsType flags, FullGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out)
 for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model. More...
 
GmmFlagsType StringToGmmFlags (std::string str)
 Convert string which is some subset of "mSwa" to flags. More...
 
std::string GmmFlagsToString (GmmFlagsType gmm_flags)
 Convert GMM flags to string. More...
 
SgmmUpdateFlagsType StringToSgmmUpdateFlags (std::string str)
 
SgmmUpdateFlagsType StringToSgmmWriteFlags (std::string str)
 
void GetSplitTargets (const Vector< BaseFloat > &state_occs, int32 target_components, BaseFloat power, BaseFloat min_count, std::vector< int32 > *targets)
 Get Gaussian-mixture or substate-mixture splitting targets, according to a power rule (e.g. More...
 
static BaseFloat CalBasisFmllrStepSize (const AffineXformStats &spk_stats, const Matrix< BaseFloat > &spk_stats_tmp_K, const std::vector< SpMatrix< BaseFloat > > &spk_stats_tmp_G, const Matrix< BaseFloat > &delta, const Matrix< BaseFloat > &A, const Matrix< BaseFloat > &S, int32 max_iters)
 This function takes the step direction (delta) of fMLLR matrix as argument, and optimize step size using Newton's method. More...
 
void InitCmvnStats (int32 dim, Matrix< double > *stats)
 This function initializes the matrix to dimension 2 by (dim+1); 1st "dim" elements of 1st row are mean stats, 1st "dim" elements of 2nd row are var stats, last element of 1st row is count, last element of 2nd row is zero. More...
 
void AccCmvnStats (const VectorBase< BaseFloat > &feat, BaseFloat weight, MatrixBase< double > *stats)
 Accumulation from a single frame (weighted). More...
 
void AccCmvnStats (const MatrixBase< BaseFloat > &feats, const VectorBase< BaseFloat > *weights, MatrixBase< double > *stats)
 Accumulation from a feature file (possibly weighted– useful in excluding silence). More...
 
void ApplyCmvn (const MatrixBase< double > &stats, bool norm_vars, MatrixBase< BaseFloat > *feats)
 Apply cepstral mean and variance normalization to a matrix of features. More...
 
void ApplyCmvnReverse (const MatrixBase< double > &stats, bool norm_vars, MatrixBase< BaseFloat > *feats)
 This is as ApplyCmvn, but does so in the reverse sense, i.e. More...
 
void FakeStatsForSomeDims (const std::vector< int32 > &dims, MatrixBase< double > *stats)
 Modify the stats so that for some dimensions (specified in "dims"), we replace them with "fake" stats that have zero mean and unit variance; this is done to disable CMVN for those dimensions. More...
 
static void ComputeGconsts (const VectorBase< BaseFloat > &weights, const MatrixBase< BaseFloat > &means, const MatrixBase< BaseFloat > &inv_vars, VectorBase< BaseFloat > *gconsts_out)
 
void UnitTestFmllrDiagGmm ()
 
void UnitTestFmllrDiagGmmDiagonal ()
 
void UnitTestFmllrDiagGmmOffset ()
 
BaseFloat ComputeFmllrMatrixDiagGmm (const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, std::string fmllr_type, int32 num_iters, MatrixBase< BaseFloat > *out_xform)
 This function internally calls ComputeFmllrMatrixDiagGmm{Full, Diagonal, Offset}, depending on "fmllr_type". More...
 
void FmllrInnerUpdate (SpMatrix< double > &inv_G, VectorBase< double > &k, double beta, int32 row, MatrixBase< double > *transform)
 This function does one row of the inner-loop fMLLR transform update. More...
 
BaseFloat ComputeFmllrMatrixDiagGmmFull (const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, int32 num_iters, MatrixBase< BaseFloat > *out_xform)
 Updates the FMLLR matrix using Mark Gales' row-by-row update. More...
 
BaseFloat ComputeFmllrMatrixDiagGmmDiagonal (const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, MatrixBase< BaseFloat > *out_xform)
 This does diagonal fMLLR (i.e. More...
 
BaseFloat ComputeFmllrMatrixDiagGmmOffset (const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, MatrixBase< BaseFloat > *out_xform)
 This does offset-only fMLLR, i.e. it only estimates an offset. More...
 
void ApplyFeatureTransformToStats (const MatrixBase< BaseFloat > &xform, AffineXformStats *stats)
 This function applies a feature-level transform to stats (useful for certain techniques based on fMLLR). More...
 
void ApplyModelTransformToStats (const MatrixBase< BaseFloat > &xform, AffineXformStats *stats)
 ApplyModelTransformToStats takes a transform "xform", which must be diagonal (i.e. More...
 
float FmllrAuxFuncDiagGmm (const MatrixBase< float > &xform, const AffineXformStats &stats)
 Returns the (diagonal-GMM) FMLLR auxiliary function value given the transform and the stats. More...
 
double FmllrAuxFuncDiagGmm (const MatrixBase< double > &xform, const AffineXformStats &stats)
 
BaseFloat FmllrAuxfGradient (const MatrixBase< BaseFloat > &xform, const AffineXformStats &stats, MatrixBase< BaseFloat > *grad_out)
 Returns the (diagonal-GMM) FMLLR auxiliary function value given the transform and the stats. More...
 
void InitFmllr (int32 dim, Matrix< BaseFloat > *out_fmllr)
 
BaseFloat ComputeFmllrDiagGmm (const FmllrDiagGmmAccs &accs, const FmllrOptions &opts, Matrix< BaseFloat > *out_fmllr, BaseFloat *logdet)
 
BaseFloat ComputeFmllrLogDet (const Matrix< BaseFloat > &fmllr_mat)
 
BaseFloat ComputeFmllrMatrixDiagGmmDiagonal2 (const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, MatrixBase< BaseFloat > *out_xform)
 
void UnitTestFmllrRaw (bool use_offset)
 
void GetFeatDeriv (const DiagGmm &gmm, const Matrix< BaseFloat > &feats, Matrix< BaseFloat > *deriv)
 
BaseFloat GetGmmLike (const DiagGmm &gmm, const Matrix< BaseFloat > &feats)
 
void TestFmpe ()
 
BaseFloat ComputeAmGmmFeatureDeriv (const AmDiagGmm &am_gmm, const TransitionModel &trans_model, const Posterior &posterior, const MatrixBase< BaseFloat > &features, Matrix< BaseFloat > *direct_deriv, const AccumAmDiagGmm *model_diff=NULL, Matrix< BaseFloat > *indirect_deriv=NULL)
 Computes derivatives of the likelihood of these states (weighted), w.r.t. More...
 
static bool GetActiveParents (int32 node, const vector< int32 > &parents, const vector< bool > &is_active, vector< int32 > *active_parents_out)
 
static void RandFullCova (Matrix< BaseFloat > *matrix)
 
static void generate_features (cova_type covariance_type, size_t n_gaussians, size_t dim, Matrix< BaseFloat > &trans_mat, size_t frames_per_gaussian, std::vector< Vector< BaseFloat > *> &train_feats, std::vector< Vector< BaseFloat > *> &adapt_feats)
 
void UnitTestRegtreeFmllrDiagGmm (cova_type feature_type, size_t max_bclass)
 
static void ComputeMllrMatrix (const Matrix< double > &K, const vector< SpMatrix< double > > &G, Matrix< BaseFloat > *out)
 
static BaseFloat MllrAuxFunction (const Matrix< BaseFloat > &xform, const AffineXformStats &stats)
 
bool ComposeTransforms (const Matrix< BaseFloat > &a, const Matrix< BaseFloat > &b, bool b_is_affine, Matrix< BaseFloat > *c)
 
void ApplyAffineTransform (const MatrixBase< BaseFloat > &xform, VectorBase< BaseFloat > *vec)
 Applies the affine transform 'xform' to the vector 'vec' and overwrites the contents of 'vec'. More...
 
TransitionModelGenRandTransitionModel (ContextDependency **ctx_dep_out)
 
HmmTopology GetDefaultTopology (const std::vector< int32 > &phones)
 This function returns a HmmTopology object giving a normal 3-state topology, covering all phones in the list "phones". More...
 
HmmTopology GenRandTopology (const std::vector< int32 > &phones, const std::vector< int32 > &num_pdf_classes)
 This method of generating an arbitrary HmmTopology object allows you to specify the number of pdf-classes for each phone separately. More...
 
HmmTopology GenRandTopology ()
 This version of GenRandTopology() generates the phone list and number of pdf classes randomly. More...
 
void GeneratePathThroughHmm (const HmmTopology &topology, bool reorder, int32 phone, std::vector< std::pair< int32, int32 > > *path)
 This function generates a random path through the HMM for the given phone. More...
 
void GenerateRandomAlignment (const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, bool reorder, const std::vector< int32 > &phone_sequence, std::vector< int32 > *alignment)
 For use in test code, this function generates an alignment (a sequence of transition-ids) corresponding to a given phone sequence. More...
 
void TestHmmTopology ()
 
void TestConvertPhnxToProns ()
 
void TestAccumulateTreeStatsOptions ()
 
void TestSplitToPhones ()
 
void TestConvertAlignment ()
 
fst::VectorFst< fst::StdArc > * GetHmmAsFsa (std::vector< int32 > context_window, const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, const HTransducerConfig &config, HmmCacheType *cache=NULL)
 Called by GetHTransducer() and probably will not need to be called directly; it creates and returns the FST corresponding to the phone. More...
 
fst::VectorFst< fst::StdArc > * GetHmmAsFsaSimple (std::vector< int32 > context_window, const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, BaseFloat prob_scale)
 Included mainly as a form of documentation, not used in any other code currently. More...
 
static fst::VectorFst< fst::StdArc > * MakeTrivialAcceptor (int32 label)
 This utility function, used in GetHTransducer(), creates an FSA (finite state acceptor, i.e. More...
 
fst::VectorFst< fst::StdArc > * GetHTransducer (const std::vector< std::vector< int32 > > &ilabel_info, const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, const HTransducerConfig &config, std::vector< int32 > *disambig_syms_left)
 Returns the H tranducer; result owned by caller. More...
 
void GetIlabelMapping (const std::vector< std::vector< int32 > > &ilabel_info_old, const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, std::vector< int32 > *old2new_map)
 GetIlabelMapping produces a mapping that's similar to HTK's logical-to-physical model mapping (i.e. More...
 
fst::VectorFst< fst::StdArc > * GetPdfToTransitionIdTransducer (const TransitionModel &trans_model)
 Returns a transducer from pdfs plus one (input) to transition-ids (output). More...
 
static void AddSelfLoopsReorder (const TransitionModel &trans_model, const std::vector< int32 > &disambig_syms, BaseFloat self_loop_scale, bool check_no_self_loops, fst::VectorFst< fst::StdArc > *fst)
 
static void AddSelfLoopsNoReorder (const TransitionModel &trans_model, const std::vector< int32 > &disambig_syms, BaseFloat self_loop_scale, bool check_no_self_loops, fst::VectorFst< fst::StdArc > *fst)
 
void AddSelfLoops (const TransitionModel &trans_model, const std::vector< int32 > &disambig_syms, BaseFloat self_loop_scale, bool reorder, bool check_no_self_loops, fst::VectorFst< fst::StdArc > *fst)
 For context, see AddSelfLoops(). More...
 
static bool IsReordered (const TransitionModel &trans_model, const std::vector< int32 > &alignment)
 
static bool SplitToPhonesInternal (const TransitionModel &trans_model, const std::vector< int32 > &alignment, bool reordered, std::vector< std::vector< int32 > > *split_output)
 
bool SplitToPhones (const TransitionModel &trans_model, const std::vector< int32 > &alignment, std::vector< std::vector< int32 > > *split_alignment)
 SplitToPhones splits up the TransitionIds in "alignment" into their individual phones (one vector per instance of a phone). More...
 
static void ConvertAlignmentForPhone (const TransitionModel &old_trans_model, const TransitionModel &new_trans_model, const ContextDependencyInterface &new_ctx_dep, const std::vector< int32 > &old_phone_alignment, const std::vector< int32 > &new_phone_window, bool old_is_reordered, bool new_is_reordered, std::vector< int32 > *new_phone_alignment)
 This function is used internally inside ConvertAlignment; it converts the alignment for a single phone. More...
 
static bool ComputeNewPhoneLengths (const HmmTopology &topology, const std::vector< int32 > &mapped_phones, const std::vector< int32 > &old_lengths, int32 conversion_shift, int32 subsample_factor, std::vector< int32 > *new_lengths)
 This function, called from ConvertAlignmentInternal(), works out suitable new lengths of phones in the case where subsample_factor != 1. More...
 
static bool ConvertAlignmentInternal (const TransitionModel &old_trans_model, const TransitionModel &new_trans_model, const ContextDependencyInterface &new_ctx_dep, const std::vector< int32 > &old_alignment, int32 conversion_shift, int32 subsample_factor, bool new_is_reordered, const std::vector< int32 > *phone_map, std::vector< int32 > *new_alignment)
 This function is the same as 'ConvertAligment', but instead of the 'repeat_frames' option it supports the 'conversion_shift' option; see the documentation of ComputeNewPhoneLengths() for what 'conversion_shift' is for. More...
 
bool ConvertAlignment (const TransitionModel &old_trans_model, const TransitionModel &new_trans_model, const ContextDependencyInterface &new_ctx_dep, const std::vector< int32 > &old_alignment, int32 subsample_factor, bool repeat_frames, bool reorder, const std::vector< int32 > *phone_map, std::vector< int32 > *new_alignment)
 ConvertAlignment converts an alignment that was created using one model, to another model. More...
 
static BaseFloat GetScaledTransitionLogProb (const TransitionModel &trans_model, int32 trans_id, BaseFloat transition_scale, BaseFloat self_loop_scale)
 
void AddTransitionProbs (const TransitionModel &trans_model, const std::vector< int32 > &disambig_syms, BaseFloat transition_scale, BaseFloat self_loop_scale, fst::VectorFst< fst::StdArc > *fst)
 Adds transition-probs, with the supplied scales (see Scaling of transition and acoustic probabilities), to the graph. More...
 
void AddTransitionProbs (const TransitionModel &trans_model, BaseFloat transition_scale, BaseFloat self_loop_scale, Lattice *lat)
 This is as AddSelfLoops(), but operates on a Lattice, where it affects the graph part of the weight (the first element of the pair). More...
 
bool ConvertPhnxToProns (const std::vector< int32 > &phnx, const std::vector< int32 > &words, int32 word_start_sym, int32 word_end_sym, std::vector< std::vector< int32 > > *prons)
 
void GetRandomAlignmentForPhone (const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, const std::vector< int32 > &phone_window, std::vector< int32 > *alignment)
 
void ChangeReorderingOfAlignment (const TransitionModel &trans_model, std::vector< int32 > *alignment)
 
void GetPdfToPhonesMap (const TransitionModel &trans_model, std::vector< std::set< int32 > > *pdf2phones)
 
void ConvertTransitionIdsToPdfs (const TransitionModel &trans_model, const std::vector< int32 > &disambig_syms, fst::VectorFst< fst::StdArc > *fst)
 Converts all transition-ids in the FST to pdfs plus one. More...
 
void TestVectorToPosteriorEntry ()
 
void TestPosteriorIo ()
 
void WritePosterior (std::ostream &os, bool binary, const Posterior &post)
 stand-alone function for writing a Posterior. More...
 
void ReadPosterior (std::istream &os, bool binary, Posterior *post)
 stand-alone function for reading a Posterior. More...
 
void ScalePosterior (BaseFloat scale, Posterior *post)
 Scales the BaseFloat (weight) element in the posterior entries. More...
 
BaseFloat TotalPosterior (const Posterior &post)
 Returns the total of all the weights in "post". More...
 
bool PosteriorEntriesAreDisjoint (const std::vector< std::pair< int32, BaseFloat > > &post_elem1, const std::vector< std::pair< int32, BaseFloat > > &post_elem2)
 Returns true if the two lists of pairs have no common .first element. More...
 
int32 MergePosteriors (const Posterior &post1, const Posterior &post2, bool merge, bool drop_frames, Posterior *post)
 Merge two sets of posteriors, which must have the same length. More...
 
void AlignmentToPosterior (const std::vector< int32 > &ali, Posterior *post)
 Convert an alignment to a posterior (with a scale of 1.0 on each entry). More...
 
void SortPosteriorByPdfs (const TransitionModel &tmodel, Posterior *post)
 Sorts posterior entries so that transition-ids with same pdf-id are next to each other. More...
 
void ConvertPosteriorToPdfs (const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
 Converts a posterior over transition-ids to be a posterior over pdf-ids. More...
 
void ConvertPosteriorToPhones (const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
 Converts a posterior over transition-ids to be a posterior over phones. More...
 
void WeightSilencePost (const TransitionModel &trans_model, const ConstIntegerSet< int32 > &silence_set, BaseFloat silence_scale, Posterior *post)
 Weight any silence phones in the posterior (i.e. More...
 
void WeightSilencePostDistributed (const TransitionModel &trans_model, const ConstIntegerSet< int32 > &silence_set, BaseFloat silence_scale, Posterior *post)
 This is similar to WeightSilencePost, except that on each frame it works out the amount by which the overall posterior would be reduced, and scales down everything on that frame by the same amount. More...
 
static BaseFloat GetTotalPosterior (const std::vector< std::pair< int32, BaseFloat > > &post_entry)
 
BaseFloat VectorToPosteriorEntry (const VectorBase< BaseFloat > &log_likes, int32 num_gselect, BaseFloat min_post, std::vector< std::pair< int32, BaseFloat > > *post_entry)
 Given a vector of log-likelihoods (typically of Gaussians in a GMM but could be of pdf-ids), a number gselect >= 1 and a minimum posterior 0 <= min_post < 1, it gets the posterior for each element of log-likes by applying Softmax(), then prunes the posteriors using "gselect" and "min_post" (keeping at least one), and outputs the result into "post_entry", sorted from greatest to least posterior. More...
 
template<typename Real >
void PosteriorToMatrix (const Posterior &post, const int32 post_dim, Matrix< Real > *mat)
 This converts a Posterior to a Matrix. More...
 
template void PosteriorToMatrix< float > (const Posterior &post, const int32 post_dim, Matrix< float > *mat)
 
template void PosteriorToMatrix< double > (const Posterior &post, const int32 post_dim, Matrix< double > *mat)
 
template<typename Real >
void PosteriorToPdfMatrix (const Posterior &post, const TransitionModel &model, Matrix< Real > *mat)
 This converts a Posterior to a Matrix. More...
 
template void PosteriorToPdfMatrix< float > (const Posterior &post, const TransitionModel &model, Matrix< float > *mat)
 
template void PosteriorToPdfMatrix< double > (const Posterior &post, const TransitionModel &model, Matrix< double > *mat)
 
void TestTransitionModel ()
 
bool GetPdfsForPhones (const TransitionModel &trans_model, const std::vector< int32 > &phones, std::vector< int32 > *pdfs)
 Works out which pdfs might correspond to the given phones. More...
 
bool GetPhonesForPdfs (const TransitionModel &trans_model, const std::vector< int32 > &pdfs, std::vector< int32 > *phones)
 Works out which phones might correspond to the given pdfs. More...
 
static int32 MapPhone (const std::vector< int32 > &phone_map, int32 phone)
 
void TrimTrailingWhitespace (std::string *str)
 
static fst::StdVectorFstCreateGenFst (bool seps, const fst::SymbolTable *pst)
 
ArpaLmCompilerCompile (bool seps, const std::string &infile)
 
fst::StdArc::StateId AddToChainFsa (fst::StdMutableFst *fst, fst::StdArc::StateId last_state, int64 symbol)
 
void AddSelfLoops (fst::StdMutableFst *fst)
 
bool CoverageTest (bool seps, const std::string &infile)
 
bool ScoringTest (bool seps, const std::string &infile, const std::string &sentence, float expected)
 
bool ThrowsExceptionTest (bool seps, const std::string &infile)
 
bool BuildConstArpaLm (const ArpaParseOptions &options, const std::string &arpa_rxfilename, const std::string &const_arpa_wxfilename)
 
template<typename FST >
bool DecodeUtteranceLatticeIncremental (LatticeIncrementalDecoderTpl< FST > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignments_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 TODO. More...
 
template<typename FST >
bool DecodeUtteranceLatticeFaster (LatticeFasterDecoderTpl< FST > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignments_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 This function DecodeUtteranceLatticeFaster is used in several decoders, and we have moved it here. More...
 
template bool DecodeUtteranceLatticeIncremental (LatticeIncrementalDecoderTpl< fst::Fst< fst::StdArc > > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 
template bool DecodeUtteranceLatticeIncremental (LatticeIncrementalDecoderTpl< fst::GrammarFst > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 
template bool DecodeUtteranceLatticeFaster (LatticeFasterDecoderTpl< fst::Fst< fst::StdArc > > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 
template bool DecodeUtteranceLatticeFaster (LatticeFasterDecoderTpl< fst::GrammarFst > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 
bool DecodeUtteranceLatticeSimple (LatticeSimpleDecoder &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 
void ModifyGraphForCarefulAlignment (fst::VectorFst< fst::StdArc > *fst)
 This function modifies the decoding graph for what we call "careful alignment". More...
 
void AlignUtteranceWrapper (const AlignConfig &config, const std::string &utt, BaseFloat acoustic_scale, fst::VectorFst< fst::StdArc > *fst, DecodableInterface *decodable, Int32VectorWriter *alignment_writer, BaseFloatWriter *scores_writer, int32 *num_done, int32 *num_error, int32 *num_retried, double *tot_like, int64 *frame_count, BaseFloatVectorWriter *per_frame_acwt_writer=NULL)
 AlignUtteranceWapper is a wrapper for alignment code used in training, that is called from many different binaries, e.g. More...
 
static void AddCompactLatticeArcToLattice (const CompactLatticeArc &clat_arc, LatticeArc::StateId src_state, Lattice *lat)
 
static int32 TotalNumArcs (const CompactLattice &clat)
 
void ComposeCompactLatticePruned (const ComposeLatticePrunedOptions &opts, const CompactLattice &clat, fst::DeterministicOnDemandFst< fst::StdArc > *det_fst, CompactLattice *composed_clat)
 Does pruned composition of a lattice 'clat' with a DeterministicOnDemandFst 'det_fst'; implements LM rescoring. More...
 
BaseFloat SentenceLevelConfidence (const CompactLattice &clat, int32 *num_paths, std::vector< int32 > *best_sentence, std::vector< int32 > *second_best_sentence)
 Caution: this function is not the only way to get confidences in Kaldi. More...
 
BaseFloat SentenceLevelConfidence (const Lattice &lat, int32 *num_paths, std::vector< int32 > *best_sentence, std::vector< int32 > *second_best_sentence)
 This version of SentenceLevelConfidence takes as input a state-level lattice. More...
 
CompactLatticeRandCompactLattice ()
 
LatticeRandLattice ()
 
void TestCompactLatticeTable (bool binary)
 
void TestCompactLatticeTableCross (bool binary)
 
void TestLatticeTable (bool binary)
 
void TestLatticeTableCross (bool binary)
 
template<class OrigWeightType >
CompactLatticeConvertToCompactLattice (fst::VectorFst< OrigWeightType > *ifst)
 Converts lattice types if necessary, deleting its input. More...
 
template<>
CompactLatticeConvertToCompactLattice (CompactLattice *ifst)
 
template<class OrigWeightType >
LatticeConvertToLattice (fst::VectorFst< OrigWeightType > *ifst)
 Converts lattice types if necessary, deleting its input. More...
 
template<>
LatticeConvertToLattice (Lattice *ifst)
 
bool WriteCompactLattice (std::ostream &os, bool binary, const CompactLattice &t)
 
CompactLatticeReadCompactLatticeText (std::istream &is)
 
LatticeReadLatticeText (std::istream &is)
 
bool ReadCompactLattice (std::istream &is, bool binary, CompactLattice **clat)
 
bool WriteLattice (std::ostream &os, bool binary, const Lattice &t)
 
bool ReadLattice (std::istream &is, bool binary, Lattice **lat)
 
void GetPerFrameAcousticCosts (const Lattice &nbest, Vector< BaseFloat > *per_frame_loglikes)
 This function extracts the per-frame log likelihoods from a linear lattice (which we refer to as an 'nbest' lattice elsewhere in Kaldi code). More...
 
int32 LatticeStateTimes (const Lattice &lat, vector< int32 > *times)
 This function iterates over the states of a topologically sorted lattice and counts the time instance corresponding to each state. More...
 
int32 CompactLatticeStateTimes (const CompactLattice &lat, vector< int32 > *times)
 As LatticeStateTimes, but in the CompactLattice format. More...
 
bool ComputeCompactLatticeAlphas (const CompactLattice &clat, vector< double > *alpha)
 
bool ComputeCompactLatticeBetas (const CompactLattice &clat, vector< double > *beta)
 
template<class LatType >
bool PruneLattice (BaseFloat beam, LatType *lat)
 
template bool PruneLattice (BaseFloat beam, Lattice *lat)
 
template bool PruneLattice (BaseFloat beam, CompactLattice *lat)
 
BaseFloat LatticeForwardBackward (const Lattice &lat, Posterior *arc_post, double *acoustic_like_sum=NULL)
 This function does the forward-backward over lattices and computes the posterior probabilities of the arcs. More...
 
void LatticeActivePhones (const Lattice &lat, const TransitionModel &trans, const vector< int32 > &silence_phones, vector< std::set< int32 > > *active_phones)
 Given a lattice, and a transition model to map pdf-ids to phones, outputs for each frame the set of phones active on that frame. More...
 
void ConvertLatticeToPhones (const TransitionModel &trans_model, Lattice *lat)
 Given a lattice, and a transition model to map pdf-ids to phones, replace the output symbols (presumably words), with phones; we use the TransitionModel to work out the phone sequence. More...
 
static double LogAddOrMax (bool viterbi, double a, double b)
 
template<typename LatticeType >
double ComputeLatticeAlphasAndBetas (const LatticeType &lat, bool viterbi, vector< double > *alpha, vector< double > *beta)
 
template double ComputeLatticeAlphasAndBetas (const Lattice &lat, bool viterbi, vector< double > *alpha, vector< double > *beta)
 
template double ComputeLatticeAlphasAndBetas (const CompactLattice &lat, bool viterbi, vector< double > *alpha, vector< double > *beta)
 
void CompactLatticeLimitDepth (int32 max_arcs_per_frame, CompactLattice *clat)
 This function limits the depth of the lattice, per frame: that means, it does not allow more than a specified number of arcs active on any given frame. More...
 
void TopSortCompactLatticeIfNeeded (CompactLattice *clat)
 Topologically sort the compact lattice if not already topologically sorted. More...
 
void TopSortLatticeIfNeeded (Lattice *clat)
 Topologically sort the lattice if not already topologically sorted. More...
 
BaseFloat CompactLatticeDepth (const CompactLattice &clat, int32 *num_frames)
 Returns the depth of the lattice, defined as the average number of arcs crossing any given frame. More...
 
void CompactLatticeDepthPerFrame (const CompactLattice &clat, std::vector< int32 > *depth_per_frame)
 This function returns, for each frame, the number of arcs crossing that frame. More...
 
void ConvertCompactLatticeToPhones (const TransitionModel &trans_model, CompactLattice *clat)
 Given a lattice, and a transition model to map pdf-ids to phones, replace the sequences of transition-ids with sequences of phones. More...
 
bool LatticeBoost (const TransitionModel &trans, const std::vector< int32 > &alignment, const std::vector< int32 > &silence_phones, BaseFloat b, BaseFloat max_silence_error, Lattice *lat)
 Boosts LM probabilities by b * [number of frame errors]; equivalently, adds -b*[number of frame errors] to the graph-component of the cost of each arc/path. More...
 
BaseFloat LatticeForwardBackwardMpeVariants (const TransitionModel &trans, const std::vector< int32 > &silence_phones, const Lattice &lat, const std::vector< int32 > &num_ali, std::string criterion, bool one_silence_class, Posterior *post)
 This function implements either the MPFE (minimum phone frame error) or SMBR (state-level minimum bayes risk) forward-backward, depending on whether "criterion" is "mpfe" or "smbr". More...
 
bool CompactLatticeToWordAlignment (const CompactLattice &clat, std::vector< int32 > *words, std::vector< int32 > *begin_times, std::vector< int32 > *lengths)
 This function takes a CompactLattice that should only contain a single linear sequence (e.g. More...
 
bool CompactLatticeToWordProns (const TransitionModel &tmodel, const CompactLattice &clat, std::vector< int32 > *words, std::vector< int32 > *begin_times, std::vector< int32 > *lengths, std::vector< std::vector< int32 > > *prons, std::vector< std::vector< int32 > > *phone_lengths)
 This function takes a CompactLattice that should only contain a single linear sequence (e.g. More...
 
void CompactLatticeShortestPath (const CompactLattice &clat, CompactLattice *shortest_path)
 A form of the shortest-path/best-path algorithm that's specially coded for CompactLattice. More...
 
void AddWordInsPenToCompactLattice (BaseFloat word_ins_penalty, CompactLattice *clat)
 This function add the word insertion penalty to graph score of each word in the compact lattice. More...
 
bool RescoreCompactLatticeInternal (const TransitionModel *tmodel, BaseFloat speedup_factor, DecodableInterface *decodable, CompactLattice *clat)
 RescoreCompactLatticeInternal is the internal code for both RescoreCompactLattice and RescoreCompatLatticeSpeedup. More...
 
bool RescoreCompactLatticeSpeedup (const TransitionModel &tmodel, BaseFloat speedup_factor, DecodableInterface *decodable, CompactLattice *clat)
 This function is like RescoreCompactLattice, but it is modified to avoid computing probabilities on most frames where all the pdf-ids are the same. More...
 
bool RescoreCompactLattice (DecodableInterface *decodable, CompactLattice *clat)
 This function *adds* the negated scores obtained from the Decodable object, to the acoustic scores on the arcs. More...
 
bool RescoreLattice (DecodableInterface *decodable, Lattice *lat)
 This function *adds* the negated scores obtained from the Decodable object, to the acoustic scores on the arcs. More...
 
BaseFloat LatticeForwardBackwardMmi (const TransitionModel &trans, const Lattice &lat, const std::vector< int32 > &num_ali, bool drop_frames, bool convert_to_pdf_ids, bool cancel, Posterior *arc_post)
 This function can be used to compute posteriors for MMI, with a positive contribution for the numerator and a negative one for the denominator. More...
 
int32 LongestSentenceLength (const Lattice &lat)
 This function returns the number of words in the longest sentence in a CompactLattice (i.e. More...
 
int32 LongestSentenceLength (const CompactLattice &lat)
 This function returns the number of words in the longest sentence in a CompactLattice, i.e. More...
 
void ComposeCompactLatticeDeterministic (const CompactLattice &clat, fst::DeterministicOnDemandFst< fst::StdArc > *det_fst, CompactLattice *composed_clat)
 This function Composes a CompactLattice format lattice with a DeterministicOnDemandFst<fst::StdFst> format fst, and outputs another CompactLattice format lattice. More...
 
void ComputeAcousticScoresMap (const Lattice &lat, unordered_map< std::pair< int32, int32 >, std::pair< BaseFloat, int32 >, PairHasher< int32 > > *acoustic_scores)
 This function computes the mapping from the pair (frame-index, transition-id) to the pair (sum-of-acoustic-scores, num-of-occurences) over all occurences of the transition-id in that frame. More...
 
void ReplaceAcousticScoresFromMap (const unordered_map< std::pair< int32, int32 >, std::pair< BaseFloat, int32 >, PairHasher< int32 > > &acoustic_scores, Lattice *lat)
 This function restores acoustic scores computed using the function ComputeAcousticScoresMap into the lattice. More...
 
int32 LatticeStateTimes (const Lattice &lat, std::vector< int32 > *times)
 This function iterates over the states of a topologically sorted lattice and counts the time instance corresponding to each state. More...
 
int32 CompactLatticeStateTimes (const CompactLattice &clat, std::vector< int32 > *times)
 As LatticeStateTimes, but in the CompactLattice format. More...
 
bool ComputeCompactLatticeAlphas (const CompactLattice &lat, std::vector< double > *alpha)
 
bool ComputeCompactLatticeBetas (const CompactLattice &lat, std::vector< double > *beta)
 
template<typename LatticeType >
double ComputeLatticeAlphasAndBetas (const LatticeType &lat, bool viterbi, std::vector< double > *alpha, std::vector< double > *beta)
 
void LatticeActivePhones (const Lattice &lat, const TransitionModel &trans, const std::vector< int32 > &sil_phones, std::vector< std::set< int32 > > *active_phones)
 Given a lattice, and a transition model to map pdf-ids to phones, outputs for each frame the set of phones active on that frame. More...
 
template<class LatticeType >
bool PruneLattice (BaseFloat beam, LatticeType *lat)
 Prunes a lattice or compact lattice. More...
 
CompactLatticeRandDeterministicCompactLattice ()
 
void TestMinimizeCompactLattice ()
 
bool PhoneAlignLattice (const CompactLattice &lat, const TransitionModel &tmodel, const PhoneAlignLatticeOptions &opts, CompactLattice *lat_out)
 Outputs a lattice in which the arcs correspond exactly to sequences of phones, so the boundaries between the arcs correspond to the boundaries between phones If remove-epsilon == false and replace-output-symbols == false, but an arc may have >1 phone on it, but the boundaries will still correspond with the boundaries between phones. More...
 
void TestPushCompactLatticeStrings ()
 
void TestPushCompactLatticeWeights ()
 
void GenerateLexicon (const std::vector< int32 > &phones, bool allow_zero_words, bool allow_empty_word, bool allow_multiple_prons, std::vector< std::vector< int32 > > *lexicon)
 
static void PrintLexicon (const std::vector< std::vector< int32 > > &lexicon)
 
static void PrintWordsAndPhones (const std::vector< int32 > &words, const std::vector< int32 > &phones)
 
void GenerateWordAndPhoneSequence (std::vector< std::vector< int32 > > &lexicon, std::vector< int32 > *phone_seq, std::vector< int32 > *word_seq)
 
void GenerateCompactLatticeRandomly (const std::vector< int32 > &alignment, const std::vector< int32 > &words, CompactLattice *clat)
 
void TestWordAlignLatticeLexicon ()
 
static bool IsPlausibleWord (const WordAlignLatticeLexiconInfo &lexicon_info, const TransitionModel &tmodel, int32 word_id, const std::vector< int32 > &transition_ids)
 
static void MapSymbols (const WordAlignLatticeLexiconInfo &lexicon_info, CompactLattice *lat)
 Testing code; map word symbols in the lattice "lat" using the equivalence-classes obtained from the lexicon, using the function EquivalenceClassOf in the lexicon_info object. More...
 
static bool TestWordAlignedLattice (const WordAlignLatticeLexiconInfo &lexicon_info, const TransitionModel &tmodel, CompactLattice clat, CompactLattice aligned_clat, bool allow_duplicate_paths)
 
bool WordAlignLatticeLexicon (const CompactLattice &lat, const TransitionModel &tmodel, const WordAlignLatticeLexiconInfo &lexicon_info, const WordAlignLatticeLexiconOpts &opts, CompactLattice *lat_out)
 Align lattice so that each arc has the transition-ids on it that correspond to the word that is on that arc. More...
 
bool ReadLexiconForWordAlign (std::istream &is, std::vector< std::vector< int32 > > *lexicon)
 Read the lexicon in the special format required for word alignment. More...
 
void TestWordAlignedLatticeLexicon (const CompactLattice &lat, const TransitionModel &tmodel, const std::vector< std::vector< int32 > > &lexicon, const CompactLattice &aligned_lat, bool allow_duplicate_paths)
 This function is designed to crash if something went wrong with the word-alignment of the lattice. More...
 
static bool IsPlausibleWord (const WordBoundaryInfo &info, const TransitionModel &tmodel, const std::vector< int32 > &transition_ids)
 
bool WordAlignLattice (const CompactLattice &lat, const TransitionModel &tmodel, const WordBoundaryInfo &info, int32 max_states, CompactLattice *lat_out)
 Align lattice so that each arc has the transition-ids on it that correspond to the word that is on that arc. More...
 
void TestWordAlignedLattice (const CompactLattice &lat, const TransitionModel &tmodel, const WordBoundaryInfo &info, const CompactLattice &aligned_lat)
 You should only test a lattice if WordAlignLattice returned true (i.e. More...
 
void RegisterCuAllocatorOptions (OptionsItf *po)
 
template<typename T >
std::ostream & operator<< (std::ostream &out, const CuArray< T > &vec)
 Print the vector to stream. More...
 
template<class T >
void AssertEqual (const std::vector< T > &vec1, const std::vector< T > &vec2)
 
template<class T >
static void UnitTestCuArray ()
 
template<typename Real >
static bool ApproxEqual (const CuBlockMatrix< Real > &A, const CuBlockMatrix< Real > &B, float tol=0.001)
 
template<class Real >
static void UnitTestCuBlockMatrixIO ()
 
template<class Real >
static void UnitTestCuBlockMatrixAddMatBlock ()
 
template<class Real >
static void UnitTestCuBlockMatrixAddMatMat ()
 
template<typename Real >
void CuBlockMatrixUnitTest ()
 
template<typename Real >
std::ostream & operator<< (std::ostream &out, const CuBlockMatrix< Real > &mat)
 Print the matrix to stream. More...
 
template std::ostream & operator<< (std::ostream &out, const CuBlockMatrix< float > &mat)
 
template std::ostream & operator<< (std::ostream &out, const CuBlockMatrix< double > &mat)
 
void CuCompressedMatrixTestSign ()
 
void CuCompressedMatrixTestNonnegative ()
 
void CuCompressedMatrixTestSymmetric ()
 
CuCompressedMatrixBaseNewCuCompressedMatrix (CuCompressedMatrixType t, BaseFloat range, bool truncate=true)
 This function allocates a new CuCompressedMatrix with type determined by t, and with the 'range' and 'truncate' parameters provided to the constructor of class CuCompressedMatrix. More...
 
template<typename Real >
void TestCuMatrixResize (int32 size_multiple)
 
template<typename Real >
void CudaMatrixResizeTest ()
 
void SynchronizeGpu ()
 The function SynchronizeGpu(), which for convenience is defined whether or not we have compiled for CUDA, is intended to be called in places where threads need to be synchronized. More...
 
template<typename Real >
static void UnitTestCuMathRandomize ()
 
template<typename Real >
static void UnitTestEnsureNonzero ()
 
template<typename Real >
static void UnitTestCuMathCopy ()
 
template<typename Real >
static void UnitTestCuMathSplice ()
 
template<typename Real >
static void UnitTestCuMathComputeLstmNonlinearity ()
 
void UnitTestLstmNonlinearity ()
 
template<typename Real >
static void UnitTestBackpropLstmNonlinearity ()
 
template<typename Real >
static void UnitTestCuMathNormalizePerRow ()
 
template<typename Real >
static void UnitTestCuMathNormalizePerRow_v2 ()
 
template<typename Real >
static void UnitTestCuDiffNormalizePerRow ()
 
template<typename Real >
void CudaMathUnitTest ()
 
template<typename Real >
void TestCuMatrixSum (int32 dim)
 
template<typename Real >
void TestCuMatrixMax (int32 dim)
 
template<typename Real >
void TestCuMatrixMin (int32 dim)
 
template<typename Real >
void TestCuMatrixDivRowsVec (int32 dim)
 
template<typename Real >
void TestCuMatrixTransposeNS (int32 dim)
 
template<typename Real >
void TestCuMatrixTransposeS (int32 dim)
 
template<typename Real >
void TestCuMatrixTransposeCross (int32 dim)
 
template<typename Real >
void TestCuMatrixAddMat (int32 dim, int32 num_row_blocks, int32 num_col_blocks)
 
template<typename Real >
void TestCuMatrixAddMatBlocks (int32 dim, int32 num_row_blocks, int32 num_col_blocks)
 
template<typename Real >
void TestCuMatrixMatMat (int32 dim)
 
template<typename Real >
void TestCuMatrixMatMatBatched (int32 dim, int32 batchCount)
 
template<typename Real >
void TestCuMatrixAddDiagVecMat (int32 dim, MatrixTransposeType trans)
 
template<typename Real >
void TestSymInvertPosDef (int32 dim)
 
template<typename Real >
static void TestCuMatrixCompObjfAndDeriv (int32 dim)
 
template<typename Real >
static void TestCuFindRowMaxId (int32 dim)
 
template<typename Real >
void TestCuMatrixSigmoid (int32 dim)
 
template<typename Real >
void TestCuMatrixHeaviside (int32 dim)
 
template<typename Real >
void TestCuMatrixMulRowsGroupMat (int32 dim)
 
template<typename Real >
void TestCuMatrixDiffSoftmax (int32 dim)
 
template<typename Real >
void TestCuMatrixDiffLogSoftmax (int32 dim)
 
template<typename Real >
void TestCuMatrixSoftmax (int32 dim)
 
template<typename Real >
void TestCuMatrixLogSoftmax (int32 dim)
 
template<typename Real >
void TestCuMatrixGroupPnorm (int32 dim)
 
template<typename Real >
void TestCuMatrixDiffGroupPnorm (int32 dim)
 
template<typename Real >
void TestCuMatrixGroupMax (int32 dim)
 
template<typename Real >
void TestCuMatrixGroupMaxAllGroupSizes (int32 dim)
 
template<typename Real >
void TestCuMatrixGroupMaxDeriv (int32 dim)
 
template<typename Real >
void TestCuMatrixTraceMatMat (int32 dim)
 
template<typename Real >
void TestCuMatrixCholesky (int32 dim)
 
template<typename Real >
void TestCuMatrixCopyLowerToUpper (int32 dim)
 
template<typename Real >
void TestCuMatrixCopyFromTp (int32 dim, MatrixTransposeType trans)
 
template<typename Real >
void TestCuMatrixCopyFromSp (int32 dim)
 
template<typename Real >
void TestCuMatrixCopyUpperToLower (int32 dim)
 
template<typename Real >
void TestCuMatrixSetZeroAboveDiag (int32 dim)
 
template<typename Real >
void TestCuMatrixLookup (int32 dim)
 
template<typename Real >
void TestCuMatrixCopyRows1 (int32 dim)
 
template<typename Real >
void TestCuMatrixCopyRows2 (int32 dim)
 
template<typename Real >
void TestCuMatrixCopyToRows (int32 dim)
 
template<typename Real >
void TestCuMatrixAddRows1 (int32 dim)
 
template<typename Real >
void TestCuMatrixAddRows2 (int32 dim)
 
template<typename Real >
void TestCuMatrixAddToRows (int32 dim)
 
template<typename Real >
void TestCuMatrixAddRowRanges (int32 dim)
 
template<typename Real >
void TestCuSparseMatrixTraceMatSmat (int32 dim)
 
template<typename Real >
void CudaMatrixSpeedTest ()
 
template<typename Real >
static void InitRand (VectorBase< Real > *v)
 
template<typename Real >
static void InitRand (MatrixBase< Real > *M)
 
template<typename Real >
static void RandZeroToOneMatrix (MatrixBase< Real > *mat)
 
template<typename Real >
static void UnitTestCuMatrixTraceMatMat ()
 
template<typename Real >
static void UnitTestCuCholesky ()
 
template<typename Real >
static void UnitTestCuMatrixApplyLog ()
 
template<typename Real >
static void UnitTestCuMatrixApplyExpSpecial ()
 
template<typename Real >
static void UnitTestCuMatrixApplyExp ()
 
template<typename Real >
static void UnitTestCuMatrixApplyExpLimited ()
 
template<typename Real >
static void UnitTestCuMatrixSigmoid ()
 
template<typename Real >
static void UnitTestCuMatrixScale ()
 
template<typename Real >
static void UnitTestCuMatrixAdd ()
 
template<typename Real >
static void UnitTestCuMatrixSoftHinge ()
 
template<typename Real >
static void UnitTestCuMatrixGroupPnorm ()
 
template<typename Real >
static void UnitTestCuMatrixGroupMax ()
 
template<typename Real >
static void UnitTestCuMatrixSet ()
 
template<typename Real >
static void UnitTestCuMatrixApplyPow ()
 
template<typename Real >
static void UnitTestCuMatrixApplyPowAbs ()
 
template<typename Real >
static void UnitTestCuMatrixCopyRowsFromVec ()
 
template<typename Real >
static void UnitTestCuMatrixCopyColsFromVec ()
 
template<typename Real >
static void UnitTestCuMatrixCopyRows ()
 
template<typename Real >
static void UnitTestCuMatrixCopyToRows ()
 
template<typename Real >
static void UnitTestCuMatrixAddRows ()
 
template<typename Real >
static void UnitTestCuMatrixMulRows ()
 
template<typename Real >
static void UnitTestCuMatrixAddToRows ()
 
template<typename Real >
void UnitTestCuMatrixCopyCross ()
 
template<typename Real >
void UnitTestCuMatrixCopyCross2 ()
 
template<typename Real >
static void UnitTestCuMatrixSumColumnRanges ()
 
template<typename Real >
static void UnitTestCuMatrixAddRowRanges ()
 
template<typename Real >
static void UnitTestCuMatrixCopyCols ()
 
template<typename Real >
static void UnitTextCuMatrixAddSmat ()
 
template<typename Real >
static void UnitTextCuMatrixAddMatSmat ()
 
template<typename Real >
static void UnitTextCuMatrixAddSmatMat ()
 
template<typename Real >
static void UnitTestCuMatrixAddCols ()
 
template<typename Real >
static void UnitTestCuMatrixApplyFloor ()
 
template<typename Real >
static void UnitTestCuMatrixApplyCeiling ()
 
template<typename Real >
static void UnitTestCuMatrixApplyHeaviside ()
 
template<typename Real >
static void UnitTestCuMatrixHeaviside ()
 
template<typename Real >
static void UnitTestCuMatrixMulElements ()
 
template<typename Real >
static void UnitTestCuMatrixDivElements ()
 
template<typename Real >
static void UnitTestCuMatrixMax ()
 
template<typename Real >
static void UnitTestCuMatrixMin ()
 
template<typename Real >
static void UnitTestCuMatrixMulColsVec ()
 
template<typename Real >
static void UnitTestCuMatrixMulRowsVec ()
 
template<typename Real >
static void UnitTestCuMatrixMulRowsGroupMat ()
 
template<typename Real >
static void UnitTestCuMatrixDiffGroupPnorm ()
 
template<typename Real >
static void UnitTestCuMatrixGroupMaxDeriv ()
 
template<typename Real >
static void UnitTestCuMatrixAddDiagVecMat ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatDiagVec ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatMatElements ()
 
template<typename Real >
static void UnitTestCuMatrixSetMatMatDivMat ()
 
template<typename Real >
static void UnitTestCuMatrixDivRowsVec ()
 
template<typename Real >
static void UnitTestCuMatrixAddMat ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatBlocks1 ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatBlocks1Trans ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatBlocks2 ()
 
template<typename Real >
static void UnitTestCuMatrixReduceSum ()
 
template<typename Real >
static void UnitTestCuMatrixReduceMax ()
 
template<typename Real >
static void UnitTestCuMatrixReduceMin ()
 
template<typename Real >
static void UnitTestCuMatrixAddVecToCols ()
 
template<typename Real >
static void UnitTestCuMatrixAddVecToRows ()
 
template<typename Real >
static void UnitTestCuMatrixSymAddMat2 ()
 
template<typename Real >
static void UnitTestCuMatrixSymInvertPosDef ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatMat ()
 
template<typename Real >
static void UnitTestCuMatrixAddVecVec ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatMatBatched ()
 
template<typename Real >
static void UnitTestCuMatrixAddToDiag ()
 
template<typename Real >
static void UnitTestCuMatrixAdd2 ()
 
template<typename Real >
static void UnitTestCuMatrixCopyFromMat ()
 
template<typename Real >
static void UnitTestCuMatrixCopyFromTp ()
 
template<typename Real >
static void UnitTestCuMatrixAddMatTp ()
 
template<typename Real >
static void UnitTestCuMatrixTranspose ()
 
template<typename Real >
static void UnitTestCuMatrixAddTpMat ()
 
template<typename Real >
static void UnitTestCuVectorAddVec ()
 
template<typename Real >
static void UnitTestCuVectorAddRowSumMat ()
 
template<typename Real >
static void UnitTestCuVectorAddRowSumMatLarge ()
 
template<typename Real >
static void UnitTestCuVectorAddColSumMat ()
 
template<typename Real >
static void UnitTestCuSubMatrix ()
 
template<typename Real >
static void UnitTestCuVectorAddColSumMatLarge ()
 
template<typename Real >
static void UnitTestCuVectorInvertElements ()
 
template<typename Real >
static void UnitTestCuMatrixInvertElements ()
 
template<class Real >
static void UnitTestCuMatrixIO ()
 
template<typename Real >
static void UnitTestCuVectorAddTpVec ()
 
template<typename Real >
static void UnitTestCuApproxEqual ()
 
template<typename Real >
static void UnitTestCuVectorMulTp ()
 
template<typename Real , typename OtherReal >
static void UnitTestCuCopy ()
 
template<typename Real >
static void UnitTestCuSigmoid ()
 
template<typename Real >
static void UnitTestCuDiffSigmoid ()
 
template<typename Real >
static void UnitTestCuDiffSoftmax ()
 
template<typename Real >
static void UnitTestCuDiffLogSoftmax ()
 
template<typename Real >
static void UnitTestCuSoftmax ()
 
template<typename Real >
static void UnitTestCuLogSoftmax ()
 
template<typename Real >
static void UnitTestCuFindRowMaxId ()
 
template<typename Real >
static void UnitTestCuDiffXent ()
 
template<typename Real >
void UnitTestCheck ()
 
template<typename Real >
void UnitTestSwapCu2Cu ()
 
template<typename Real >
void UnitTestSwapCu2M ()
 
template<typename Real >
void UnitTestCuTanh ()
 
template<typename Real >
static void UnitTestCuDiffTanh ()
 
static int32 DoubleFactorial (int32 i)
 
template<typename Real >
static void UnitTestCuMatrixSetRandn ()
 
template<typename Real >
static void UnitTestCuMatrixSetRandUniform ()
 
template<typename Real >
static void UnitTestCuMatrixCopyLowerToUpper ()
 
template<typename Real >
static void UnitTestCuMatrixSetZeroAboveDiag ()
 
template<typename Real >
static void UnitTestCuMatrixCopyUpperToLower ()
 
template<typename Real >
static void UnitTestCuMatrixObjfDeriv ()
 
template<typename Real >
static void UnitTestCuMatrixAddElements ()
 
template<typename Real >
static void UnitTestCuMatrixAddToElements ()
 
template<typename Real >
static void UnitTestCuMatrixLookup ()
 
template<typename Real >
static void UnitTestCuMatrixEqualElementMask ()
 
template<typename Real >
void CudaMatrixUnitTest ()
 
template<typename Real >
Real TraceMatMat (const CuMatrixBase< Real > &A, const CuMatrixBase< Real > &B, MatrixTransposeType trans)
 
template float TraceMatMat (const CuMatrixBase< float > &A, const CuMatrixBase< float > &B, MatrixTransposeType trans)
 
template double TraceMatMat (const CuMatrixBase< double > &A, const CuMatrixBase< double > &B, MatrixTransposeType trans)
 
template<typename Real >
void AddMatMatBatched (const Real alpha, std::vector< CuSubMatrix< Real > *> &C, const std::vector< CuSubMatrix< Real > *> &A, MatrixTransposeType transA, const std::vector< CuSubMatrix< Real > *> &B, MatrixTransposeType transB, const Real beta)
 Does multiple matrix multiplications, executing them in parallel using cuBLAS's gemmBatched if we are using a GPU. More...
 
template void AddMatMatBatched (const float alpha, std::vector< CuSubMatrix< float > * > &C, const std::vector< CuSubMatrix< float > * > &A, MatrixTransposeType transA, const std::vector< CuSubMatrix< float > * > &B, MatrixTransposeType transB, const float beta)
 
template void AddMatMatBatched (const double alpha, std::vector< CuSubMatrix< double > * > &C, const std::vector< CuSubMatrix< double > * > &A, MatrixTransposeType transA, const std::vector< CuSubMatrix< double > * > &B, MatrixTransposeType transB, const double beta)
 
template<typename Real >
std::ostream & operator<< (std::ostream &out, const CuMatrixBase< Real > &mat)
 Print the matrix to stream. More...
 
template std::ostream & operator<< (std::ostream &out, const CuMatrixBase< float > &mat)
 
template std::ostream & operator<< (std::ostream &out, const CuMatrixBase< double > &mat)
 
template<typename Real >
bool ApproxEqual (const CuMatrixBase< Real > &A, const CuMatrixBase< Real > &B, Real tol=0.01)
 
template<typename Real >
void AssertEqual (const CuMatrixBase< Real > &A, const CuMatrixBase< Real > &B, float tol=0.01)
 
template<typename Real >
bool SameDim (const CuMatrixBase< Real > &M, const CuMatrixBase< Real > &N)
 
template<typename Real >
bool SameDimAndStride (const CuMatrixBase< Real > &M, const CuMatrixBase< Real > &N)
 
template<typename Real >
static void AssertEqual (const CuPackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
 
template<typename Real >
static void AssertEqual (const PackedMatrix< Real > &A, const PackedMatrix< Real > &B, float tol=0.001)
 
template<typename Real >
static void AssertDiagEqual (const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float value, float tol=0.001)
 
template<typename Real >
static void AssertDiagEqual (const PackedMatrix< Real > &A, const PackedMatrix< Real > &B, float value, float tol=0.001)
 
template<typename Real >
static void AssertEqual (const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
 
template<typename Real >
static bool ApproxEqual (const PackedMatrix< Real > &A, const PackedMatrix< Real > &B, Real tol=0.001)
 
template<typename Real >
static void UnitTestCuPackedMatrixConstructor ()
 
template<typename Real >
static void UnitTestCuPackedMatrixCopy ()
 
template<typename Real >
static void UnitTestCuPackedMatrixTrace ()
 
template<typename Real >
static void UnitTestCuPackedMatrixScale ()
 
template<typename Real >
static void UnitTestCuPackedMatrixScaleDiag ()
 
template<typename Real >
static void UnitTestCuPackedMatrixAddToDiag ()
 
template<typename Real >
static void UnitTestCuPackedMatrixSetUnit ()
 
template<typename Real >
void CudaPackedMatrixUnitTest ()
 
template<typename Real >
std::ostream & operator<< (std::ostream &out, const CuPackedMatrix< Real > &mat)
 Print the matrix to stream. More...
 
template std::ostream & operator<< (std::ostream &out, const CuPackedMatrix< float > &mat)
 
template std::ostream & operator<< (std::ostream &out, const CuPackedMatrix< double > &mat)
 
template<typename T >
std::string ToString (const T &t)
 
template<typename Real >
std::string MeanVariance (const CuMatrixBase< Real > &m)
 
template<typename Real >
std::string MeanVariance (const CuVectorBase< Real > &v)
 
template<typename Real >
void CuRandUniformMatrixSpeedTest (const int32 iter)
 
template<typename Real >
void CuRandUniformMatrixBaseSpeedTest (const int32 iter)
 
template<typename Real >
void CuRandGaussianMatrixSpeedTest (const int32 iter)
 
template<typename Real >
void CuRandGaussianMatrixBaseSpeedTest (const int32 iter)
 
template<typename Real >
void CuRandUniformVectorSpeedTest (const int32 iter)
 
template<typename Real >
void CuRandGaussianVectorSpeedTest (const int32 iter)
 
template<typename Real >
static void UnitTestCuSpMatrixInvert (int32 dim)
 
template<typename Real >
static void UnitTestCuSpMatrixCopyFromMat (int32 dim, SpCopyType copy_type)
 
template<typename Real >
void CuSpMatrixSpeedTest ()
 
template<typename Real >
static void UnitTestCuSpMatrixConstructor ()
 
template<typename Real >
static void UnitTestCuSpMatrixApproxEqual ()
 
template<typename Real >
static void UnitTestCuSpMatrixOperator ()
 
template<typename Real >
static void UnitTestCuSpMatrixAddToDiag ()
 
template<typename Real >
static void UnitTestCuSpMatrixCopyFromMat ()
 
template<typename Real >
static void UnitTestCuSpMatrixInvert ()
 
template<typename Real >
static void UnitTestCuSpMatrixAddVec2 ()
 
template<typename Real >
static void UnitTestCuSpMatrixAddMat2 ()
 
template<typename Real >
static void UnitTestCuSpMatrixAddSp ()
 
template<typename Real , typename OtherReal >
static void UnitTestCuSpMatrixTraceSpSp ()
 
template<typename Real >
void UnitTestCuSpMatrixSetUnit ()
 
template<class Real >
static void UnitTestCuSpMatrixIO ()
 
template<typename Real , typename OtherReal >
static void UnitTestCuSpMatrixAddSp ()
 
template<typename Real >
void CudaSpMatrixUnitTest ()
 
template<typename Real , typename OtherReal >
void CudaSpMatrixUnitTest ()
 
template<typename Real , typename OtherReal >
Real TraceSpSp (const CuSpMatrix< Real > &A, const CuSpMatrix< OtherReal > &B)
 C++ templatd wrapper of ANSI-C CUBLAS function GEMM (matrix multiply) More...
 
template float TraceSpSp (const CuSpMatrix< float > &A, const CuSpMatrix< float > &B)
 
template float TraceSpSp (const CuSpMatrix< float > &A, const CuSpMatrix< double > &B)
 
template double TraceSpSp (const CuSpMatrix< double > &A, const CuSpMatrix< float > &B)
 
template double TraceSpSp (const CuSpMatrix< double > &A, const CuSpMatrix< double > &B)
 
template<typename Real >
bool ApproxEqual (const CuSpMatrix< Real > &A, const CuSpMatrix< Real > &B, Real tol=0.001)
 
template<typename Real >
void AssertEqual (const CuSpMatrix< Real > &A, const CuSpMatrix< Real > &B, Real tol=0.001)
 
template<typename Real >
static void UnitTestCuSparseMatrixConstructFromIndexes ()
 
template<typename Real >
static void UnitTestCuSparseMatrixSelectRowsAndTranspose ()
 
template<typename Real >
static void UnitTestCuSparseMatrixTraceMatSmat ()
 
template<typename Real >
static void UnitTestCuSparseMatrixSum ()
 
template<typename Real >
static void UnitTestCuSparseMatrixFrobeniusNorm ()
 
template<typename Real >
static void UnitTestCuSparseMatrixCopyToSmat ()
 
template<typename Real >
static void UnitTestCuSparseMatrixSwap ()
 
template<typename Real >
void CudaSparseMatrixUnitTest ()
 
template<typename Real >
Real TraceMatSmat (const CuMatrixBase< Real > &A, const CuSparseMatrix< Real > &B, MatrixTransposeType trans)
 
template float TraceMatSmat (const CuMatrixBase< float > &A, const CuSparseMatrix< float > &B, MatrixTransposeType trans)
 
template double TraceMatSmat (const CuMatrixBase< double > &A, const CuSparseMatrix< double > &B, MatrixTransposeType trans)
 
template<typename Real >
static void InitRand (SpMatrix< Real > *M)
 
template<typename Real >
static void InitRand (VectorBase< Real > *v)
 
template<typename Real >
static void UnitTestSetZeroAboveDiag ()
 
template<typename Real >
static void UnitTestCholesky ()
 
template<typename Real >
static void UnitTestTrace ()
 
template<typename Real >
static void UnitInvert ()
 
template<typename Real >
static void UnitTestInvert ()
 
template<typename Real >
static void UnitTestConstructor ()
 
template<typename Real >
static void UnitTestCopySp ()
 
template<typename Real >
static void UnitTestCopyFromMat ()
 
template<typename Real >
static void UnitTestMatrix ()
 
template<typename Real >
static void UnitTestMulTp ()
 
template<typename Real >
static void UnitTestVector ()
 
template<typename Real >
static void CuMatrixUnitTest ()
 
template<typename Real >
static void AssertEqual (const CuPackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
 
template<typename Real >
static void AssertEqual (const PackedMatrix< Real > &A, const PackedMatrix< Real > &B, float tol=0.001)
 
template<typename Real >
static void AssertEqual (const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
 
template<typename Real >
static void UnitTestCuTpMatrixInvert ()
 
template<typename Real >
static void UnitTestCuTpMatrixCopyFromTp ()
 
template<typename Real >
static void UnitTestCuTpMatrixCopyFromMat ()
 
template<typename Real >
static void UnitTestCuTpMatrixCholesky ()
 
template<class Real >
static void UnitTestCuTpMatrixIO ()
 
template<typename Real >
void CudaTpMatrixUnitTest ()
 
template<typename Real >
void TestCuVectorSoftmax (int32 dim)
 
template<typename Real >
void TestCuVectorSum (int32 dim)
 
template<typename Real , typename OtherReal >
void TestCuVectorCopyFromVec (int32 dim)
 
template<typename Real >
void TestCuVectorVecVecOne (int32 dim)
 
template<typename Real >
void TestCuVectorAddDiagMatMat (int32 dim, MatrixTransposeType transN, MatrixTransposeType transO)
 
template<typename Real >
void TestCuVectorAddDiagMat2OnVariousShapes (int32 dim, MatrixTransposeType trans)
 
template<typename Real >
void TestCuVectorAddDiagMat2 (int32 dim, MatrixTransposeType trans)
 
template<typename Real >
void TestCuVectorAddRowSumMat (int32 dim, MatrixTransposeType trans)
 
template<typename Real >
void TestCuVectorAddColSumMat (int32 dim, MatrixTransposeType trans)
 
template<typename Real >
void TestCuVectorApplyFloor (int32 dim)
 
template<typename Real >
void TestCuVectorApplyFloorNoCount (int32 dim)
 
template<typename Real >
void TestCuVectorApplyCeiling (int32 dim)
 
template<typename Real >
void TestCuVectorApplyCeilingNoCount (int32 dim)
 
template<typename Real >
void TestCuVectorAddDiagMatMatShape (int32 num_rows, int32 num_cols, MatrixTransposeType transM, MatrixTransposeType transN)
 
template<typename Real >
void CudaVectorSpeedTest ()
 
template<class Real >
static void UnitTestCuVectorIO ()
 
template<typename Real , typename OtherReal >
static void UnitTestCuVectorCopyFromVec ()
 
template<typename Real >
static void UnitTestCuSubVector ()
 
template<typename Real >
static void UnitTestCuVectorMulTp ()
 
template<typename Real >
static void UnitTestCuVectorAddTp ()
 
template<typename Real >
void CuVectorUnitTestVecVec ()
 
template<typename Real >
void CuVectorUnitTestAddVec ()
 
template<typename Real >
void CuVectorUnitTestAddVecCross ()
 
template<typename Real >
void CuVectorUnitTestAddVecExtra ()
 
template<typename Real >
void CuVectorUnitTestCopyElements ()
 
template<typename Real >
void UnitTestVecMatVec ()
 
template<typename Real >
void CuVectorUnitTestAddRowSumMat ()
 
template<typename Real >
void CuVectorUnitTestAddColSumMat ()
 
template<typename Real >
void CuVectorUnitTestApproxEqual ()
 
template<typename Real >
static void UnitTestCuVectorReplaceValue ()
 
template<typename Real >
static void UnitTestCuVectorSum ()
 
template<typename Real >
void CuVectorUnitTestInvertElements ()
 
template<typename Real >
void CuVectorUnitTestSum ()
 
template<typename Real >
void CuVectorUnitTestScale ()
 
template<typename Real >
void CuVectorUnitTestCopyFromMat ()
 
template<typename Real >
void CuVectorUnitTestCopyDiagFromPacked ()
 
template<typename Real >
void CuVectorUnitTestCopyCross ()
 
template<typename Real >
void CuVectorUnitTestCopyCross2 ()
 
template<typename Real >
void CuVectorUnitTestCopyDiagFromMat ()
 
template<typename Real >
void CuVectorUnitTestNorm ()
 
template<typename Real >
void CuVectorUnitTestMin ()
 
template<typename Real >
void CuVectorUnitTestMax ()
 
template<typename Real >
void CuVectorUnitTestApplySoftMax ()
 
template<typename Real >
void CuVectorUnitTestApplyExp ()
 
template<typename Real >
void CuVectorUnitTestApplyLog ()
 
template<typename Real >
void CuVectorUnitTestApplyFloor ()
 
template<typename Real >
void CuVectorUnitTestApplyFloorNoCount ()
 
template<typename Real >
void CuVectorUnitTestApplyCeiling ()
 
template<typename Real >
void CuVectorUnitTestApplyCeilingNoCount ()
 
template<typename Real >
void CuVectorUnitTestApplyPow ()
 
template<typename Real >
void CuVectorUnitTestAddVecVec ()
 
template<typename Real >
void CuVectorUnitTestAddDiagMat2 ()
 
template<typename Real >
static void CuVectorUnitTestAddDiagMatMat ()
 
template<typename Real >
void CuVectorUnitTestAddMatVec ()
 
template<typename Real >
void CuVectorUnitTestAddSpVec ()
 
template<typename Real >
void CuVectorUnitTest ()
 
template<typename Real >
Real VecVec (const CuVectorBase< Real > &a, const CuVectorBase< Real > &b)
 
template float VecVec (const CuVectorBase< float > &a, const CuVectorBase< float > &b)
 
template double VecVec (const CuVectorBase< double > &a, const CuVectorBase< double > &b)
 
template<typename Real , typename OtherReal >
Real VecVec (const CuVectorBase< Real > &A, const CuVectorBase< OtherReal > &B)
 
template float VecVec (const CuVectorBase< float > &A, const CuVectorBase< double > &B)
 
template double VecVec (const CuVectorBase< double > &A, const CuVectorBase< float > &B)
 
template<typename Real >
Real VecMatVec (const CuVectorBase< Real > &v1, const CuMatrixBase< Real > &M, const CuVectorBase< Real > &v2)
 Returns $ v_1^T M v_2 $ . More...
 
template float VecMatVec (const CuVectorBase< float > &v1, const CuMatrixBase< float > &M, const CuVectorBase< float > &v2)
 
template double VecMatVec (const CuVectorBase< double > &v1, const CuMatrixBase< double > &M, const CuVectorBase< double > &v2)
 
template<typename Real >
std::ostream & operator<< (std::ostream &out, const CuVectorBase< Real > &vec)
 Print the vector to stream. More...
 
template std::ostream & operator<< (std::ostream &out, const CuVectorBase< float > &vec)
 
template std::ostream & operator<< (std::ostream &out, const CuVectorBase< double > &vec)
 
template<typename Real >
bool ApproxEqual (const CuVectorBase< Real > &a, const CuVectorBase< Real > &b, Real tol=0.01)
 
template<typename Real >
void AssertEqual (const CuVectorBase< Real > &a, const CuVectorBase< Real > &b, Real tol=0.01)
 
void GetSeenPhones (BuildTreeStatsType &stats, int P, std::vector< int32 > *phones_out)
 
void AddToCount (int32 location_to_add, double value_to_add, std::vector< double > *counts)
 
void AddToConfusionMatrix (int32 phone1, int32 phone2, Matrix< double > *counts)
 
void WriteAsKaldiVector (const std::vector< double > &counts, std::string &wxfilename, bool binary)
 
int32 ProcessTopo (const HmmTopology &topo, const std::vector< std::vector< int32 > > &questions)
 
void FrameLevelLpp (const SubVector< BaseFloat > &prob_row, const std::vector< std::set< int32 > > &pdf2phones, const std::vector< int32 > *phone_map, Vector< BaseFloat > *out_frame_level_lpp)
 FrameLevelLpp compute a log posterior for pure-phones by sum the posterior of the states belonging to those triphones whose current phone is the canonical phone: More...
 
void GetEditsSingleHyp (const std::string &hyp_rspecifier, const std::string &ref_rspecifier, const std::string &mode, std::vector< std::pair< int32, int32 > > &edit_word_per_hyp)
 
void GetEditsDualHyp (const std::string &hyp_rspecifier, const std::string &hyp_rspecifier2, const std::string &ref_rspecifier, const std::string &mode, std::vector< std::pair< int32, int32 > > &edit_word_per_hyp, std::vector< std::pair< int32, int32 > > &edit_word_per_hyp2)
 
void GetBootstrapWERInterval (const std::vector< std::pair< int32, int32 > > &edit_word_per_hyp, int32 replications, BaseFloat *mean, BaseFloat *interval)
 
void GetBootstrapWERTwoSystemComparison (const std::vector< std::pair< int32, int32 > > &edit_word_per_hyp, const std::vector< std::pair< int32, int32 > > &edit_word_per_hyp2, int32 replications, BaseFloat *p_improv)
 
void ApplySoftMaxPerRow (MatrixBase< BaseFloat > *mat)
 
int32 TypeOneUsage (const ParseOptions &po, BaseFloat scale1, BaseFloat scale2)
 
int32 TypeOneUsageAverage (const ParseOptions &po)
 
int32 TypeTwoUsage (const ParseOptions &po, bool binary)
 
int32 TypeThreeUsage (const ParseOptions &po, bool binary, bool average)
 
int32 TypeOneUsage (const ParseOptions &po)
 
int32 TypeTwoUsage (const ParseOptions &po, bool binary, bool average=false)
 
int32 TypeThreeUsage (const ParseOptions &po, bool binary)
 
void AccumulateForUtterance (const Matrix< BaseFloat > &feats, const GaussPost &gpost, const TransitionModel &trans_model, const AmDiagGmm &am_gmm, FmllrDiagGmmAccs *spk_stats)
 
void AccumulateForUtterance (const Matrix< BaseFloat > &feats, const Posterior &post, const TransitionModel &trans_model, const AmDiagGmm &am_gmm, FmllrDiagGmmAccs *spk_stats)
 
fst::Fst< fst::StdArc > * ReadNetwork (std::string filename)
 
void AccStatsForUtterance (const TransitionModel &trans_model, const AmDiagGmm &am_gmm, const GaussPost &gpost, const Matrix< BaseFloat > &feats, FmllrRawAccs *accs)
 
void AccStatsForUtterance (const TransitionModel &trans_model, const AmDiagGmm &am_gmm, const Posterior &post, const Matrix< BaseFloat > &feats, FmllrRawAccs *accs)
 
void AccumulateForUtterance (const Matrix< BaseFloat > &feats, const GaussPost &gpost, const AmDiagGmm &am_gmm, FmllrDiagGmmAccs *spk_stats)
 
bool AccumulateForUtterance (const Matrix< BaseFloat > &feats, const DiagGmm &gmm, const std::string &key, RandomAccessBaseFloatVectorReader *weights_reader, RandomAccessInt32VectorVectorReader *gselect_reader, AccumFullGmm *fullcov_stats)
 
void AccumulateForUtterance (const Matrix< BaseFloat > &feats, const Posterior &post, const DiagGmm &gmm, FmllrDiagGmmAccs *spk_stats)
 
void InitGmmFromRandomFrames (const Matrix< BaseFloat > &feats, DiagGmm *gmm)
 
void TrainOneIter (const Matrix< BaseFloat > &feats, const MleDiagGmmOptions &gmm_opts, int32 iter, int32 num_threads, DiagGmm *gmm)
 
void ReadSharedPhonesList (std::string rxfilename, std::vector< std::vector< int32 > > *list_out)
 
EventMapGetFullBiphoneStubMap (const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< int32 > &ci_phones_list, const std::vector< std::vector< int32 > > &bi_counts, int32 biphone_min_count, const std::vector< int32 > &mono_counts, int32 mono_min_count)
 
ContextDependencyBiphoneContextDependencyFull (std::vector< std::vector< int32 > > phone_sets, const std::vector< int32 > phone2num_pdf_classes, const std::vector< int32 > &ci_phones_list, const std::vector< std::vector< int32 > > &bi_counts, int32 biphone_min_count, const std::vector< int32 > &mono_counts, int32 mono_min_count)
 
void GetFeatureMeanAndVariance (const std::string &feat_rspecifier, Vector< BaseFloat > *inv_var_out, Vector< BaseFloat > *mean_out)
 
void InitAmGmm (const BuildTreeStatsType &stats, const EventMap &to_pdf_map, AmDiagGmm *am_gmm, const TransitionModel &trans_model, BaseFloat var_floor)
 InitAmGmm initializes the GMM with one Gaussian per state. More...
 
void GetOccs (const BuildTreeStatsType &stats, const EventMap &to_pdf_map, Vector< BaseFloat > *occs)
 Get state occupation counts. More...
 
void InitAmGmmFromOld (const BuildTreeStatsType &stats, const EventMap &to_pdf_map, int32 N, int32 P, const std::string &old_tree_rxfilename, const std::string &old_model_rxfilename, BaseFloat var_floor, AmDiagGmm *am_gmm)
 InitAmGmmFromOld initializes the GMM based on a previously trained model and tree, which must require no more phonetic context than the current tree. More...
 
bool DecodeUtterance (LatticeBiglmFasterDecoder &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 
void MergeFullGmm (const FullGmm &src, FullGmm *dst)
 merges GMMs by appending Gaussians in "src" to "dst". More...
 
void AppendPostToFeats (const Matrix< BaseFloat > &in, const Posterior &post, const int32 post_dim, Matrix< BaseFloat > *out)
 
void AppendVectorToFeats (const Matrix< BaseFloat > &in, const Vector< BaseFloat > &vec, Matrix< BaseFloat > *out)
 
void GetUtterancePairs (const std::string &reco2file_and_channel_rxfilename, std::vector< std::vector< std::string > > *utt_pairs)
 
void AccCmvnStatsForPair (const std::string &utt1, const std::string &utt2, const MatrixBase< BaseFloat > &feats1, const MatrixBase< BaseFloat > &feats2, BaseFloat quieter_channel_weight, MatrixBase< double > *cmvn_stats1, MatrixBase< double > *cmvn_stats2)
 
bool AccCmvnStatsWrapper (const std::string &utt, const MatrixBase< BaseFloat > &feats, RandomAccessBaseFloatVectorReader *weights_reader, Matrix< double > *cmvn_stats)
 
void ConcatFeats (const std::vector< Matrix< BaseFloat > > &in, Matrix< BaseFloat > *out)
 
void IncreaseTransformDimension (int32 new_dimension, Matrix< BaseFloat > *mat)
 
void LinearlyInterpolatePitch (Matrix< BaseFloat > *mat)
 
bool AppendFeats (const std::vector< Matrix< BaseFloat > > &in, const std::string &utt, int32 tolerance, Matrix< BaseFloat > *out)
 
void ProcessPovFeatures (Matrix< BaseFloat > *mat)
 
void TakeLogOfPitch (Matrix< BaseFloat > *mat)
 
void SubtractMovingAverage (int32 normalization_window_size, Matrix< BaseFloat > *mat)
 
void SetToMovingAverage (int32 average_window_size, Matrix< BaseFloat > *mat)
 
void ShiftFeatureMatrix (const Matrix< BaseFloat > &src, int32 shift, Matrix< BaseFloat > *rearranged)
 
void AddVectorsOfUnequalLength (const VectorBase< BaseFloat > &signal1, Vector< BaseFloat > *signal2)
 
void AddVectorsWithOffset (const Vector< BaseFloat > &signal1, int32 offset, Vector< BaseFloat > *signal2)
 
BaseFloat MaxAbsolute (const Vector< BaseFloat > &vector)
 
BaseFloat ComputeEarlyReverbEnergy (const Vector< BaseFloat > &rir, const Vector< BaseFloat > &signal, BaseFloat samp_freq)
 
float DoReverberation (const Vector< BaseFloat > &rir, BaseFloat samp_freq, Vector< BaseFloat > *signal)
 
void AddNoise (Vector< BaseFloat > *noise, BaseFloat snr_db, BaseFloat time, BaseFloat samp_freq, BaseFloat signal_power, Vector< BaseFloat > *signal)
 
void ReadCommaSeparatedCommand (const std::string &s, std::vector< BaseFloat > *v)
 
bool ReadData (SequentialBaseFloatMatrixReader &feature_reader, RandomAccessPosteriorReader &target_reader, RandomAccessBaseFloatVectorReader &weights_reader, int32 length_tolerance, Matrix< BaseFloat > *feats, Posterior *targets, Vector< BaseFloat > *weights, int32 *num_no_tgt_mat, int32 *num_other_error)
 
bool CompactLatticeNormalize (CompactLattice *clat, BaseFloat weight)
 
void SplitStringToWeights (const string &full, const char *delim, vector< BaseFloat > *out)
 
int32 CopySubsetLattices (std::string filename, SequentialLatticeReader *lattice_reader, LatticeWriter *lattice_writer, bool include=true, bool ignore_missing=false, bool sorted=false)
 
int32 CopySubsetLattices (std::string filename, SequentialCompactLatticeReader *lattice_reader, CompactLatticeWriter *lattice_writer, bool include=true, bool ignore_missing=false, bool sorted=false)
 
bool DeterminizeLatticeWrapper (const Lattice &lat, const std::string &key, bool prune, BaseFloat beam, BaseFloat beam_ratio, int32 max_mem, int32 max_loop, BaseFloat delta, int32 num_loops, CompactLattice *clat)
 
void ReadSymbolList (const std::string &rxfilename, fst::SymbolTable *word_syms, LabelPairVector *lpairs)
 
void ConvertLatticeToUnweightedAcceptor (const kaldi::Lattice &ilat, const LabelPairVector &wildcards, fst::StdVectorFst *ofst)
 
void CreateEditDistance (const fst::StdVectorFst &fst1, const fst::StdVectorFst &fst2, fst::StdVectorFst *pfst)
 
void CountErrors (const fst::StdVectorFst &fst, int32 *correct, int32 *substitutions, int32 *insertions, int32 *deletions, int32 *num_words)
 
bool CheckFst (const fst::StdVectorFst &fst, string name, string key)
 
void LatticeAcousticRescore (const TransitionModel &trans_model, const Matrix< BaseFloat > &log_likes, const std::vector< int32 > &state_times, Lattice *lat)
 
void MakeLatticeFromLinear (const std::vector< int32 > &ali, const std::vector< int32 > &words, BaseFloat lm_cost, BaseFloat ac_cost, Lattice *lat_out)
 
static float _RandGauss ()
 
void ComputeFeatureNormalizingTransform (const FullGmm &gmm, Matrix< BaseFloat > *xform)
 Computes the inverse of an LDA transform (without dimensionality reduction) The computed transform is used in initializing the phonetic and speaker subspaces, as well as while increasing the dimensions of those spaces. More...
 
static void ApplyPreXformToGradient (const Sgmm2FmllrGlobalParams &globals, const Matrix< BaseFloat > &gradient_in, Matrix< BaseFloat > *gradient_out)
 
static void ApplyInvPreXformToChange (const Sgmm2FmllrGlobalParams &globals, const Matrix< BaseFloat > &delta_in, Matrix< BaseFloat > *delta_out)
 
static void ApplyHessianXformToGradient (const Sgmm2FmllrGlobalParams &globals, const Matrix< BaseFloat > &gradient_in, Matrix< BaseFloat > *gradient_out)
 
static void ApplyInvHessianXformToChange (const Sgmm2FmllrGlobalParams &globals, const Matrix< BaseFloat > &delta_in, Matrix< BaseFloat > *delta_out)
 
static BaseFloat CalcFmllrStepSize (const AffineXformStats &stats, const AmSgmm2 &sgmm, const MatrixBase< BaseFloat > &Delta, const MatrixBase< BaseFloat > &A, const Matrix< BaseFloat > &G, int32 max_iters)
 
void EstimateSgmm2FmllrSubspace (const SpMatrix< double > &fmllr_grad_scatter, int32 num_fmllr_bases, int32 feat_dim, Sgmm2FmllrGlobalParams *fmllr_globals, double min_eig=0.0)
 Computes the fMLLR basis matrices given the scatter of the vectorized gradients (eq: B.10). More...
 
void AccumulateForUtterance (const Matrix< BaseFloat > &feats, const Matrix< BaseFloat > &transformed_feats, const std::vector< std::vector< int32 > > &gselect, const Posterior &post, const TransitionModel &trans_model, const AmSgmm2 &am_sgmm, BaseFloat logdet, Sgmm2PerSpkDerivedVars *spk_vars, FmllrSgmm2Accs *spk_stats)
 
void AccumulateForUtterance (const Matrix< BaseFloat > &feats, const Sgmm2GauPost &gpost, const TransitionModel &trans_model, const AmSgmm2 &am_sgmm, Sgmm2PerSpkDerivedVars *spk_vars, MleSgmm2SpeakerAccs *spk_stats)
 
void AccumulateForUtterance (const Matrix< BaseFloat > &feats, const Posterior &post, const TransitionModel &trans_model, const AmSgmm2 &am_sgmm, const vector< vector< int32 > > &gselect, Sgmm2PerSpkDerivedVars *spk_vars, MleSgmm2SpeakerAccs *spk_stats)
 
void ProcessUtterance (const AmSgmm2 &am_sgmm, const TransitionModel &trans_model, double log_prune, double acoustic_scale, const Matrix< BaseFloat > &features, RandomAccessInt32VectorVectorReader &gselect_reader, RandomAccessBaseFloatVectorReaderMapped &spkvecs_reader, const fst::SymbolTable *word_syms, const std::string &utt, bool determinize, bool allow_partial, Int32VectorWriter *alignments_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, LatticeFasterDecoder *decoder, double *like_sum, int64 *frame_sum, int32 *num_done, int32 *num_err, TaskSequencer< DecodeUtteranceLatticeFasterClass > *sequencer)
 
bool ProcessUtterance (LatticeFasterDecoder &decoder, const AmSgmm2 &am_sgmm, const TransitionModel &trans_model, double log_prune, double acoustic_scale, const Matrix< BaseFloat > &features, RandomAccessInt32VectorVectorReader &gselect_reader, RandomAccessBaseFloatVectorReaderMapped &spkvecs_reader, const fst::SymbolTable *word_syms, const std::string &utt, bool determinize, bool allow_partial, Int32VectorWriter *alignments_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
 
void GetWeights (const std::string &weights_str, int32 num_inputs, std::vector< BaseFloat > *weights)
 
std::vector< boolGetSkipLayers (const std::string &skip_layers_str, const int32 first_layer_idx, const int32 last_layer_idx)
 
bool SplitEgsKey (const std::string &key, std::string *utt_id, int32 *frame_id)
 
nnet2::ComponentConvertAffineTransformComponent (const nnet1::Component &nnet1_component, const bool use_preconditioned_affine_component)
 
nnet2::ComponentConvertSoftmaxComponent (const nnet1::Component &nnet1_component)
 
nnet2::ComponentConvertSigmoidComponent (const nnet1::Component &nnet1_component)
 
nnet2::ComponentConvertSpliceComponent (const nnet1::Component &nnet1_component)
 
nnet2::ComponentConvertAddShiftComponent (const nnet1::Component &nnet1_component)
 
nnet2::ComponentConvertRescaleComponent (const nnet1::Component &nnet1_component)
 
nnet2::ComponentConvertComponent (const nnet1::Component &nnet1_component, const bool use_preconditioned_affine_component)
 
nnet2::NnetConvertNnet1ToNnet2 (const nnet1::Nnet &nnet1, const bool use_preconditioned_affine_component)
 
void ReadModels (std::vector< std::pair< std::string, BaseFloat > > models_and_weights, nnet3::Nnet *output_nnet, int32 *success)
 
int32 GetCount (double expected_count)
 
void SplitArgOnEquals (const std::string &arg, std::string *name, std::string *rspecifier)
 
void HandleOutput (bool determinize, const fst::SymbolTable *word_syms, nnet3::NnetBatchDecoder *decoder, CompactLatticeWriter *clat_writer, LatticeWriter *lat_writer)
 
bool CompareInterval (const Interval &i1, const Interval &i2)
 
bool ClusterLattice (CompactLattice *clat, const std::vector< int32 > &state_times)
 
bool CreateFactorTransducer (const CompactLattice &clat, const std::vector< int32 > &state_times, int32 utterance_id, KwsProductFst *factor_transducer)
 
void RemoveLongSilences (int32 max_silence_frames, const std::vector< int32 > &state_times, KwsProductFst *factor_transducer)
 
template<class Arc >
static void DifferenceWrapper (const fst::VectorFst< Arc > &fst1, const fst::VectorFst< Arc > &fst2, fst::VectorFst< Arc > *difference)
 
void MaybeDoSanityCheck (const KwsLexicographicFst &index_transducer)
 
void MaybeDoSanityCheck (const KwsProductFst &product_transducer)
 
void DoFactorMerging (KwsProductFst *factor_transducer, KwsLexicographicFst *index_transducer)
 
void DoFactorDisambiguation (KwsLexicographicFst *index_transducer)
 
void OptimizeFactorTransducer (KwsLexicographicFst *index_transducer, int32 max_states, bool allow_partial)
 
template<class Arc >
static void ReplaceSymbolWithEpsilon (typename Arc::Label symbol, fst::VectorFst< Arc > *fst)
 
uint64 EncodeLabel (StateId ilabel, StateId olabel)
 
StateId DecodeLabelUid (uint64 osymbol)
 
bool GenerateActivePaths (const KwsLexicographicFst &proxy, std::vector< ActivePath > *paths, KwsLexicographicFst::StateId cur_state, std::vector< KwsLexicographicArc::Label > cur_path, KwsLexicographicArc::Weight cur_weight)
 
void SetLinearAcceptorWeight (double cost, fst::VectorFst< fst::StdArc > *fst)
 
void AgglomerativeCluster (const Matrix< BaseFloat > &costs, BaseFloat threshold, int32 min_clusters, int32 first_pass_max_points, BaseFloat max_cluster_fraction, std::vector< int32 > *assignments_out)
 This is the function that is called to perform the agglomerative clustering. More...
 
void TestIvectorExtractorIO (const IvectorExtractor &extractor)
 
void TestIvectorExtractorStatsIO (IvectorExtractorStats &stats)
 
void TestIvectorExtraction (const IvectorExtractor &extractor, const MatrixBase< BaseFloat > &feats, const FullGmm &fgmm)
 
void UnitTestIvectorExtractor ()
 
static double GetLogDetNoFailure (const SpMatrix< double > &var)
 
static void ConvertPostToGaussInfo (const std::vector< std::vector< std::pair< int32, BaseFloat > > > &gauss_post, std::unordered_map< int32, GaussInfo > *gauss_info)
 
double EstimateIvectorsOnline (const Matrix< BaseFloat > &feats, const Posterior &post, const IvectorExtractor &extractor, int32 ivector_period, int32 num_cg_iters, BaseFloat max_count, Matrix< BaseFloat > *ivectors)
 
void UnitTestPosteriors ()
 
void UnitTestTrain ()
 
void UnitTestPldaEstimation (int32 dim)
 
template<class Real >
static void ComputeNormalizingTransform (const SpMatrix< Real > &covar, MatrixBase< Real > *proj)
 This function computes a projection matrix that when applied makes the covariance unit (i.e. More...
 
void ComputeVadEnergy (const VadEnergyOptions &opts, const MatrixBase< BaseFloat > &input_features, Vector< BaseFloat > *output_voiced)
 Compute voice-activity vector for a file: 1 if we judge the frame as voiced, 0 otherwise. More...
 
BaseFloat ComputeEer (std::vector< BaseFloat > *target_scores, std::vector< BaseFloat > *nontarget_scores, BaseFloat *threshold)
 ComputeEer computes the Equal Error Rate (EER) for the given scores and returns it as a proportion beween 0 and 1. More...
 
void PrepareMap (const std::string &map_rxfilename, int32 num_classes, unordered_map< int32, int32 > *map)
 PrepareMap creates a map that specifies the mapping between the input and output class labels. More...
 
void PreparePriors (const std::string &priors_str, int32 num_classes, std::vector< BaseFloat > *priors)
 PreparePriors creates a table specifying the priors for each class. More...
 
template<class Real >
void ComputeNormalizingTransform (const SpMatrix< Real > &covar, Real floor, MatrixBase< Real > *proj)
 
void ComputeLdaTransform (const std::map< std::string, Vector< BaseFloat > *> &utt2ivector, const std::map< std::string, std::vector< std::string > > &spk2utt, BaseFloat total_covariance_factor, BaseFloat covariance_floor, MatrixBase< BaseFloat > *lda_out)
 
void ComputeAndSubtractMean (std::map< std::string, Vector< BaseFloat > *> utt2ivector, Vector< BaseFloat > *mean_out)
 
int32 RunPerSpeaker (const std::string &ivector_extractor_rxfilename, const IvectorEstimationOptions &opts, bool compute_objf_change, const std::string &spk2utt_rspecifier, const std::string &feature_rspecifier, const std::string &posterior_rspecifier, const std::string &ivector_wspecifier)
 
bool EstPca (const Matrix< BaseFloat > &ivector_mat, BaseFloat target_energy, const std::string &reco, Matrix< BaseFloat > *mat)
 
void TransformIvectors (const Matrix< BaseFloat > &ivectors_in, const PldaConfig &plda_config, const Plda &plda, Matrix< BaseFloat > *ivectors_out)
 
void ApplyPca (const Matrix< BaseFloat > &ivectors_in, const Matrix< BaseFloat > &pca_mat, Matrix< BaseFloat > *ivectors_out)
 
void PrepareMap (const std::string map_rxfilename, unordered_map< std::pair< int32, int32 >, int32, PairHasher< int32 > > *map)
 PrepareMap creates a mapping between the pairs of VAD decisions and the output label. More...
 
int PaCallback (const void *input, void *output, long unsigned frame_count, const PaStreamCallbackTimeInfo *time_info, PaStreamCallbackFlags status_flags, void *user_data)
 
template<class Real >
static void AssertEqual (const Matrix< Real > &A, const Matrix< Real > &B, float tol=0.001)
 
void GetOutput (OnlineFeatInputItf *a, Matrix< BaseFloat > *output)
 
void TestOnlineMatrixInput ()
 
void TestOnlineFeatureMatrix ()
 
void TestOnlineLdaInput ()
 
void TestOnlineDeltaInput ()
 
void TestOnlineCmnInput ()
 
fst::Fst< fst::StdArc > * ReadDecodeGraph (const std::string &filename)
 
void PrintPartialResult (const std::vector< int32 > &words, const fst::SymbolTable *word_syms, bool line_break)
 
bool WriteFull (int32 desc, char *data, int32 size)
 
bool ReadLine (int32 desc, std::string *str)
 
std::string TimeToTimecode (float time)
 
bool WriteLine (int32 socket, std::string line)
 
void SendPartialResult (const std::vector< int32 > &words, const fst::SymbolTable *word_syms, const bool line_break, const int32 serv_sock, const sockaddr_in &client_addr)
 
static bool RuleActivated (const OnlineEndpointRule &rule, const std::string &rule_name, BaseFloat trailing_silence, BaseFloat relative_cost, BaseFloat utterance_length)
 
bool EndpointDetected (const OnlineEndpointConfig &config, int32 num_frames_decoded, int32 trailing_silence_frames, BaseFloat frame_shift_in_seconds, BaseFloat final_relative_cost)
 This function returns true if this set of endpointing rules thinks we should terminate decoding. More...
 
template<typename FST , typename DEC >
int32 TrailingSilenceLength (const TransitionModel &tmodel, const std::string &silence_phones, const DEC &decoder)
 returns the number of frames of trailing silence in the best-path traceback (not using final-probs). More...
 
template<typename FST >
bool EndpointDetected (const OnlineEndpointConfig &config, const TransitionModel &tmodel, BaseFloat frame_shift_in_seconds, const LatticeFasterOnlineDecoderTpl< FST > &decoder)
 This is a higher-level convenience function that works out the arguments to the EndpointDetected function above, from the decoder. More...
 
template<typename FST >
bool EndpointDetected (const OnlineEndpointConfig &config, const TransitionModel &tmodel, BaseFloat frame_shift_in_seconds, const LatticeIncrementalOnlineDecoderTpl< FST > &decoder)
 This is a higher-level convenience function that works out the arguments to the EndpointDetected function above, from the decoder. More...
 
template bool EndpointDetected< fst::Fst< fst::StdArc > > (const OnlineEndpointConfig &config, const TransitionModel &tmodel, BaseFloat frame_shift_in_seconds, const LatticeFasterOnlineDecoderTpl< fst::Fst< fst::StdArc > > &decoder)
 
template bool EndpointDetected< fst::GrammarFst > (const OnlineEndpointConfig &config, const TransitionModel &tmodel, BaseFloat frame_shift_in_seconds, const LatticeFasterOnlineDecoderTpl< fst::GrammarFst > &decoder)
 
template bool EndpointDetected< fst::Fst< fst::StdArc > > (const OnlineEndpointConfig &config, const TransitionModel &tmodel, BaseFloat frame_shift_in_seconds, const LatticeIncrementalOnlineDecoderTpl< fst::Fst< fst::StdArc > > &decoder)
 
template bool EndpointDetected< fst::GrammarFst > (const OnlineEndpointConfig &config, const TransitionModel &tmodel, BaseFloat frame_shift_in_seconds, const LatticeIncrementalOnlineDecoderTpl< fst::GrammarFst > &decoder)
 
template void OnlineSilenceWeighting::ComputeCurrentTraceback< fst::Fst< fst::StdArc > > (const LatticeFasterOnlineDecoderTpl< fst::Fst< fst::StdArc > > &decoder)
 
template void OnlineSilenceWeighting::ComputeCurrentTraceback< fst::GrammarFst > (const LatticeFasterOnlineDecoderTpl< fst::GrammarFst > &decoder)
 
template void OnlineSilenceWeighting::ComputeCurrentTraceback< fst::Fst< fst::StdArc > > (const LatticeIncrementalOnlineDecoderTpl< fst::Fst< fst::StdArc > > &decoder)
 
template void OnlineSilenceWeighting::ComputeCurrentTraceback< fst::GrammarFst > (const LatticeIncrementalOnlineDecoderTpl< fst::GrammarFst > &decoder)
 
void FindQuietestSegment (const Vector< BaseFloat > &wav_in, BaseFloat samp_rate, Vector< BaseFloat > *wav_sil, BaseFloat search_dur=0.5, BaseFloat seg_dur=0.1, BaseFloat seg_shift_dur=0.05)
 
void ExtendWaveWithSilence (const Vector< BaseFloat > &wav_in, BaseFloat samp_rate, Vector< BaseFloat > *wav_out, BaseFloat sil_search_len, BaseFloat sil_extract_len, BaseFloat sil_extract_shift)
 
std::string LatticeToString (const Lattice &lat, const fst::SymbolTable &word_syms)
 
std::string GetTimeString (int32 t_beg, int32 t_end, BaseFloat time_unit)
 
int32 GetLatticeTimeSpan (const Lattice &lat)
 
std::string LatticeToString (const CompactLattice &clat, const fst::SymbolTable &word_syms)
 
void GetDiagnosticsAndPrintOutput (const std::string &utt, const fst::SymbolTable *word_syms, const CompactLattice &clat, int64 *tot_num_frames, double *tot_like)
 
template<typename Real >
Real TraceMatMat (const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans=kNoTrans)
 We need to declare this here as it will be a friend function. More...
 
void AccumulateTreeStats (const TransitionModel &trans_model, const AccumulateTreeStatsInfo &info, const std::vector< int32 > &alignment, const Matrix< BaseFloat > &features, std::map< EventType, GaussClusterable * > *stats)
 Accumulates the stats needed for training context-dependency trees (in the "normal" way). More...
 
void ReadPhoneMap (std::string phone_map_rxfilename, std::vector< int32 > *phone_map)
 

Variables

int32 g_kaldi_verbose_level = 0
 This is set by util/parse-options. More...
 
static std::string program_name
 
static LogHandler log_handler = NULL
 
static std::mutex _RandMutex
 
static const double kMinLogDiffDouble = Log(DBL_EPSILON)
 
static const float kMinLogDiffFloat = Log(FLT_EPSILON)
 
const float kLogZeroFloat = -std::numeric_limits<float>::infinity()
 
const double kLogZeroDouble = -std::numeric_limits<double>::infinity()
 
const BaseFloat kLogZeroBaseFloat = -std::numeric_limits<BaseFloat>::infinity()
 
ProfileStats g_profile_stats
 
int32 g_num_threads = 8
 
static ShellType kShellType = kBash
 
const char * ws_delim = " \t\n\r"
 
bool pitch_use_naive_search = false
 
const BaseFloat kWaveSampleMax = 32768.0
 For historical reasons, we scale waveforms to the range (2^15-1)*[-1, 1], not the usual default DSP range [-1, 1]. More...
 
static const EventKeyType kPdfClass = -1
 
const int32 kMaxVal = 20
 
static const int32 kNoPdf = -1
 A constant used in the HmmTopology class as the pdf-class kNoPdf, which is used when a HMM-state is nonemitting (has no associated PDF). More...
 
static const int kRandomSentences = 50
 
const int kTemporaryEpsilon = -2
 
const int kNumStatesOffset = 1000
 
CuAllocatorOptions g_allocator_options
 
int32 buffer_offset = 0
 
int32 buffer_fill = 0
 
char read_buffer [1025]
 
const float kFramesPerSecond = 100.0f
 

Detailed Description

This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for mispronunciations detection tasks, the reference:

Relabels neural network egs with the read pdf-id alignments.

"Improved mispronunciation detection with deep neural network trained acoustic models and transfer learning based logistic regression classifiers" by Hu et al., Speech Comunication, 2015.

GOP is widely used to detect mispronunciations. The DNN-based GOP was defined as the log phone posterior ratio between the canonical phone and the one with the highest score.

To compute GOP, we need to compute Log Phone Posterior (LPP): LPP(p) = p(p| o; t_s,t_e) where { o} is the input observations, p is the canonical phone, {t_s, t_e} are the start and end frame indexes.

LPP could be calculated as the average of the frame-level LPP, i.e. p(p|o_t): LPP(p) = {1}{t_e-t_s+1} {t=t_s}^{t_e} p(p|o_t) p(p|o_t) = {s p} p(s|o_t) where s is the senone label, {s|s p} is the states belonging to those triphones whose current phone is p.

GOP is extracted from LPP: GOP(p) = {LPP(p)}{{q Q} LPP(q)}

An array of a phone-level feature for each phone is extracted as well, which could be used to train a classifier to detect mispronunciations. Normally the classifier-based approach archives better performance than the GOP-based approach.

The phone-level feature is defined as: {[LPP(p_1),,LPP(p_M), LPR(p_1|p_i), , LPR(p_j|p_i),]}^T

where the Log Posterior Ratio (LPR) between phone p_j and p_i is defined as: LPR(p_j|p_i) = p(p_j| o; t_s, t_e) - p(p_i| o; t_s, t_e)

Typedef Documentation

◆ Arc

Definition at line 35 of file lattice-determinize-non-compact.cc.

◆ BaseFloat

typedef float BaseFloat

Definition at line 29 of file kaldi-types.h.

◆ CompactLattice

typedef fst::VectorFst<CompactLatticeArc> CompactLattice

Definition at line 46 of file kaldi-lattice.h.

◆ CompactLatticeArc

Definition at line 42 of file kaldi-lattice.h.

◆ CompactLatticeWeight

◆ CompactLatticeWeightCommonDivisor

◆ CompactLatticeWriter

◆ double64

typedef double double64

Definition at line 54 of file kaldi-types.h.

◆ EventAnswerType

As far as the event-map code itself is concerned, things of type EventAnswerType may take any value except kNoAnswer (== -1).

However, some specific uses of EventMap (e.g. in build-tree-utils.h) assume these quantities are nonnegative.

Definition at line 56 of file event-map.h.

◆ EventKeyType

Things of type EventKeyType can take any value.

The code does not assume they are contiguous. So values like -1, 1000000 and the like are acceptable.

Definition at line 45 of file event-map.h.

◆ EventType

typedef std::vector<std::pair<EventKeyType, EventValueType> > EventType

Definition at line 58 of file event-map.h.

◆ EventValueType

Given current code, things of type EventValueType should generally be nonnegative and in a reasonably small range (e.g.

not one million), as we sometimes construct vectors of the size: [largest value we saw for this key]. This deficiency may be fixed in future [would require modifying TableEventMap]

Definition at line 51 of file event-map.h.

◆ float32

typedef float float32

Definition at line 53 of file kaldi-types.h.

◆ GmmFlagsType

typedef uint16 GmmFlagsType

Bitwise OR of the above flags.

Definition at line 35 of file model-common.h.

◆ int32

Definition at line 27 of file online-tcp-source.cc.

◆ int_smaller

typedef int16 int_smaller

Definition at line 33 of file cluster-utils.cc.

◆ KwsLexicographicArc

Definition at line 45 of file kaldi-kws.h.

◆ KwsLexicographicFst

typedef fst::VectorFst<KwsLexicographicArc> KwsLexicographicFst

Definition at line 46 of file kaldi-kws.h.

◆ KwsLexicographicWeight

Definition at line 44 of file kaldi-kws.h.

◆ KwsProductArc

Definition at line 48 of file kaldi-kws.h.

◆ KwsProductFst

typedef fst::VectorFst<KwsProductArc> KwsProductFst

Definition at line 49 of file kaldi-kws.h.

◆ KwsProductWeight

Definition at line 47 of file kaldi-kws.h.

◆ Label

typedef fst::StdArc::Label Label

Definition at line 32 of file lattice-oracle.cc.

◆ LabelPairVector

typedef std::vector<std::pair<Label, Label> > LabelPairVector

Definition at line 33 of file lattice-oracle.cc.

◆ Lattice

typedef fst::VectorFst<LatticeArc> Lattice

Definition at line 44 of file kaldi-lattice.h.

◆ LatticeArc

typedef fst::ArcTpl<LatticeWeight> LatticeArc

Definition at line 40 of file kaldi-lattice.h.

◆ LatticeBiglmFasterDecoderConfig

◆ LatticeFasterDecoder

◆ LatticeFasterOnlineDecoder

◆ LatticeIncrementalDecoder

◆ LatticeIncrementalOnlineDecoder

◆ LatticeWeight

Definition at line 32 of file kaldi-lattice.h.

◆ LatticeWriter

Definition at line 145 of file kaldi-lattice.h.

◆ LogXStdXStdprimeArc

Definition at line 41 of file kaldi-kws.h.

◆ LogXStdXStdprimeWeight

typedef fst::ProductWeight<LogWeight, StdXStdprimeWeight> LogXStdXStdprimeWeight

Definition at line 40 of file kaldi-kws.h.

◆ MapAmDiagGmmSeqReader

◆ MapAmDiagGmmWriter

◆ MatrixIndexT

Definition at line 98 of file matrix-common.h.

◆ PipebufType

typedef basic_pipebuf<char> PipebufType

Definition at line 55 of file kaldi-io.cc.

◆ RandomAccessCompactLatticeReader

◆ RandomAccessLatticeReader

◆ RandomAccessMapAmDiagGmmReader

◆ RandomAccessMapAmDiagGmmReaderMapped

◆ RandomAccessRegtreeFmllrDiagGmmReader

◆ RandomAccessRegtreeFmllrDiagGmmReaderMapped

◆ RandomAccessRegtreeMllrDiagGmmReader

◆ RandomAccessRegtreeMllrDiagGmmReaderMapped

◆ RandomAccessSgmm2GauPostReader

◆ RegtreeFmllrDiagGmmSeqReader

◆ RegtreeFmllrDiagGmmWriter

◆ RegtreeMllrDiagGmmSeqReader

◆ RegtreeMllrDiagGmmWriter

◆ SequentialCompactLatticeReader

◆ SequentialLatticeReader

◆ SequentialSgmm2GauPostReader

◆ Sgmm2GauPostHolder

Definition at line 578 of file am-sgmm2.h.

◆ Sgmm2GauPostWriter

Definition at line 581 of file am-sgmm2.h.

◆ SgmmUpdateFlagsType

typedef uint16 SgmmUpdateFlagsType

Bitwise OR of the above flags.

Definition at line 59 of file model-common.h.

◆ SgmmWriteFlagsType

typedef uint16 SgmmWriteFlagsType

Bitwise OR of the above flags.

Definition at line 70 of file model-common.h.

◆ SignedMatrixIndexT

Definition at line 99 of file matrix-common.h.

◆ StateId

typedef Arc::StateId StateId

Definition at line 34 of file lattice-determinize-non-compact.cc.

◆ StdLStdLStdArc

typedef fst::ArcTpl<StdLStdLStdWeight> StdLStdLStdArc

Definition at line 36 of file kaldi-kws.h.

◆ StdLStdLStdWeight

typedef fst::LexicographicWeight<TropicalWeight, StdLStdWeight> StdLStdLStdWeight

Definition at line 35 of file kaldi-kws.h.

◆ StdLStdWeight

typedef fst::LexicographicWeight<TropicalWeight, TropicalWeight> StdLStdWeight

Definition at line 34 of file kaldi-kws.h.

◆ StdXStdprimeWeight

typedef fst::ProductWeight<TropicalWeight, ArcticWeight> StdXStdprimeWeight

Definition at line 39 of file kaldi-kws.h.

◆ uint_smaller

typedef uint16 uint_smaller

Definition at line 32 of file cluster-utils.cc.

◆ UnsignedMatrixIndexT

typedef uint32 UnsignedMatrixIndexT

Definition at line 100 of file matrix-common.h.

◆ Weight

typedef Arc::Weight Weight

Definition at line 31 of file kws-search.cc.

Enumeration Type Documentation

◆ anonymous enum

anonymous enum
Enumerator
kEps 
kDisambig 
kBos 
kEos 

Definition at line 33 of file arpa-lm-compiler-test.cc.

◆ cova_type

enum cova_type

Generate features for a certain covariance type covariance_type == 0: full covariance covariance_type == 1: diagonal covariance.

Enumerator
full 
diag 

Definition at line 58 of file regtree-fmllr-diag-gmm-test.cc.

◆ CuCompressedMatrixType

Enumerator
kCompressedMatrixInt8 
kCompressedMatrixUint8 
kCompressedMatrixInt16 
kCompressedMatrixUint16 

Definition at line 140 of file cu-compressed-matrix.h.

◆ DetectionDecision

Enumerator
kKwsFalseAlarm 
kKwsMiss 
kKwsCorr 
kKwsCorrUndetected 
kKwsUnseen 

Definition at line 81 of file kws-scoring.h.

81  {
82  kKwsFalseAlarm, // Marked incorrectly as a hit
83  kKwsMiss, // Not marked as hit while it should be
84  kKwsCorr, // Marked correctly as a hit
85  kKwsCorrUndetected, // Not marked as a hit, correctly
86  kKwsUnseen // Instance not seen in the hypotheses list
87 };

◆ GmmUpdateFlags

Enumerator
kGmmMeans 
kGmmVariances 
kGmmWeights 
kGmmTransitions 
kGmmAll 

Definition at line 28 of file model-common.h.

28  {
29  kGmmMeans = 0x001, // m
30  kGmmVariances = 0x002, // v
31  kGmmWeights = 0x004, // w
32  kGmmTransitions = 0x008, // t ... not really part of GMM.
33  kGmmAll = 0x00F // a
34 };

◆ MatrixResizeType

Enumerator
kSetZero 
kUndefined 
kCopyData 

Definition at line 37 of file matrix-common.h.

◆ MatrixStrideType

Enumerator
kDefaultStride 
kStrideEqualNumCols 

Definition at line 44 of file matrix-common.h.

◆ MatrixTransposeType

Enumerator
kTrans 
kNoTrans 

Definition at line 32 of file matrix-common.h.

32  {
33  kTrans = 112, // = CblasTrans
34  kNoTrans = 111 // = CblasNoTrans
MatrixTransposeType
Definition: matrix-common.h:32

◆ SgmmUpdateFlags

Enumerator
kSgmmPhoneVectors 

The letters correspond to the variable names.

kSgmmPhoneProjections 

v

kSgmmPhoneWeightProjections 

M.

kSgmmCovarianceMatrix 

w

kSgmmSubstateWeights 

S.

kSgmmSpeakerProjections 

c

kSgmmTransitions 

N.

kSgmmSpeakerWeightProjections 

t .. not really part of SGMM.

kSgmmAll 

u [ for SSGMM ]

Definition at line 47 of file model-common.h.

◆ SgmmWriteFlags

Enumerator
kSgmmGlobalParams 
kSgmmStateParams 

g

kSgmmNormalizers 

s

kSgmmBackgroundGmms 

n

kSgmmWriteAll 

u

Definition at line 62 of file model-common.h.

◆ ShellType

enum ShellType
Enumerator
kBash 

Definition at line 210 of file parse-options.cc.

210 { kBash = 0 };

◆ SpCopyType

enum SpCopyType
Enumerator
kTakeLower 
kTakeUpper 
kTakeMean 
kTakeMeanAndCheck 

Definition at line 49 of file matrix-common.h.

Function Documentation

◆ _RandGauss()

static float kaldi::_RandGauss ( )
inlinestatic

Definition at line 34 of file am-sgmm2.cc.

References RandGauss().

Referenced by AmSgmm2::SplitSubstatesInGroup().

35 {
36  return RandGauss();
37 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155

◆ AccCmvnStats() [1/2]

void AccCmvnStats ( const VectorBase< BaseFloat > &  feats,
BaseFloat  weight,
MatrixBase< double > *  stats 
)

Accumulation from a single frame (weighted).

Definition at line 30 of file cmvn.cc.

References VectorBase< Real >::Data(), VectorBase< Real >::Dim(), KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and MatrixBase< Real >::RowData().

Referenced by AccCmvnStats(), AccCmvnStatsForPair(), AccCmvnStatsWrapper(), and main().

30  {
31  int32 dim = feats.Dim();
32  KALDI_ASSERT(stats != NULL);
33  KALDI_ASSERT(stats->NumRows() == 2 && stats->NumCols() == dim + 1);
34  // Remove these __restrict__ modifiers if they cause compilation problems.
35  // It's just an optimization.
36  double *__restrict__ mean_ptr = stats->RowData(0),
37  *__restrict__ var_ptr = stats->RowData(1),
38  *__restrict__ count_ptr = mean_ptr + dim;
39  const BaseFloat * __restrict__ feats_ptr = feats.Data();
40  *count_ptr += weight;
41  // Careful-- if we change the format of the matrix, the "mean_ptr < count_ptr"
42  // statement below might become wrong.
43  for (; mean_ptr < count_ptr; mean_ptr++, var_ptr++, feats_ptr++) {
44  *mean_ptr += *feats_ptr * weight;
45  *var_ptr += *feats_ptr * *feats_ptr * weight;
46  }
47 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AccCmvnStats() [2/2]

void AccCmvnStats ( const MatrixBase< BaseFloat > &  feats,
const VectorBase< BaseFloat > *  weights,
MatrixBase< double > *  stats 
)

Accumulation from a feature file (possibly weighted– useful in excluding silence).

Definition at line 49 of file cmvn.cc.

References AccCmvnStats(), VectorBase< Real >::Dim(), rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

51  {
52  int32 num_frames = feats.NumRows();
53  if (weights != NULL) {
54  KALDI_ASSERT(weights->Dim() == num_frames);
55  }
56  for (int32 i = 0; i < num_frames; i++) {
57  SubVector<BaseFloat> this_frame = feats.Row(i);
58  BaseFloat weight = (weights == NULL ? 1.0 : (*weights)(i));
59  if (weight != 0.0)
60  AccCmvnStats(this_frame, weight, stats);
61  }
62 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
void AccCmvnStats(const MatrixBase< BaseFloat > &feats, const VectorBase< BaseFloat > *weights, MatrixBase< double > *stats)
Accumulation from a feature file (possibly weighted– useful in excluding silence).
Definition: cmvn.cc:49
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AccCmvnStatsForPair()

void kaldi::AccCmvnStatsForPair ( const std::string &  utt1,
const std::string &  utt2,
const MatrixBase< BaseFloat > &  feats1,
const MatrixBase< BaseFloat > &  feats2,
BaseFloat  quieter_channel_weight,
MatrixBase< double > *  cmvn_stats1,
MatrixBase< double > *  cmvn_stats2 
)

Definition at line 69 of file compute-cmvn-stats-two-channel.cc.

References AccCmvnStats(), rnnlm::i, KALDI_ASSERT, KALDI_WARN, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

Referenced by main().

74  {
75  KALDI_ASSERT(feats1.NumCols() == feats2.NumCols()); // same dim.
76  if (feats1.NumRows() != feats2.NumRows()) {
77  KALDI_WARN << "Number of frames differ between " << utt1 << " and " << utt2
78  << ": " << feats1.NumRows() << " vs. " << feats2.NumRows()
79  << ", treating them separately.";
80  AccCmvnStats(feats1, NULL, cmvn_stats1);
81  AccCmvnStats(feats2, NULL, cmvn_stats2);
82  return;
83  }
84 
85  for (int32 i = 0; i < feats1.NumRows(); i++) {
86  if (feats1(i, 0) > feats2(i, 0)) {
87  AccCmvnStats(feats1.Row(i), 1.0, cmvn_stats1);
88  AccCmvnStats(feats2.Row(i), quieter_channel_weight, cmvn_stats2);
89  }
90  else {
91  AccCmvnStats(feats2.Row(i), 1.0, cmvn_stats2);
92  AccCmvnStats(feats1.Row(i), quieter_channel_weight, cmvn_stats1);
93  }
94  }
95 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
#define KALDI_WARN
Definition: kaldi-error.h:150
void AccCmvnStats(const VectorBase< BaseFloat > &feats, BaseFloat weight, MatrixBase< double > *stats)
Accumulation from a single frame (weighted).
Definition: cmvn.cc:30
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ AccCmvnStatsWrapper()

bool kaldi::AccCmvnStatsWrapper ( const std::string &  utt,
const MatrixBase< BaseFloat > &  feats,
RandomAccessBaseFloatVectorReader weights_reader,
Matrix< double > *  cmvn_stats 
)

Definition at line 28 of file compute-cmvn-stats.cc.

References AccCmvnStats(), VectorBase< Real >::Dim(), RandomAccessTableReader< Holder >::HasKey(), RandomAccessTableReader< Holder >::IsOpen(), KALDI_WARN, MatrixBase< Real >::NumRows(), and RandomAccessTableReader< Holder >::Value().

Referenced by main().

31  {
32  if (!weights_reader->IsOpen()) {
33  AccCmvnStats(feats, NULL, cmvn_stats);
34  return true;
35  } else {
36  if (!weights_reader->HasKey(utt)) {
37  KALDI_WARN << "No weights available for utterance " << utt;
38  return false;
39  }
40  const Vector<BaseFloat> &weights = weights_reader->Value(utt);
41  if (weights.Dim() != feats.NumRows()) {
42  KALDI_WARN << "Weights for utterance " << utt << " have wrong dimension "
43  << weights.Dim() << " vs. " << feats.NumRows();
44  return false;
45  }
46  AccCmvnStats(feats, &weights, cmvn_stats);
47  return true;
48  }
49 }
const T & Value(const std::string &key)
#define KALDI_WARN
Definition: kaldi-error.h:150
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
bool HasKey(const std::string &key)
void AccCmvnStats(const VectorBase< BaseFloat > &feats, BaseFloat weight, MatrixBase< double > *stats)
Accumulation from a single frame (weighted).
Definition: cmvn.cc:30
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ AccStatsForUtterance() [1/2]

void kaldi::AccStatsForUtterance ( const TransitionModel trans_model,
const AmDiagGmm am_gmm,
const GaussPost gpost,
const Matrix< BaseFloat > &  feats,
FmllrRawAccs accs 
)

Definition at line 31 of file gmm-est-fmllr-raw-gpost.cc.

References FmllrRawAccs::AccumulateFromPosteriors(), AmDiagGmm::GetPdf(), rnnlm::i, and MatrixBase< Real >::Row().

Referenced by UtteranceSplitter::ExitStatus(), IvectorExtractorStats::IvectorExtractorStats(), and main().

35  {
36  for (size_t t = 0; t < gpost.size(); t++) {
37  for (size_t i = 0; i < gpost[t].size(); i++) {
38  int32 pdf = gpost[t][i].first;
39  const Vector<BaseFloat> &posterior(gpost[t][i].second);
40  accs->AccumulateFromPosteriors(am_gmm.GetPdf(pdf),
41  feats.Row(t), posterior);
42  }
43  }
44 }
kaldi::int32 int32
void AccumulateFromPosteriors(const DiagGmm &gmm, const VectorBase< BaseFloat > &data, const VectorBase< BaseFloat > &posteriors)
Accumulate stats for a GMM, given supplied posteriors.
Definition: fmllr-raw.cc:246
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
DiagGmm & GetPdf(int32 pdf_index)
Accessors.
Definition: am-diag-gmm.h:119
A class representing a vector.
Definition: kaldi-vector.h:406

◆ AccStatsForUtterance() [2/2]

void kaldi::AccStatsForUtterance ( const TransitionModel trans_model,
const AmDiagGmm am_gmm,
const Posterior post,
const Matrix< BaseFloat > &  feats,
FmllrRawAccs accs 
)

Definition at line 31 of file gmm-est-fmllr-raw.cc.

References FmllrRawAccs::AccumulateForGmm(), ConvertPosteriorToPdfs(), AmDiagGmm::GetPdf(), rnnlm::i, and MatrixBase< Real >::Row().

35  {
36  Posterior pdf_post;
37  ConvertPosteriorToPdfs(trans_model, post, &pdf_post);
38  for (size_t t = 0; t < post.size(); t++) {
39  for (size_t i = 0; i < pdf_post[t].size(); i++) {
40  int32 pdf = pdf_post[t][i].first;
41  BaseFloat weight = pdf_post[t][i].second;
42  accs->AccumulateForGmm(am_gmm.GetPdf(pdf),
43  feats.Row(t), weight);
44  }
45  }
46 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
DiagGmm & GetPdf(int32 pdf_index)
Accessors.
Definition: am-diag-gmm.h:119
BaseFloat AccumulateForGmm(const DiagGmm &gmm, const VectorBase< BaseFloat > &data, BaseFloat weight)
Accumulate stats for a single GMM in the model; returns log likelihood.
Definition: fmllr-raw.cc:107
void ConvertPosteriorToPdfs(const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
Converts a posterior over transition-ids to be a posterior over pdf-ids.
Definition: posterior.cc:322

◆ AccumulateForUtterance() [1/8]

bool kaldi::AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const DiagGmm gmm,
const std::string &  key,
RandomAccessBaseFloatVectorReader weights_reader,
RandomAccessInt32VectorVectorReader gselect_reader,
AccumFullGmm fullcov_stats 
)

Definition at line 32 of file gmm-global-est-fmllr.cc.

References AccumFullGmm::AccumulateForComponent(), AccumFullGmm::AccumulateFromDiag(), VectorBase< Real >::Dim(), RandomAccessTableReader< Holder >::HasKey(), rnnlm::i, RandomAccessTableReader< Holder >::IsOpen(), KALDI_WARN, DiagGmm::LogLikelihoodsPreselect(), MatrixBase< Real >::NumRows(), MatrixBase< Real >::Row(), and RandomAccessTableReader< Holder >::Value().

37  {
38  Vector<BaseFloat> weights;
39  if (weights_reader->IsOpen()) {
40  if (!weights_reader->HasKey(key)) {
41  KALDI_WARN << "No weights present for utterance " << key;
42  return false;
43  }
44  weights = weights_reader->Value(key);
45  }
46  int32 num_frames = feats.NumRows();
47  if (gselect_reader->IsOpen()) {
48  if (!gselect_reader->HasKey(key)) {
49  KALDI_WARN << "No gselect information present for utterance " << key;
50  return false;
51  }
52  const std::vector<std::vector<int32> > &gselect(gselect_reader->Value(key));
53  if (gselect.size() != num_frames) {
54  KALDI_WARN << "gselect information has wrong size for utterance " << key;
55  return false;
56  }
57  for (int32 t = 0; t < num_frames; t++) {
58  const std::vector<int32> &this_gselect(gselect[t]);
59  BaseFloat weight = (weights.Dim() != 0 ? weights(t) : 1.0);
60  if (weight != 0.0) {
61  Vector<BaseFloat> post(this_gselect.size());
62  gmm.LogLikelihoodsPreselect(feats.Row(t), this_gselect, &post);
63  post.ApplySoftMax(); // get posteriors.
64  post.Scale(weight); // scale by the weight for this frame.
65  for (size_t i = 0; i < this_gselect.size(); i++)
66  fullcov_stats->AccumulateForComponent(feats.Row(t),
67  this_gselect[i], post(i));
68  }
69  }
70  } else {
71  for (int32 t = 0; t < num_frames; t++) {
72  BaseFloat weight = (weights.Dim() != 0 ? weights(t) : 1.0);
73  if (weight != 0.0)
74  fullcov_stats->AccumulateFromDiag(gmm, feats.Row(t), weight);
75  }
76  }
77  return true;
78 }
void LogLikelihoodsPreselect(const VectorBase< BaseFloat > &data, const std::vector< int32 > &indices, Vector< BaseFloat > *loglikes) const
Outputs the per-component log-likelihoods of a subset of mixture components.
Definition: diag-gmm.cc:566
BaseFloat AccumulateFromDiag(const DiagGmm &gmm, const VectorBase< BaseFloat > &data, BaseFloat frame_posterior)
Accumulate for all components given a diagonal-covariance GMM.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
const T & Value(const std::string &key)
#define KALDI_WARN
Definition: kaldi-error.h:150
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
bool HasKey(const std::string &key)
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void AccumulateForComponent(const VectorBase< BaseFloat > &data, int32 comp_index, BaseFloat weight)
Accumulate for a single component, given the posterior.
Definition: mle-full-gmm.cc:96

◆ AccumulateForUtterance() [2/8]

void kaldi::AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const Sgmm2GauPost gpost,
const TransitionModel trans_model,
const AmSgmm2 am_sgmm,
Sgmm2PerSpkDerivedVars spk_vars,
MleSgmm2SpeakerAccs spk_stats 
)

Definition at line 33 of file sgmm2-est-spkvecs-gpost.cc.

References MleSgmm2SpeakerAccs::AccumulateFromPosteriors(), AmSgmm2::ComputePerFrameVars(), rnnlm::i, rnnlm::j, MatrixBase< Real >::Row(), and TransitionModel::TransitionIdToPdf().

38  {
39  kaldi::Sgmm2PerFrameDerivedVars per_frame_vars;
40 
41  for (size_t i = 0; i < gpost.size(); i++) {
42  am_sgmm.ComputePerFrameVars(feats.Row(i),
43  gpost[i].gselect, *spk_vars,
44  &per_frame_vars);
45 
46  for (size_t j = 0; j < gpost[i].tids.size(); j++) {
47  int32 pdf_id = trans_model.TransitionIdToPdf(gpost[i].tids[j]);
48  spk_stats->AccumulateFromPosteriors(am_sgmm, per_frame_vars,
49  gpost[i].posteriors[j], pdf_id,
50  spk_vars);
51  }
52  }
53 }
kaldi::int32 int32
int32 TransitionIdToPdf(int32 trans_id) const
BaseFloat AccumulateFromPosteriors(const AmSgmm2 &model, const Sgmm2PerFrameDerivedVars &frame_vars, const Matrix< BaseFloat > &posteriors, int32 pdf_index, Sgmm2PerSpkDerivedVars *spk_vars)
Accumulate statistics, given posteriors.
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
void ComputePerFrameVars(const VectorBase< BaseFloat > &data, const std::vector< int32 > &gselect, const Sgmm2PerSpkDerivedVars &spk_vars, Sgmm2PerFrameDerivedVars *per_frame_vars) const
This needs to be called with each new frame of data, prior to accumulation or likelihood evaluation: ...
Definition: am-sgmm2.cc:442
Holds the per-frame precomputed quantities x(t), x_{i}(t), z_{i}(t), and n_{i}(t) (cf...
Definition: am-sgmm2.h:142

◆ AccumulateForUtterance() [3/8]

void kaldi::AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const Posterior post,
const DiagGmm gmm,
FmllrDiagGmmAccs spk_stats 
)

Definition at line 34 of file gmm-global-est-lvtln-trans.cc.

References FmllrDiagGmmAccs::AccumulateFromPosteriorsPreselect(), rnnlm::i, rnnlm::j, KALDI_ASSERT, MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

37  {
38  KALDI_ASSERT(static_cast<int32>(post.size()) == feats.NumRows());
39  for (size_t i = 0; i < post.size(); i++) {
40  std::vector<int32> gselect(post[i].size());
41  Vector<BaseFloat> this_post(post[i].size());
42  for (size_t j = 0; j < post[i].size(); j++) {
43  int32 g = post[i][j].first;
44  BaseFloat weight = post[i][j].second;
45  gselect[j] = g;
46  this_post(j) = weight;
47  }
48  spk_stats->AccumulateFromPosteriorsPreselect(gmm, gselect,
49  feats.Row(i),
50  this_post);
51  }
52 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void AccumulateFromPosteriorsPreselect(const DiagGmm &gmm, const std::vector< int32 > &gselect, const VectorBase< BaseFloat > &data, const VectorBase< BaseFloat > &posteriors)
Accumulate stats for a GMM, given supplied posteriors.

◆ AccumulateForUtterance() [4/8]

void kaldi::AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const GaussPost gpost,
const AmDiagGmm am_gmm,
FmllrDiagGmmAccs spk_stats 
)

Definition at line 34 of file gmm-est-lvtln-trans.cc.

References FmllrDiagGmmAccs::AccumulateFromPosteriors(), AmDiagGmm::GetPdf(), rnnlm::i, rnnlm::j, and MatrixBase< Real >::Row().

37  {
38  for (size_t i = 0; i < gpost.size(); i++) {
39  for (size_t j = 0; j < gpost[i].size(); j++) {
40  int32 pdf_id = gpost[i][j].first;
41  const Vector<BaseFloat> &posterior(gpost[i][j].second);
42  spk_stats->AccumulateFromPosteriors(am_gmm.GetPdf(pdf_id),
43  feats.Row(i), posterior);
44  }
45  }
46 }
void AccumulateFromPosteriors(const DiagGmm &gmm, const VectorBase< BaseFloat > &data, const VectorBase< BaseFloat > &posteriors)
Accumulate stats for a GMM, given supplied posteriors.
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
DiagGmm & GetPdf(int32 pdf_index)
Accessors.
Definition: am-diag-gmm.h:119
A class representing a vector.
Definition: kaldi-vector.h:406

◆ AccumulateForUtterance() [5/8]

void AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const GaussPost gpost,
const TransitionModel trans_model,
const AmDiagGmm am_gmm,
FmllrDiagGmmAccs spk_stats 
)

Definition at line 35 of file gmm-basis-fmllr-accs-gpost.cc.

References FmllrDiagGmmAccs::AccumulateFromPosteriors(), AmDiagGmm::GetPdf(), rnnlm::i, rnnlm::j, and MatrixBase< Real >::Row().

Referenced by main().

39  {
40  for (size_t i = 0; i < gpost.size(); i++) {
41  for (size_t j = 0; j < gpost[i].size(); j++) {
42  int32 pdf_id = gpost[i][j].first;
43  const Vector<BaseFloat> & posterior(gpost[i][j].second);
44  spk_stats->AccumulateFromPosteriors(am_gmm.GetPdf(pdf_id),
45  feats.Row(i), posterior);
46  }
47  }
48 }
void AccumulateFromPosteriors(const DiagGmm &gmm, const VectorBase< BaseFloat > &data, const VectorBase< BaseFloat > &posteriors)
Accumulate stats for a GMM, given supplied posteriors.
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
DiagGmm & GetPdf(int32 pdf_index)
Accessors.
Definition: am-diag-gmm.h:119
A class representing a vector.
Definition: kaldi-vector.h:406

◆ AccumulateForUtterance() [6/8]

void AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const Posterior post,
const TransitionModel trans_model,
const AmDiagGmm am_gmm,
FmllrDiagGmmAccs spk_stats 
)

Definition at line 35 of file gmm-basis-fmllr-accs.cc.

References FmllrDiagGmmAccs::AccumulateForGmm(), ConvertPosteriorToPdfs(), AmDiagGmm::GetPdf(), rnnlm::i, rnnlm::j, and MatrixBase< Real >::Row().

39  {
40  Posterior pdf_post;
41  ConvertPosteriorToPdfs(trans_model, post, &pdf_post);
42  for (size_t i = 0; i < post.size(); i++) {
43  for (size_t j = 0; j < pdf_post[i].size(); j++) {
44  int32 pdf_id = pdf_post[i][j].first;
45  spk_stats->AccumulateForGmm(am_gmm.GetPdf(pdf_id),
46  feats.Row(i),
47  pdf_post[i][j].second);
48  }
49  }
50 }
kaldi::int32 int32
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
DiagGmm & GetPdf(int32 pdf_index)
Accessors.
Definition: am-diag-gmm.h:119
void ConvertPosteriorToPdfs(const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
Converts a posterior over transition-ids to be a posterior over pdf-ids.
Definition: posterior.cc:322
BaseFloat AccumulateForGmm(const DiagGmm &gmm, const VectorBase< BaseFloat > &data, BaseFloat weight)
Accumulate stats for a single GMM in the model; returns log likelihood.

◆ AccumulateForUtterance() [7/8]

void kaldi::AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const Matrix< BaseFloat > &  transformed_feats,
const std::vector< std::vector< int32 > > &  gselect,
const Posterior post,
const TransitionModel trans_model,
const AmSgmm2 am_sgmm,
BaseFloat  logdet,
Sgmm2PerSpkDerivedVars spk_vars,
FmllrSgmm2Accs spk_stats 
)

Definition at line 35 of file sgmm2-est-fmllr.cc.

References FmllrSgmm2Accs::AccumulateFromPosteriors(), AmSgmm2::ComponentPosteriors(), AmSgmm2::ComputePerFrameVars(), ConvertPosteriorToPdfs(), rnnlm::j, MatrixBase< Real >::Row(), and MatrixBase< Real >::Scale().

43  {
44  kaldi::Sgmm2PerFrameDerivedVars per_frame_vars;
45 
46  Posterior pdf_post;
47  ConvertPosteriorToPdfs(trans_model, post, &pdf_post);
48  for (size_t t = 0; t < post.size(); t++) {
49  // per-frame vars only used for computing posteriors... use the
50  // transformed feats for this, if available.
51  am_sgmm.ComputePerFrameVars(transformed_feats.Row(t), gselect[t],
52  *spk_vars, &per_frame_vars);
53 
54 
55  for (size_t j = 0; j < pdf_post[t].size(); j++) {
56  int32 pdf_id = pdf_post[t][j].first;
57  Matrix<BaseFloat> posteriors;
58  am_sgmm.ComponentPosteriors(per_frame_vars, pdf_id,
59  spk_vars, &posteriors);
60  posteriors.Scale(pdf_post[t][j].second);
61  spk_stats->AccumulateFromPosteriors(am_sgmm, *spk_vars, feats.Row(t),
62  gselect[t], posteriors, pdf_id);
63  }
64  }
65 }
BaseFloat ComponentPosteriors(const Sgmm2PerFrameDerivedVars &per_frame_vars, int32 j2, Sgmm2PerSpkDerivedVars *spk_vars, Matrix< BaseFloat > *post) const
Similar to LogLikelihood() function above, but also computes the posterior probabilities for the pre-...
Definition: am-sgmm2.cc:574
void AccumulateFromPosteriors(const AmSgmm2 &sgmm, const Sgmm2PerSpkDerivedVars &spk, const VectorBase< BaseFloat > &data, const std::vector< int32 > &gauss_select, const Matrix< BaseFloat > &posteriors, int32 state_index)
Definition: fmllr-sgmm2.cc:171
kaldi::int32 int32
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
void Scale(Real alpha)
Multiply each element with a scalar value.
void ComputePerFrameVars(const VectorBase< BaseFloat > &data, const std::vector< int32 > &gselect, const Sgmm2PerSpkDerivedVars &spk_vars, Sgmm2PerFrameDerivedVars *per_frame_vars) const
This needs to be called with each new frame of data, prior to accumulation or likelihood evaluation: ...
Definition: am-sgmm2.cc:442
void ConvertPosteriorToPdfs(const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
Converts a posterior over transition-ids to be a posterior over pdf-ids.
Definition: posterior.cc:322
Holds the per-frame precomputed quantities x(t), x_{i}(t), z_{i}(t), and n_{i}(t) (cf...
Definition: am-sgmm2.h:142

◆ AccumulateForUtterance() [8/8]

void kaldi::AccumulateForUtterance ( const Matrix< BaseFloat > &  feats,
const Posterior post,
const TransitionModel trans_model,
const AmSgmm2 am_sgmm,
const vector< vector< int32 > > &  gselect,
Sgmm2PerSpkDerivedVars spk_vars,
MleSgmm2SpeakerAccs spk_stats 
)

Definition at line 36 of file sgmm2-est-spkvecs.cc.

References MleSgmm2SpeakerAccs::Accumulate(), AmSgmm2::ComputePerFrameVars(), ConvertPosteriorToPdfs(), rnnlm::i, rnnlm::j, KALDI_ASSERT, MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

42  {
43  kaldi::Sgmm2PerFrameDerivedVars per_frame_vars;
44 
45  KALDI_ASSERT(gselect.size() == feats.NumRows());
46  Posterior pdf_post;
47  ConvertPosteriorToPdfs(trans_model, post, &pdf_post);
48  for (size_t i = 0; i < post.size(); i++) {
49  am_sgmm.ComputePerFrameVars(feats.Row(i), gselect[i],
50  *spk_vars, &per_frame_vars);
51 
52  for (size_t j = 0; j < pdf_post[i].size(); j++) {
53  int32 pdf_id = pdf_post[i][j].first;
54  spk_stats->Accumulate(am_sgmm, per_frame_vars, pdf_id,
55  pdf_post[i][j].second, spk_vars);
56  }
57  }
58 }
BaseFloat Accumulate(const AmSgmm2 &model, const Sgmm2PerFrameDerivedVars &frame_vars, int32 pdf_index, BaseFloat weight, Sgmm2PerSpkDerivedVars *spk_vars)
Accumulate statistics. Returns per-frame log-likelihood.
kaldi::int32 int32
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
void ComputePerFrameVars(const VectorBase< BaseFloat > &data, const std::vector< int32 > &gselect, const Sgmm2PerSpkDerivedVars &spk_vars, Sgmm2PerFrameDerivedVars *per_frame_vars) const
This needs to be called with each new frame of data, prior to accumulation or likelihood evaluation: ...
Definition: am-sgmm2.cc:442
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void ConvertPosteriorToPdfs(const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
Converts a posterior over transition-ids to be a posterior over pdf-ids.
Definition: posterior.cc:322
Holds the per-frame precomputed quantities x(t), x_{i}(t), z_{i}(t), and n_{i}(t) (cf...
Definition: am-sgmm2.h:142

◆ AccumulateTreeStats()

void AccumulateTreeStats ( const TransitionModel trans_model,
const AccumulateTreeStatsInfo info,
const std::vector< int32 > &  alignment,
const Matrix< BaseFloat > &  features,
std::map< EventType, GaussClusterable * > *  stats 
)

Accumulates the stats needed for training context-dependency trees (in the "normal" way).

It adds to 'stats' the stats obtained from this file. Any new GaussClusterable* pointers in "stats" will be allocated with "new".

Definition at line 36 of file tree-accu.cc.

References AccumulateTreeStatsInfo::central_position, AccumulateTreeStatsInfo::ci_phones, AccumulateTreeStatsInfo::context_width, rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_WARN, kPdfClass, MapPhone(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), AccumulateTreeStatsInfo::phone_map, MatrixBase< Real >::Row(), SplitToPhones(), TransitionModel::TransitionIdToPdfClass(), TransitionModel::TransitionIdToPhone(), and AccumulateTreeStatsInfo::var_floor.

Referenced by main().

40  {
41  std::vector<std::vector<int32> > split_alignment;
42  bool ans = SplitToPhones(trans_model, alignment, &split_alignment);
43  if (!ans) {
44  KALDI_WARN << "AccumulateTreeStats: alignment appears to be bad, not using it";
45  return;
46  }
47  int32 cur_pos = 0;
48  int32 dim = features.NumCols();
49  KALDI_ASSERT(features.NumRows() == static_cast<int32>(alignment.size()));
50  for (int32 i = -info.context_width; i < static_cast<int32>(split_alignment.size()); i++) {
51  // consider window starting at i, only if i+info.central_position is within
52  // list of phones.
53  if (i + info.central_position >= 0 &&
54  i + info.central_position < static_cast<int32>(split_alignment.size())) {
55  int32 central_phone =
56  MapPhone(info.phone_map,
57  trans_model.TransitionIdToPhone(
58  split_alignment[i+info.central_position][0]));
59  bool is_ctx_dep = !std::binary_search(info.ci_phones.begin(),
60  info.ci_phones.end(),
61  central_phone);
62  EventType evec;
63  for (int32 j = 0; j < info.context_width; j++) {
64  int32 phone;
65  if (i + j >= 0 && i + j < static_cast<int32>(split_alignment.size()))
66  phone =
67  MapPhone(info.phone_map,
68  trans_model.TransitionIdToPhone(split_alignment[i+j][0]));
69  else
70  phone = 0; // ContextDependency class uses 0 to mean "out of window";
71  // we also set the phone arbitrarily to 0
72 
73  // Don't add stuff to the event that we don't "allow" to be asked, due
74  // to the central phone being context-independent: check "is_ctx_dep".
75  // Why not just set the value to zero in this
76  // case? It's for safety. By omitting the key from the event, we
77  // ensure that there is no way a question can ever be asked that might
78  // give an inconsistent answer in tree-training versus graph-building.
79  // [setting it to zero would have the same effect given the "normal"
80  // recipe but might be less robust to changes in tree-building recipe].
81  if (is_ctx_dep || j == info.central_position)
82  evec.push_back(std::make_pair(static_cast<EventKeyType>(j), static_cast<EventValueType>(phone)));
83  }
84  for (int32 j = 0; j < static_cast<int32>(split_alignment[i+info.central_position].size());j++) {
85  // for central phone of this window...
86  EventType evec_more(evec);
87  int32 pdf_class = trans_model.TransitionIdToPdfClass(
88  split_alignment[i+info.central_position][j]);
89  // pdf_class will normally by 0, 1 or 2 for 3-state HMM.
90  std::pair<EventKeyType, EventValueType> pr(kPdfClass, pdf_class);
91  evec_more.push_back(pr);
92  std::sort(evec_more.begin(), evec_more.end()); // these must be sorted!
93  if (stats->count(evec_more) == 0)
94  (*stats)[evec_more] = new GaussClusterable(dim, info.var_floor);
95 
96  BaseFloat weight = 1.0;
97  (*stats)[evec_more]->AddStats(features.Row(cur_pos), weight);
98  cur_pos++;
99  }
100  }
101  }
102  KALDI_ASSERT(cur_pos == static_cast<int32>(alignment.size()));
103 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
static int32 MapPhone(const std::vector< int32 > &phone_map, int32 phone)
Definition: tree-accu.cc:26
bool SplitToPhones(const TransitionModel &trans_model, const std::vector< int32 > &alignment, std::vector< std::vector< int32 > > *split_alignment)
SplitToPhones splits up the TransitionIds in "alignment" into their individual phones (one vector per...
Definition: hmm-utils.cc:723
static const EventKeyType kPdfClass
Definition: context-dep.h:39
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ AddCompactLatticeArcToLattice()

static void kaldi::AddCompactLatticeArcToLattice ( const CompactLatticeArc clat_arc,
LatticeArc::StateId  src_state,
Lattice lat 
)
static

Definition at line 1106 of file lattice-incremental-decoder.cc.

References rnnlm::i.

Referenced by LatticeIncrementalDeterminizer::InitializeRawLatticeChunk().

1109  {
1110  const std::vector<int32> &string = clat_arc.weight.String();
1111  size_t N = string.size();
1112  if (N == 0) {
1113  LatticeArc arc;
1114  arc.ilabel = 0;
1115  arc.olabel = clat_arc.ilabel;
1116  arc.nextstate = clat_arc.nextstate;
1117  arc.weight = clat_arc.weight.Weight();
1118  lat->AddArc(src_state, arc);
1119  } else {
1120  LatticeArc::StateId cur_state = src_state;
1121  for (size_t i = 0; i < N; i++) {
1122  LatticeArc arc;
1123  arc.ilabel = string[i];
1124  arc.olabel = (i == 0 ? clat_arc.ilabel : 0);
1125  arc.nextstate = (i + 1 == N ? clat_arc.nextstate : lat->AddState());
1126  arc.weight = (i == 0 ? clat_arc.weight.Weight() : LatticeWeight::One());
1127  lat->AddArc(cur_state, arc);
1128  cur_state = arc.nextstate;
1129  }
1130  }
1131 }
fst::StdArc::StateId StateId
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40

◆ AddMatMatBatched() [1/3]

void AddMatMatBatched ( const Real  alpha,
std::vector< CuSubMatrix< Real > *> &  C,
const std::vector< CuSubMatrix< Real > *> &  A,
MatrixTransposeType  transA,
const std::vector< CuSubMatrix< Real > *> &  B,
MatrixTransposeType  transB,
const Real  beta 
)

Does multiple matrix multiplications, executing them in parallel using cuBLAS's gemmBatched if we are using a GPU.

Vectors A, B and C must have the same length; for each i, this function executes the matrix operation C[i] = alpha * A[i](^T)*B[i](^T) + beta * C[i].

Definition at line 2207 of file cu-matrix.cc.

References AddMatMatBatched(), CuMatrixBase< Real >::data_, rnnlm::i, KALDI_ASSERT, kTrans, rnnlm::n, CuMatrixBase< Real >::NumCols(), and CuMatrixBase< Real >::NumRows().

Referenced by TestCuMatrixMatMatBatched(), and UnitTestCuMatrixAddMatMatBatched().

2211  {
2212  KALDI_ASSERT(A.size() == B.size() && B.size() == C.size());
2213  int32 size = A.size();
2214 
2215  if (size == 0) return;
2216 
2217  // all elements must have the same num-rows, num-cols and stride
2218  for (int32 i = 0; i + 1 < size; i++) {
2219  KALDI_ASSERT(A[i]->NumRows() == A[i+1]->NumRows());
2220  KALDI_ASSERT(A[i]->NumCols() == A[i+1]->NumCols());
2221  KALDI_ASSERT(A[i]->Stride() == A[i+1]->Stride());
2222  KALDI_ASSERT(B[i]->NumRows() == B[i+1]->NumRows());
2223  KALDI_ASSERT(B[i]->NumCols() == B[i+1]->NumCols());
2224  KALDI_ASSERT(B[i]->Stride() == B[i+1]->Stride());
2225  KALDI_ASSERT(C[i]->NumRows() == C[i+1]->NumRows());
2226  KALDI_ASSERT(C[i]->NumCols() == C[i+1]->NumCols());
2227  KALDI_ASSERT(C[i]->Stride() == C[i+1]->Stride());
2228  }
2229  // CUBLAS is col-major, cudamatrix is row-major, how to do the mapping?
2230  // keep trans..., just swap A&B matrices: A->B B->A
2231  MatrixIndexT m = ((transB==kTrans)? B[0]->NumRows() : B[0]->NumCols());
2232  MatrixIndexT n = ((transA==kTrans)? A[0]->NumCols() : A[0]->NumRows());
2233  MatrixIndexT k = ((transB==kTrans)? B[0]->NumCols() : B[0]->NumRows());
2234  MatrixIndexT k1 = ((transA==kTrans)? A[0]->NumRows() : A[0]->NumCols());
2235 
2236  KALDI_ASSERT(m == C[0]->NumCols());
2237  KALDI_ASSERT(n == C[0]->NumRows());
2238  KALDI_ASSERT(k == k1);
2239 
2240  if (m == 0) return;
2241 
2242 #if HAVE_CUDA == 1
2243  if (CuDevice::Instantiate().Enabled()) {
2244  CuTimer tim;
2245  Real **device_abc_array =
2246  static_cast<Real**>(CuDevice::Instantiate().Malloc(3 * size * sizeof(Real*)));
2247  const Real **device_a_array = const_cast<const Real**>(device_abc_array);
2248  const Real **device_b_array = const_cast<const Real**>(device_abc_array) + size;
2249  Real **device_c_array = device_abc_array + 2 * size;
2250  const Real **host_abc_array = new const Real*[3*size];
2251  const Real **host_a_array = host_abc_array;
2252  const Real **host_b_array = host_abc_array + size;
2253  const Real **host_c_array = host_abc_array + 2 * size;
2254 
2255  for (int32 i = 0; i < size; i++) {
2256  host_a_array[i] = A[i]->data_;
2257  host_b_array[i] = B[i]->data_;
2258  host_c_array[i] = C[i]->data_;
2259  }
2260 
2261  CU_SAFE_CALL(cudaMemcpyAsync(device_abc_array, host_abc_array,
2262  3*size*sizeof(Real*), cudaMemcpyHostToDevice,
2263  cudaStreamPerThread));
2264 
2265  CUBLAS_SAFE_CALL(cublas_gemmBatched(GetCublasHandle(),
2266  (transB==kTrans? CUBLAS_OP_T:CUBLAS_OP_N),
2267  (transA==kTrans? CUBLAS_OP_T:CUBLAS_OP_N),
2268  m, n, k, alpha, device_b_array,
2269  B[0]->Stride(), device_a_array,
2270  A[0]->Stride(), beta, device_c_array,
2271  C[0]->Stride(), size));
2272 
2273  CuDevice::Instantiate().Free(device_abc_array);
2274  delete[] host_abc_array;
2275 
2276  CuDevice::Instantiate().AccuProfile(__func__, tim);
2277  } else
2278 #endif
2279  {
2280  for (int32 i = 0; i < size; i++) {
2281  C[i]->Mat().AddMatMat(alpha, A[i]->Mat(), transA, B[i]->Mat(), transB, beta);
2282  }
2283  }
2284 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddMatMatBatched() [2/3]

template void kaldi::AddMatMatBatched ( const float  alpha,
std::vector< CuSubMatrix< float > * > &  C,
const std::vector< CuSubMatrix< float > * > &  A,
MatrixTransposeType  transA,
const std::vector< CuSubMatrix< float > * > &  B,
MatrixTransposeType  transB,
const float  beta 
)

◆ AddMatMatBatched() [3/3]

template void kaldi::AddMatMatBatched ( const double  alpha,
std::vector< CuSubMatrix< double > * > &  C,
const std::vector< CuSubMatrix< double > * > &  A,
MatrixTransposeType  transA,
const std::vector< CuSubMatrix< double > * > &  B,
MatrixTransposeType  transB,
const double  beta 
)

Referenced by AddMatMatBatched().

◆ AddNoise()

void kaldi::AddNoise ( Vector< BaseFloat > *  noise,
BaseFloat  snr_db,
BaseFloat  time,
BaseFloat  samp_freq,
BaseFloat  signal_power,
Vector< BaseFloat > *  signal 
)

Definition at line 104 of file wav-reverberate.cc.

References AddVectorsWithOffset(), VectorBase< Real >::Dim(), KALDI_VLOG, VectorBase< Real >::Scale(), and VecVec().

Referenced by main().

106  {
107  float noise_power = VecVec(*noise, *noise) / noise->Dim();
108  float scale_factor = sqrt(pow(10, -snr_db / 10) * signal_power / noise_power);
109  noise->Scale(scale_factor);
110  KALDI_VLOG(1) << "Noise signal is being scaled with " << scale_factor
111  << " to generate output with SNR " << snr_db << "db\n";
112  int32 offset = time * samp_freq;
113  AddVectorsWithOffset(*noise, offset, signal);
114 }
kaldi::int32 int32
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
void Scale(Real alpha)
Multiplies all elements by this constant.
void AddVectorsWithOffset(const Vector< BaseFloat > &signal1, int32 offset, Vector< BaseFloat > *signal2)
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ AddOuterProductPlusMinus< double >()

template void kaldi::AddOuterProductPlusMinus< double > ( double  alpha,
const VectorBase< double > &  a,
const VectorBase< double > &  b,
MatrixBase< double > *  plus,
MatrixBase< double > *  minus 
)

◆ AddOuterProductPlusMinus< float >()

template void kaldi::AddOuterProductPlusMinus< float > ( float  alpha,
const VectorBase< float > &  a,
const VectorBase< float > &  b,
MatrixBase< float > *  plus,
MatrixBase< float > *  minus 
)

◆ AddSelfLoops()

void kaldi::AddSelfLoops ( fst::StdMutableFst *  fst)

Definition at line 109 of file arpa-lm-compiler-test.cc.

References kDisambig, and kEps.

109  {
110  for (fst::StateIterator<fst::StdMutableFst> siter(*fst);
111  !siter.Done(); siter.Next()) {
112  fst->AddArc(siter.Value(),
113  fst::StdArc(kEps, kDisambig, 0, siter.Value()));
114  }
115 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::StdArc StdArc

◆ AddSelfLoopsNoReorder()

static void kaldi::AddSelfLoopsNoReorder ( const TransitionModel trans_model,
const std::vector< int32 > &  disambig_syms,
BaseFloat  self_loop_scale,
bool  check_no_self_loops,
fst::VectorFst< fst::StdArc > *  fst 
)
static

Definition at line 555 of file hmm-utils.cc.

References TransitionModel::GetNonSelfLoopLogProb(), TransitionModel::GetTransitionLogProb(), KALDI_ASSERT, fst::MakeFollowingInputSymbolsSameClass(), TransitionModel::SelfLoopOf(), and fst::Times().

Referenced by AddSelfLoops().

560  {
561  using namespace fst;
562  typedef StdArc Arc;
563  typedef Arc::Label Label;
564  typedef Arc::StateId StateId;
565  typedef Arc::Weight Weight;
566 
567  // Duplicate states as necessary so that each state has at most one self-loop
568  // on it.
569  TidToTstateMapper f(trans_model, disambig_syms, check_no_self_loops);
571 
572  StateId num_states = fst->NumStates();
573  for (StateId s = 0; s < num_states; s++) {
574  int32 my_trans_state = f(kNoLabel);
575  KALDI_ASSERT(my_trans_state == -1);
576  for (MutableArcIterator<VectorFst<Arc> > aiter(fst, s);
577  !aiter.Done();
578  aiter.Next()) {
579  Arc arc = aiter.Value();
580  if (my_trans_state == -1) my_trans_state = f(arc.ilabel);
581  else KALDI_ASSERT(my_trans_state == f(arc.ilabel)); // or MakeFollowingInputSymbolsSameClass failed.
582  if (my_trans_state > 0) { // transition-id; multiply weight...
583  BaseFloat log_prob = trans_model.GetNonSelfLoopLogProb(my_trans_state);
584  arc.weight = Times(arc.weight, Weight(-log_prob*self_loop_scale));
585  aiter.SetValue(arc);
586  }
587  }
588  if (fst->Final(s) != Weight::Zero()) {
589  KALDI_ASSERT(my_trans_state == kNoLabel || my_trans_state == 0); // or MakeFollowingInputSymbolsSameClass failed.
590  }
591  if (my_trans_state != kNoLabel && my_trans_state != 0) {
592  // a transition-state; add self-loop, if it has one.
593  int32 trans_id = trans_model.SelfLoopOf(my_trans_state);
594  if (trans_id != 0) { // has self-loop.
595  BaseFloat log_prob = trans_model.GetTransitionLogProb(trans_id);
596  fst->AddArc(s, Arc(trans_id, 0, Weight(-log_prob*self_loop_scale), s));
597  }
598  }
599  }
600 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::StdArc StdArc
kaldi::int32 int32
LatticeWeightTpl< FloatType > Times(const LatticeWeightTpl< FloatType > &w1, const LatticeWeightTpl< FloatType > &w2)
fst::StdArc::Label Label
float BaseFloat
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void MakeFollowingInputSymbolsSameClass(bool end_is_epsilon, MutableFst< Arc > *fst, const F &f)
As MakeFollowingInputSymbolsSame, but takes a functor object that maps labels to classes.

◆ AddSelfLoopsReorder()

static void kaldi::AddSelfLoopsReorder ( const TransitionModel trans_model,
const std::vector< int32 > &  disambig_syms,
BaseFloat  self_loop_scale,
bool  check_no_self_loops,
fst::VectorFst< fst::StdArc > *  fst 
)
static

Definition at line 472 of file hmm-utils.cc.

References TransitionModel::GetNonSelfLoopLogProb(), TransitionModel::GetTransitionLogProb(), KALDI_ASSERT, fst::MakePrecedingInputSymbolsSameClass(), TransitionModel::SelfLoopOf(), and fst::Times().

Referenced by AddSelfLoops().

476  {
477  using namespace fst;
478  typedef StdArc Arc;
479  typedef Arc::Label Label;
480  typedef Arc::StateId StateId;
481  typedef Arc::Weight Weight;
482 
483  TidToTstateMapper f(trans_model, disambig_syms, check_no_self_loops);
484  // Duplicate states as necessary so that each state will require at most one
485  // self-loop to be added to it. Approximately this means that if a
486  // state has multiple different symbols on arcs entering it, it will be
487  // duplicated, with one copy per incoming symbol.
489 
490  int32 kNoTransState = f(kNoLabel);
491  KALDI_ASSERT(kNoTransState == -1);
492 
493  // use the following to keep track of the transition-state for each state.
494  std::vector<int32> state_in(fst->NumStates(), kNoTransState);
495 
496  // This first loop just works out the label into each state,
497  // and converts the transitions in the graph from transition-states
498  // to transition-ids.
499 
500  for (StateIterator<VectorFst<Arc> > siter(*fst);
501  !siter.Done();
502  siter.Next()) {
503  StateId s = siter.Value();
504  for (MutableArcIterator<VectorFst<Arc> > aiter(fst, s);
505  !aiter.Done();
506  aiter.Next()) {
507  Arc arc = aiter.Value();
508  int32 trans_state = f(arc.ilabel);
509  if (state_in[arc.nextstate] == kNoTransState)
510  state_in[arc.nextstate] = trans_state;
511  else {
512  KALDI_ASSERT(state_in[arc.nextstate] == trans_state);
513  // or probably an error in MakePrecedingInputSymbolsSame.
514  }
515  }
516  }
517 
518  KALDI_ASSERT(state_in[fst->Start()] == kNoStateId || state_in[fst->Start()] == 0);
519  // or MakePrecedingInputSymbolsSame failed.
520 
521  // The next loop looks at each graph state, adds the self-loop [if needed] and
522  // multiples all the out-transitions' probs (and final-prob) by the
523  // forward-prob for that state (which is one minus self-loop-prob). We do it
524  // like this to maintain stochasticity (i.e. rather than multiplying the arcs
525  // with the corresponding labels on them by this probability).
526 
527  for (StateId s = 0; s < static_cast<StateId>(state_in.size()); s++) {
528  if (state_in[s] > 0) { // defined, and not eps or a disambiguation symbol or a
529  // nonterminal-related sybol for grammar decoding...
530  int32 trans_state = static_cast<int32>(state_in[s]);
531  // First multiply all probabilities by "forward" probability.
532  BaseFloat log_prob = trans_model.GetNonSelfLoopLogProb(trans_state);
533  fst->SetFinal(s, Times(fst->Final(s), Weight(-log_prob*self_loop_scale)));
534  for (MutableArcIterator<MutableFst<Arc> > aiter(fst, s);
535  !aiter.Done();
536  aiter.Next()) {
537  Arc arc = aiter.Value();
538  arc.weight = Times(arc.weight, Weight(-log_prob*self_loop_scale));
539  aiter.SetValue(arc);
540  }
541  // Now add self-loop, if needed.
542  int32 trans_id = trans_model.SelfLoopOf(trans_state);
543  if (trans_id != 0) { // has self-loop.
544  BaseFloat log_prob = trans_model.GetTransitionLogProb(trans_id);
545  fst->AddArc(s, Arc(trans_id, 0, Weight(-log_prob*self_loop_scale), s));
546  }
547  }
548  }
549 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::StdArc StdArc
kaldi::int32 int32
LatticeWeightTpl< FloatType > Times(const LatticeWeightTpl< FloatType > &w1, const LatticeWeightTpl< FloatType > &w2)
fst::StdArc::Label Label
float BaseFloat
void MakePrecedingInputSymbolsSameClass(bool start_is_epsilon, MutableFst< Arc > *fst, const F &f)
As MakePrecedingInputSymbolsSame, but takes a functor object that maps labels to classes.
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AddToChainFsa()

fst::StdArc::StateId kaldi::AddToChainFsa ( fst::StdMutableFst *  fst,
fst::StdArc::StateId  last_state,
int64  symbol 
)

Definition at line 100 of file arpa-lm-compiler-test.cc.

Referenced by ScoringTest().

102  {
103  fst::StdArc::StateId next_state = fst->AddState();
104  fst->AddArc(last_state, fst::StdArc(symbol, symbol, 0, next_state));
105  return next_state;
106 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::StdArc StdArc

◆ AddToConfusionMatrix()

void kaldi::AddToConfusionMatrix ( int32  phone1,
int32  phone2,
Matrix< double > *  counts 
)

Definition at line 40 of file compare-int-vector.cc.

References KALDI_ERR, kCopyData, MatrixBase< Real >::NumRows(), and Matrix< Real >::Resize().

Referenced by main().

41  {
42  if (phone1 < 0 || phone2 < 0)
43  KALDI_ERR << "Contents of vectors cannot be "
44  "negative if --write-confusion-matrix option is "
45  "provided.";
46  int32 max_size = std::max<int32>(phone1, phone2) + 1;
47  if (counts->NumRows() < max_size)
48  counts->Resize(max_size, max_size, kCopyData);
49  (*counts)(phone1, phone2) += 1.0;
50 }
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ AddToCount()

void kaldi::AddToCount ( int32  location_to_add,
double  value_to_add,
std::vector< double > *  counts 
)

Definition at line 28 of file compare-int-vector.cc.

References KALDI_ERR.

Referenced by main().

30  {
31  if (location_to_add < 0)
32  KALDI_ERR << "Contents of vectors cannot be "
33  "negative if --write-tot-counts or --write-diff-counts "
34  "options are provided.";
35  if (counts->size() <= static_cast<size_t>(location_to_add))
36  counts->resize(location_to_add + 1, 0.0);
37  (*counts)[location_to_add] += value_to_add;
38 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ AddVectorsOfUnequalLength()

void kaldi::AddVectorsOfUnequalLength ( const VectorBase< BaseFloat > &  signal1,
Vector< BaseFloat > *  signal2 
)

Definition at line 31 of file wav-reverberate.cc.

References VectorBase< Real >::Dim(), and VectorBase< Real >::Range().

Referenced by main().

32  {
33  for (int32 po = 0; po < signal2->Dim(); po += signal1.Dim()) {
34  int32 block_length = signal1.Dim();
35  if (signal2->Dim() - po < block_length) block_length = signal2->Dim() - po;
36  signal2->Range(po, block_length).AddVec(1.0, signal1.Range(0, block_length));
37  }
38 }
kaldi::int32 int32
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
SubVector< Real > Range(const MatrixIndexT o, const MatrixIndexT l)
Returns a sub-vector of a vector (a range of elements).
Definition: kaldi-vector.h:94

◆ AddVectorsWithOffset()

void kaldi::AddVectorsWithOffset ( const Vector< BaseFloat > &  signal1,
int32  offset,
Vector< BaseFloat > *  signal2 
)

Definition at line 44 of file wav-reverberate.cc.

References VectorBase< Real >::Dim(), and VectorBase< Real >::Range().

Referenced by AddNoise().

45  {
46  int32 add_length = std::min(signal2->Dim() - offset, signal1.Dim());
47  if (add_length > 0)
48  signal2->Range(offset, add_length).AddVec(1.0, signal1.Range(0, add_length));
49 }
kaldi::int32 int32
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
SubVector< Real > Range(const MatrixIndexT o, const MatrixIndexT l)
Returns a sub-vector of a vector (a range of elements).
Definition: kaldi-vector.h:94

◆ AddWordInsPenToCompactLattice()

void AddWordInsPenToCompactLattice ( BaseFloat  word_ins_penalty,
CompactLattice clat 
)

This function add the word insertion penalty to graph score of each word in the compact lattice.

Definition at line 1181 of file lattice-functions.cc.

References LatticeWeightTpl< FloatType >::SetValue1(), and LatticeWeightTpl< FloatType >::Value1().

Referenced by main().

1182  {
1183  typedef CompactLatticeArc Arc;
1184  int32 num_states = clat->NumStates();
1185 
1186  //scan the lattice
1187  for (int32 state = 0; state < num_states; state++) {
1188  for (fst::MutableArcIterator<CompactLattice> aiter(clat, state);
1189  !aiter.Done(); aiter.Next()) {
1190 
1191  Arc arc(aiter.Value());
1192 
1193  if (arc.ilabel != 0) { // if there is a word on this arc
1194  LatticeWeight weight = arc.weight.Weight();
1195  // add word insertion penalty to lattice
1196  weight.SetValue1( weight.Value1() + word_ins_penalty);
1197  arc.weight.SetWeight(weight);
1198  aiter.SetValue(arc);
1199  }
1200  } // end looping over arcs
1201  } // end looping over states
1202 }
kaldi::int32 int32
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ AgglomerativeCluster()

void AgglomerativeCluster ( const Matrix< BaseFloat > &  costs,
BaseFloat  threshold,
int32  min_clusters,
int32  first_pass_max_points,
BaseFloat  max_cluster_fraction,
std::vector< int32 > *  assignments_out 
)

This is the function that is called to perform the agglomerative clustering.

It takes the following arguments:

  • A matrix of all pairwise costs, with each row/column corresponding to an utterance ID, and the elements of the matrix containing the cost for pairing the utterances for its row and column
  • A threshold which is used as the stopping criterion for the clusters
  • A minimum number of clusters that will not be merged past
  • A maximum fraction of points that can be in a cluster
  • A vector which will be filled with integer IDs corresponding to each of the rows/columns of the score matrix.

The basic algorithm is as follows:

while (num-clusters > min-clusters && smallest-merge-cost <= threshold)
if (size-of-new-cluster <= max-cluster-size)
merge the two clusters with lowest cost

The cost between two clusters is the average cost of all pairwise costs between points across the two clusters.

The algorithm takes advantage of the fact that the sum of the pairwise costs between the points of clusters I and J is equiavlent to the sum of the pairwise costs between cluster I and the parents of cluster J. In other words, the total cost between I and J is the sum of the costs between clusters I and M and clusters I and N, where cluster J was formed by merging clusters M and N.

If the number of points to cluster is larger than first-pass-max-points, then clustering is done in two passes. In the first pass, input points are divided into contiguous subsets of size at most first-pass-max-points and each subset is clustered separately. In the second pass, the first pass clusters are merged into the final set of clusters.

Definition at line 223 of file agglomerative-clustering.cc.

References AgglomerativeClusterer::Cluster(), and KALDI_ASSERT.

Referenced by main().

229  {
230  KALDI_ASSERT(min_clusters >= 0);
231  KALDI_ASSERT(max_cluster_fraction >= 1.0 / min_clusters);
232  AgglomerativeClusterer ac(costs, threshold, min_clusters,
233  first_pass_max_points, max_cluster_fraction,
234  assignments_out);
235  ac.Cluster();
236 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AlignUtteranceWrapper()

void AlignUtteranceWrapper ( const AlignConfig config,
const std::string &  utt,
BaseFloat  acoustic_scale,
fst::VectorFst< fst::StdArc > *  fst,
DecodableInterface decodable,
Int32VectorWriter alignment_writer,
BaseFloatWriter scores_writer,
int32 num_done,
int32 num_error,
int32 num_retried,
double *  tot_like,
int64 *  frame_count,
BaseFloatVectorWriter per_frame_acwt_writer = NULL 
)

AlignUtteranceWapper is a wrapper for alignment code used in training, that is called from many different binaries, e.g.

gmm-align, gmm-align-compiled, sgmm-align, etc. The writers for alignments and words will only be written to if they are open. The num_done, num_error, num_retried, tot_like and frame_count pointers will (if non-NULL) be incremented or added to, not set, by this function.

Definition at line 576 of file decoder-wrappers.cc.

References FasterDecoderOptions::beam, AlignConfig::beam, AlignConfig::careful, FasterDecoder::Decode(), FasterDecoder::GetBestPath(), fst::GetLinearSymbolSequence(), GetPerFrameAcousticCosts(), TableWriter< Holder >::IsOpen(), KALDI_ERR, KALDI_WARN, ModifyGraphForCarefulAlignment(), DecodableInterface::NumFramesReady(), FasterDecoder::ReachedFinal(), AlignConfig::retry_beam, VectorBase< Real >::Scale(), FasterDecoder::SetOptions(), LatticeWeightTpl< FloatType >::Value1(), LatticeWeightTpl< FloatType >::Value2(), words, and TableWriter< Holder >::Write().

Referenced by main(), and AlignConfig::Register().

591  {
592 
593  if ((config.retry_beam != 0 && config.retry_beam <= config.beam) ||
594  config.beam <= 0.0) {
595  KALDI_ERR << "Beams do not make sense: beam " << config.beam
596  << ", retry-beam " << config.retry_beam;
597  }
598 
599  if (fst->Start() == fst::kNoStateId) {
600  KALDI_WARN << "Empty decoding graph for " << utt;
601  if (num_error != NULL) (*num_error)++;
602  return;
603  }
604 
605  if (config.careful)
607 
608  FasterDecoderOptions decode_opts;
609  decode_opts.beam = config.beam;
610 
611  FasterDecoder decoder(*fst, decode_opts);
612  decoder.Decode(decodable);
613 
614  bool ans = decoder.ReachedFinal(); // consider only final states.
615 
616  if (!ans && config.retry_beam != 0.0) {
617  if (num_retried != NULL) (*num_retried)++;
618  KALDI_WARN << "Retrying utterance " << utt << " with beam "
619  << config.retry_beam;
620  decode_opts.beam = config.retry_beam;
621  decoder.SetOptions(decode_opts);
622  decoder.Decode(decodable);
623  ans = decoder.ReachedFinal();
624  }
625 
626  if (!ans) { // Still did not reach final state.
627  KALDI_WARN << "Did not successfully decode file " << utt << ", len = "
628  << decodable->NumFramesReady();
629  if (num_error != NULL) (*num_error)++;
630  return;
631  }
632 
633  fst::VectorFst<LatticeArc> decoded; // linear FST.
634  decoder.GetBestPath(&decoded);
635  if (decoded.NumStates() == 0) {
636  KALDI_WARN << "Error getting best path from decoder (likely a bug)";
637  if (num_error != NULL) (*num_error)++;
638  return;
639  }
640 
641  std::vector<int32> alignment;
642  std::vector<int32> words;
643  LatticeWeight weight;
644 
645  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
646  BaseFloat like = -(weight.Value1()+weight.Value2()) / acoustic_scale;
647 
648  if (num_done != NULL) (*num_done)++;
649  if (tot_like != NULL) (*tot_like) += like;
650  if (frame_count != NULL) (*frame_count) += decodable->NumFramesReady();
651 
652  if (alignment_writer != NULL && alignment_writer->IsOpen())
653  alignment_writer->Write(utt, alignment);
654 
655  if (scores_writer != NULL && scores_writer->IsOpen())
656  scores_writer->Write(utt, -(weight.Value1()+weight.Value2()));
657 
658  Vector<BaseFloat> per_frame_loglikes;
659  if (per_frame_acwt_writer != NULL && per_frame_acwt_writer->IsOpen()) {
660  GetPerFrameAcousticCosts(decoded, &per_frame_loglikes);
661  per_frame_loglikes.Scale(-1 / acoustic_scale);
662  per_frame_acwt_writer->Write(utt, per_frame_loglikes);
663  }
664 }
int32 words[kMaxOrder]
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
void GetPerFrameAcousticCosts(const Lattice &nbest, Vector< BaseFloat > *per_frame_loglikes)
This function extracts the per-frame log likelihoods from a linear lattice (which we refer to as an &#39;...
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
void ModifyGraphForCarefulAlignment(fst::VectorFst< fst::StdArc > *fst)
This function modifies the decoding graph for what we call "careful alignment".
LatticeWeightTpl< BaseFloat > LatticeWeight

◆ AppendFeats()

bool kaldi::AppendFeats ( const std::vector< Matrix< BaseFloat > > &  in,
const std::string &  utt,
int32  tolerance,
Matrix< BaseFloat > *  out 
)

Definition at line 30 of file paste-feats.cc.

References rnnlm::i, KALDI_VLOG, KALDI_WARN, MatrixBase< Real >::Range(), and Matrix< Real >::Resize().

Referenced by main().

33  {
34  // Check the lengths
35  int32 min_len = in[0].NumRows(),
36  max_len = in[0].NumRows(),
37  tot_dim = in[0].NumCols();
38  for (int32 i = 1; i < in.size(); i++) {
39  int32 len = in[i].NumRows(), dim = in[i].NumCols();
40  tot_dim += dim;
41  if(len < min_len) min_len = len;
42  if(len > max_len) max_len = len;
43  }
44  if (max_len - min_len > tolerance || min_len == 0) {
45  KALDI_WARN << "Length mismatch " << max_len << " vs. " << min_len
46  << (utt.empty() ? "" : " for utt ") << utt
47  << " exceeds tolerance " << tolerance;
48  out->Resize(0, 0);
49  return false;
50  }
51  if (max_len - min_len > 0) {
52  KALDI_VLOG(2) << "Length mismatch " << max_len << " vs. " << min_len
53  << (utt.empty() ? "" : " for utt ") << utt
54  << " within tolerance " << tolerance;
55  }
56  out->Resize(min_len, tot_dim);
57  int32 dim_offset = 0;
58  for (int32 i = 0; i < in.size(); i++) {
59  int32 this_dim = in[i].NumCols();
60  out->Range(0, min_len, dim_offset, this_dim).CopyFromMat(
61  in[i].Range(0, min_len, 0, this_dim));
62  dim_offset += this_dim;
63  }
64  return true;
65 }
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
SubMatrix< Real > Range(const MatrixIndexT row_offset, const MatrixIndexT num_rows, const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
Return a sub-part of matrix.
Definition: kaldi-matrix.h:202
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ AppendPostToFeats()

void kaldi::AppendPostToFeats ( const Matrix< BaseFloat > &  in,
const Posterior post,
const int32  post_dim,
Matrix< BaseFloat > *  out 
)

Definition at line 28 of file append-post-to-feats.cc.

References MatrixBase< Real >::ColRange(), KALDI_ASSERT, KALDI_WARN, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), PosteriorToMatrix(), and Matrix< Real >::Resize().

Referenced by main().

31  {
32  // Check inputs,
33  if (in.NumRows() != post.size()) {
34  KALDI_WARN << "Mismatch of length!"
35  << " features: " << in.NumRows()
36  << " posteriors: " << post.size();
37  }
38  KALDI_ASSERT(in.NumRows() == post.size());
39  // Convert post to Matrix,
40  Matrix<BaseFloat> post_mat;
41  PosteriorToMatrix(post, post_dim, &post_mat);
42  // Build the output matrix,
43  out->Resize(in.NumRows(), in.NumCols() + post_dim);
44  out->ColRange(0, in.NumCols()).CopyFromMat(in);
45  out->ColRange(in.NumCols(), post_mat.NumCols()).CopyFromMat(post_mat);
46 }
void PosteriorToMatrix(const Posterior &post, const int32 post_dim, Matrix< Real > *mat)
This converts a Posterior to a Matrix.
Definition: posterior.cc:512
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
SubMatrix< Real > ColRange(const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
Definition: kaldi-matrix.h:213
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ AppendVector()

void kaldi::AppendVector ( const VectorBase< Real > &  src,
Vector< Real > *  dst 
)
inline

Definition at line 1377 of file pitch-functions.cc.

References VectorBase< Real >::Dim(), kCopyData, VectorBase< Real >::Range(), and Vector< Real >::Resize().

1377  {
1378  if (src.Dim() == 0) return;
1379  dst->Resize(dst->Dim() + src.Dim(), kCopyData);
1380  dst->Range(dst->Dim() - src.Dim(), src.Dim()).CopyFromVec(src);
1381 }

◆ AppendVectorToFeats()

void kaldi::AppendVectorToFeats ( const Matrix< BaseFloat > &  in,
const Vector< BaseFloat > &  vec,
Matrix< BaseFloat > *  out 
)

Definition at line 29 of file append-vector-to-feats.cc.

References MatrixBase< Real >::ColRange(), VectorBase< Real >::Dim(), KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and Matrix< Real >::Resize().

Referenced by main().

31  {
32  // Check inputs,
33  KALDI_ASSERT(in.NumRows() != 0);
34  // Build the output matrix,
35  out->Resize(in.NumRows(), in.NumCols() + vec.Dim());
36  out->ColRange(0, in.NumCols()).CopyFromMat(in);
37  out->ColRange(in.NumCols(), vec.Dim()).CopyRowsFromVec(vec);
38 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
SubMatrix< Real > ColRange(const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
Definition: kaldi-matrix.h:213
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ ApplyAffineTransform()

void ApplyAffineTransform ( const MatrixBase< BaseFloat > &  xform,
VectorBase< BaseFloat > *  vec 
)

Applies the affine transform 'xform' to the vector 'vec' and overwrites the contents of 'vec'.

Definition at line 168 of file transform-common.cc.

References VectorBase< Real >::AddMatVec(), VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Dim(), KALDI_ASSERT, kNoTrans, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

Referenced by AffineXformStats::AffineXformStats(), main(), TestOnlineTransform(), UnitTestFmllrDiagGmm(), UnitTestFmllrDiagGmmDiagonal(), UnitTestFmllrDiagGmmOffset(), and UnitTestFmllrRaw().

169  {
170  int32 dim = xform.NumRows();
171  KALDI_ASSERT(dim > 0 && xform.NumCols() == dim+1 && vec->Dim() == dim);
172  Vector<BaseFloat> tmp(dim+1);
173  SubVector<BaseFloat> tmp_part(tmp, 0, dim);
174  tmp_part.CopyFromVec(*vec);
175  tmp(dim) = 1.0;
176  // next line is: vec = 1.0 * xform * tmp + 0.0 * vec
177  vec->AddMatVec(1.0, xform, kNoTrans, tmp, 0.0);
178 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApplyCmvn()

void ApplyCmvn ( const MatrixBase< double > &  stats,
bool  norm_vars,
MatrixBase< BaseFloat > *  feats 
)

Apply cepstral mean and variance normalization to a matrix of features.

If norm_vars == true, expects stats to be of dimension 2 by (dim+1), but if norm_vars == false, will accept stats of dimension 1 by (dim+1); these are produced by the balanced-cmvn code when it computes an offset and represents it as "fake stats".

Definition at line 64 of file cmvn.cc.

References VectorBase< Real >::AddVec(), MatrixBase< Real >::AddVecToRows(), count, rnnlm::d, KALDI_ASSERT, KALDI_ERR, KALDI_WARN, MatrixBase< Real >::MulColsVec(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), MatrixBase< Real >::Row(), and MatrixBase< Real >::RowData().

Referenced by OnlineCmvn::GetFrame(), and main().

66  {
67  KALDI_ASSERT(feats != NULL);
68  int32 dim = stats.NumCols() - 1;
69  if (stats.NumRows() > 2 || stats.NumRows() < 1 || feats->NumCols() != dim) {
70  KALDI_ERR << "Dim mismatch: cmvn "
71  << stats.NumRows() << 'x' << stats.NumCols()
72  << ", feats " << feats->NumRows() << 'x' << feats->NumCols();
73  }
74  if (stats.NumRows() == 1 && var_norm)
75  KALDI_ERR << "You requested variance normalization but no variance stats "
76  << "are supplied.";
77 
78  double count = stats(0, dim);
79  // Do not change the threshold of 1.0 here: in the balanced-cmvn code, when
80  // computing an offset and representing it as stats, we use a count of one.
81  if (count < 1.0)
82  KALDI_ERR << "Insufficient stats for cepstral mean and variance normalization: "
83  << "count = " << count;
84 
85  if (!var_norm) {
86  Vector<BaseFloat> offset(dim);
87  SubVector<double> mean_stats(stats.RowData(0), dim);
88  offset.AddVec(-1.0 / count, mean_stats);
89  feats->AddVecToRows(1.0, offset);
90  return;
91  }
92  // norm(0, d) = mean offset;
93  // norm(1, d) = scale, e.g. x(d) <-- x(d)*norm(1, d) + norm(0, d).
94  Matrix<BaseFloat> norm(2, dim);
95  for (int32 d = 0; d < dim; d++) {
96  double mean, offset, scale;
97  mean = stats(0, d)/count;
98  double var = (stats(1, d)/count) - mean*mean,
99  floor = 1.0e-20;
100  if (var < floor) {
101  KALDI_WARN << "Flooring cepstral variance from " << var << " to "
102  << floor;
103  var = floor;
104  }
105  scale = 1.0 / sqrt(var);
106  if (scale != scale || 1/scale == 0.0)
107  KALDI_ERR << "NaN or infinity in cepstral mean/variance computation";
108  offset = -(mean*scale);
109  norm(0, d) = offset;
110  norm(1, d) = scale;
111  }
112  // Apply the normalization.
113  feats->MulColsVec(norm.Row(1));
114  feats->AddVecToRows(1.0, norm.Row(0));
115 }
kaldi::int32 int32
const size_t count
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApplyCmvnReverse()

void ApplyCmvnReverse ( const MatrixBase< double > &  stats,
bool  norm_vars,
MatrixBase< BaseFloat > *  feats 
)

This is as ApplyCmvn, but does so in the reverse sense, i.e.

applies a transform that would take zero-mean, unit-variance input and turn it into output with the stats of "stats". This can be useful if you trained without CMVN but later want to correct a mismatch, so you would first apply CMVN and then do the "reverse" CMVN with the summed stats of your training data.

Definition at line 117 of file cmvn.cc.

References MatrixBase< Real >::AddVecToRows(), count, rnnlm::d, KALDI_ASSERT, KALDI_ERR, KALDI_WARN, MatrixBase< Real >::MulColsVec(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

Referenced by main().

119  {
120  KALDI_ASSERT(feats != NULL);
121  int32 dim = stats.NumCols() - 1;
122  if (stats.NumRows() > 2 || stats.NumRows() < 1 || feats->NumCols() != dim) {
123  KALDI_ERR << "Dim mismatch: cmvn "
124  << stats.NumRows() << 'x' << stats.NumCols()
125  << ", feats " << feats->NumRows() << 'x' << feats->NumCols();
126  }
127  if (stats.NumRows() == 1 && var_norm)
128  KALDI_ERR << "You requested variance normalization but no variance stats "
129  << "are supplied.";
130 
131  double count = stats(0, dim);
132  // Do not change the threshold of 1.0 here: in the balanced-cmvn code, when
133  // computing an offset and representing it as stats, we use a count of one.
134  if (count < 1.0)
135  KALDI_ERR << "Insufficient stats for cepstral mean and variance normalization: "
136  << "count = " << count;
137 
138  Matrix<BaseFloat> norm(2, dim); // norm(0, d) = mean offset
139  // norm(1, d) = scale, e.g. x(d) <-- x(d)*norm(1, d) + norm(0, d).
140  for (int32 d = 0; d < dim; d++) {
141  double mean, offset, scale;
142  mean = stats(0, d) / count;
143  if (!var_norm) {
144  scale = 1.0;
145  offset = mean;
146  } else {
147  double var = (stats(1, d)/count) - mean*mean,
148  floor = 1.0e-20;
149  if (var < floor) {
150  KALDI_WARN << "Flooring cepstral variance from " << var << " to "
151  << floor;
152  var = floor;
153  }
154  // we aim to transform zero-mean, unit-variance input into data
155  // with the given mean and variance.
156  scale = sqrt(var);
157  offset = mean;
158  }
159  norm(0, d) = offset;
160  norm(1, d) = scale;
161  }
162  if (var_norm)
163  feats->MulColsVec(norm.Row(1));
164  feats->AddVecToRows(1.0, norm.Row(0));
165 }
kaldi::int32 int32
const size_t count
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApplyFeatureTransformToStats()

void ApplyFeatureTransformToStats ( const MatrixBase< BaseFloat > &  xform,
AffineXformStats stats 
)

This function applies a feature-level transform to stats (useful for certain techniques based on fMLLR).

Assumes the stats are of the standard diagonal sort. The transform "xform" may be either dim x dim (linear), dim x dim+1 (affine), or dim+1 x dim+1 (affine with the last row equal to 0 0 0 .. 0 1).

Definition at line 381 of file fmllr-diag-gmm.cc.

References SpMatrix< Real >::AddMat2Sp(), MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::CopyFromMat(), AffineXformStats::Dim(), AffineXformStats::G_, rnnlm::i, AffineXformStats::K_, KALDI_ASSERT, kNoTrans, kTrans, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

Referenced by ComputeFmllrLogDet(), LinearVtln::ComputeTransform(), and UnitTestFmllrDiagGmm().

382  {
383  KALDI_ASSERT(stats != NULL && stats->Dim() != 0);
384  int32 dim = stats->Dim();
385  // make sure the stats are of the standard diagonal kind.
386  KALDI_ASSERT(stats->G_.size() == static_cast<size_t>(dim));
387  KALDI_ASSERT( (xform.NumRows() == dim && xform.NumCols() == dim) // linear
388  || (xform.NumRows() == dim && xform.NumCols() == dim+1) // affine
389  || (xform.NumRows() == dim+1 && xform.NumCols() == dim+1)); // affine w/ extra row.
390  if (xform.NumRows() == dim+1) { // check last row of input
391  // has correct value. 0 0 0 .. 0 1.
392  for (int32 i = 0; i < dim; i++)
393  KALDI_ASSERT(xform(dim, i) == 0.0);
394  KALDI_ASSERT(xform(dim, dim) == 1.0);
395  }
396 
397  // Get the transform into the (dim+1 x dim+1) format, with
398  // 0 0 0 .. 0 1 as the last row.
399  SubMatrix<BaseFloat> xform_square(xform, 0, dim, 0, dim);
400  Matrix<double> xform_full(dim+1, dim+1);
401  SubMatrix<double> xform_full_square(xform_full, 0, dim, 0, dim);
402  xform_full_square.CopyFromMat(xform_square);
403  if (xform.NumCols() == dim+1) // copy offset.
404  for (int32 i = 0; i < dim; i++)
405  xform_full(i, dim) = xform(i, dim);
406 
407  xform_full(dim, dim) = 1.0;
408 
409  SpMatrix<double> Gtmp(dim+1);
410  for (int32 i = 0; i < dim; i++) {
411  // Gtmp <-- xform_full * stats->G_[i] * xform_full^T
412  Gtmp.AddMat2Sp(1.0, xform_full, kNoTrans, stats->G_[i], 0.0);
413  stats->G_[i].CopyFromSp(Gtmp);
414  }
415  Matrix<double> Ktmp(dim, dim+1);
416  // Ktmp <-- stats->K_ * xform_full^T
417  Ktmp.AddMatMat(1.0, stats->K_, kNoTrans, xform_full, kTrans, 0.0);
418  stats->K_.CopyFromMat(Ktmp);
419 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApplyHessianXformToGradient()

static void kaldi::ApplyHessianXformToGradient ( const Sgmm2FmllrGlobalParams globals,
const Matrix< BaseFloat > &  gradient_in,
Matrix< BaseFloat > *  gradient_out 
)
static

Definition at line 59 of file fmllr-sgmm2.cc.

References KALDI_ERR, Sgmm2FmllrGlobalParams::mean_scatter_, VectorBase< Real >::Min(), and MatrixBase< Real >::NumRows().

Referenced by FmllrSgmm2Accs::AccumulateForFmllrSubspace(), and FmllrSgmm2Accs::Update().

61  {
62  int32 dim = gradient_in.NumRows();
63  const Vector<BaseFloat> &D = globals.mean_scatter_;
64  if (D.Min() <= 0.0)
65  KALDI_ERR << "Cannot estimate FMLLR: mean scatter has 0 eigenvalues.";
66  for (int32 r = 0; r < dim; r++) {
67  for (int32 c = 0; c < r; c++) {
68  // Eq. (B.15)
69  (*gradient_out)(r, c) = gradient_in(r, c) / std::sqrt(1 + D(c));
70  // Eq. (B.16)
71  (*gradient_out)(c, r) = gradient_in(c, r) / std::sqrt(1 + D(r) -
72  1 / (1 + D(c))) - gradient_in(r, c) / ((1 + D(c)) *
73  std::sqrt(1 + D(r) - 1 / (1 + D(c))));
74  }
75  // Eq. (B.17) & (B.18)
76  (*gradient_out)(r, r) = gradient_in(r, r) / std::sqrt(2 + D(r));
77  (*gradient_out)(r, dim) = gradient_in(r, dim);
78  }
79 }
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ApplyInvHessianXformToChange()

static void kaldi::ApplyInvHessianXformToChange ( const Sgmm2FmllrGlobalParams globals,
const Matrix< BaseFloat > &  delta_in,
Matrix< BaseFloat > *  delta_out 
)
static

Definition at line 81 of file fmllr-sgmm2.cc.

References KALDI_ERR, Sgmm2FmllrGlobalParams::mean_scatter_, VectorBase< Real >::Min(), and MatrixBase< Real >::NumRows().

Referenced by FmllrSgmm2Accs::Update().

83  {
84  int32 dim = delta_in.NumRows();
85  const Vector<BaseFloat> &D = globals.mean_scatter_;
86  if (D.Min() <= 0.0)
87  KALDI_ERR << "Cannot estimate FMLLR: mean scatter has 0 eigenvalues.";
88  for (int32 r = 0; r < dim; r++) {
89  for (int32 c = 0; c < r; c++) {
90  // Eq. (B.21)
91  (*delta_out)(r, c) = delta_in(r, c) / std::sqrt(1 + D(c)) -
92  delta_in(c, r) / ((1 + D(c)) * std::sqrt(1 + D(r) - 1 / (1 + D(c))));
93  // Eq. (B.22)
94  (*delta_out)(c, r) = delta_in(c, r) / std::sqrt(1 + D(r) - 1/ (1 + D(c)));
95  }
96  // Eq. (B.23) & (B.24)
97  (*delta_out)(r, r) = delta_in(r, r) / std::sqrt(2 + D(r));
98  (*delta_out)(r, dim) = delta_in(r, dim);
99  }
100 }
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ApplyInvPreXformToChange()

static void kaldi::ApplyInvPreXformToChange ( const Sgmm2FmllrGlobalParams globals,
const Matrix< BaseFloat > &  delta_in,
Matrix< BaseFloat > *  delta_out 
)
static

Definition at line 45 of file fmllr-sgmm2.cc.

References MatrixBase< Real >::AddMatMat(), Sgmm2FmllrGlobalParams::inv_xform_, kNoTrans, kSetZero, kUndefined, MatrixBase< Real >::NumRows(), Sgmm2FmllrGlobalParams::pre_xform_, and MatrixBase< Real >::Range().

Referenced by FmllrSgmm2Accs::Update().

47  {
48  // Eq. (B.25): \Delta = A_{inv} \Delta' W_{pre}^+
49  int32 dim = delta_in.NumRows();
50  Matrix<BaseFloat> Wpre_plus(dim + 1, dim + 1, kSetZero);
51  Wpre_plus.Range(0, dim, 0, dim + 1).CopyFromMat(globals.pre_xform_);
52  Wpre_plus(dim, dim) = 1;
53  SubMatrix<BaseFloat> Ainv(globals.inv_xform_, 0, dim, 0, dim);
54  Matrix<BaseFloat> AinvD(dim, dim + 1, kUndefined);
55  AinvD.AddMatMat(1.0, Ainv, kNoTrans, delta_in, kNoTrans, 0.0);
56  delta_out->AddMatMat(1.0, AinvD, kNoTrans, Wpre_plus, kNoTrans, 0.0);
57 }
kaldi::int32 int32
void AddMatMat(const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ApplyModelTransformToStats()

void ApplyModelTransformToStats ( const MatrixBase< BaseFloat > &  xform,
AffineXformStats stats 
)

ApplyModelTransformToStats takes a transform "xform", which must be diagonal (i.e.

of the form T = [ D; b ] where D is diagonal), and applies it to the stats as if we had made it a model-space transform (note that the transform applied to the model means is the inverse transform of T). Thus, if we are estimating a transform T U, and we get stats valid for estimating T U and we estimate T, we can then call this function (treating T as a model-space transform) and will get stats valid for estimating U. This only works if T is diagonal, because otherwise the standard stats format is not valid. xform must be of dimension d x d+1

Definition at line 421 of file fmllr-diag-gmm.cc.

References AffineXformStats::Dim(), AffineXformStats::G_, rnnlm::i, MatrixBase< Real >::IsDiagonal(), rnnlm::j, AffineXformStats::K_, KALDI_ASSERT, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

Referenced by ComputeFmllrLogDet(), UnitTestFmllrDiagGmmDiagonal(), and UnitTestFmllrDiagGmmOffset().

422  {
423  KALDI_ASSERT(stats != NULL && stats->Dim() != 0.0);
424  int32 dim = stats->Dim();
425  KALDI_ASSERT(xform.NumRows() == dim && xform.NumCols() == dim+1);
426  {
427  SubMatrix<BaseFloat> xform_square(xform, 0, dim, 0, dim);
428  // Only works with diagonal transforms.
429  KALDI_ASSERT(xform_square.IsDiagonal());
430  }
431 
432  // Working out rules for transforming fMLLR statistics under diagonal
433  // model-space transformations.
434  //
435  // We work out what the stats would be if we had accumulated
436  // with offset/scaled means and vars. Let T be the transform
437  // T = [ D; b ],
438  // where D is diagonal, d_i is the i'th diagonal of D, and b_i
439  // is the i'th offset element. This is equivalent to the transform
440  // x_i -> y_i = d_i x_i + b_i,
441  // so d_i is the diagonal and b_i is the offset term. We work out the
442  // reverse feature transform (from general to speaker-specific space),
443  // which is
444  // y_i -> x_i = (y_i - b_i) / d_i
445  // the corresponding mean transform to speaker-space is the same:
446  // mu_i -> (mu_i - b_i) / d_i
447  // and the transfrom on the variances is:
448  // sigma_i^2 -> sigma_i^2 / d_i^2,
449  // so on inverse variance this becomes:
450  // (1/sigma_i^2) -> (1/sigma_i^2) * d_i^2.
451  //
452  // Now, we work out the change in K and G_i from these effects on the
453  // means and variances.
454  //
455  // Now, k_{ij} is \sum_{m, t} \gamma_m (1/\sigma^2_{m, i}) \mu_{m, i} x^+_j .
456  //
457  // If we are transforming to K', we want:
458  //
459  // k'_{ij} = \sum_{m, t} \gamma_m (d_i^2/\sigma^2_{m, i}) ((\mu_{m, i} - b_i)/d_i) x^+_j .
460  // = d_i k_{i, j} - \sum_{m, t} \gamma_m (1/\sigma^2_{m, i}) d_i b_i x^+_j .
461  // = d_i k_{i, j} - d_i b_i g_{i, d, j},
462  // where g_{i, d, j} is the {d, j}'th element of G_i. (in zero-based indexing).
463  //
464  //
465  // G_i only depends on the variances and features, so the only change
466  // in G_i is G_i -> d_i^2 G_i (this comes from the change in 1/sigma_i^2).
467  // This is done after the change in K.
468 
469  for (int32 i = 0; i < dim; i++) {
470  BaseFloat d_i = xform(i, i), b_i = xform(i, dim);
471  for (int32 j = 0; j <= dim; j++) {
472  stats->K_(i, j) = d_i * stats->K_(i, j) - d_i * b_i * stats->G_[i](dim, j);
473  }
474  }
475  for (int32 i = 0; i < dim; i++) {
476  BaseFloat d_i = xform(i, i);
477  stats->G_[i].Scale(d_i * d_i);
478  }
479 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApplyPca()

void kaldi::ApplyPca ( const Matrix< BaseFloat > &  ivectors_in,
const Matrix< BaseFloat > &  pca_mat,
Matrix< BaseFloat > *  ivectors_out 
)

Definition at line 101 of file ivector-plda-scoring-dense.cc.

References MatrixBase< Real >::AddMatMat(), KALDI_ASSERT, kNoTrans, kTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and Matrix< Real >::Resize().

Referenced by main().

102  {
103  int32 transform_cols = pca_mat.NumCols(),
104  transform_rows = pca_mat.NumRows(),
105  feat_dim = ivectors_in.NumCols();
106  ivectors_out->Resize(ivectors_in.NumRows(), transform_rows);
107  KALDI_ASSERT(transform_cols == feat_dim);
108  ivectors_out->AddMatMat(1.0, ivectors_in, kNoTrans,
109  pca_mat, kTrans, 0.0);
110 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
void AddMatMat(const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ ApplyPreXformToGradient()

static void kaldi::ApplyPreXformToGradient ( const Sgmm2FmllrGlobalParams globals,
const Matrix< BaseFloat > &  gradient_in,
Matrix< BaseFloat > *  gradient_out 
)
static

Definition at line 31 of file fmllr-sgmm2.cc.

References MatrixBase< Real >::AddMatMat(), Sgmm2FmllrGlobalParams::inv_xform_, kNoTrans, kSetZero, kTrans, kUndefined, MatrixBase< Real >::NumRows(), Sgmm2FmllrGlobalParams::pre_xform_, and MatrixBase< Real >::Range().

Referenced by FmllrSgmm2Accs::AccumulateForFmllrSubspace(), and FmllrSgmm2Accs::Update().

33  {
34  // Eq. (B.14): P' = A_{inv}^T P {W_{pre}^+}^T
35  int32 dim = gradient_in.NumRows();
36  Matrix<BaseFloat> Wpre_plus(dim + 1, dim + 1, kSetZero);
37  Wpre_plus.Range(0, dim, 0, dim + 1).CopyFromMat(globals.pre_xform_);
38  Wpre_plus(dim, dim) = 1;
39  SubMatrix<BaseFloat> Ainv(globals.inv_xform_, 0, dim, 0, dim);
40  Matrix<BaseFloat> AinvP(dim, dim + 1, kUndefined);
41  AinvP.AddMatMat(1.0, Ainv, kTrans, gradient_in, kNoTrans, 0.0);
42  gradient_out->AddMatMat(1.0, AinvP, kNoTrans, Wpre_plus, kTrans, 0.0);
43 }
kaldi::int32 int32
void AddMatMat(const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ApplySoftMaxPerRow()

void kaldi::ApplySoftMaxPerRow ( MatrixBase< BaseFloat > *  mat)

Definition at line 27 of file copy-matrix.cc.

References rnnlm::i, MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

Referenced by main().

27  {
28  for (int32 i = 0; i < mat->NumRows(); i++) {
29  mat->Row(i).ApplySoftMax();
30  }
31 }
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ approx_equal()

static bool kaldi::approx_equal ( Real  a,
Real  b 
)
static

Definition at line 3323 of file matrix-lib-test.cc.

Referenced by UnitTestTrace().

3323  {
3324  return ( std::abs(a-b) <= 1.0e-03 * (std::abs(a)+std::abs(b)));
3325 }

◆ ApproxEqual() [1/6]

static bool kaldi::ApproxEqual ( const CuBlockMatrix< Real > &  A,
const CuBlockMatrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 35 of file cu-block-matrix-test.cc.

37  {
38  CuMatrix<Real> Acopy(A), Bcopy(B);
39  return Acopy.ApproxEqual(Bcopy, tol);
40 }
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71

◆ ApproxEqual() [2/6]

static bool kaldi::ApproxEqual ( const PackedMatrix< Real > &  A,
const PackedMatrix< Real > &  B,
Real  tol = 0.001 
)
static

Definition at line 100 of file cu-packed-matrix-test.cc.

References rnnlm::d, KALDI_ASSERT, PackedMatrix< Real >::Max(), PackedMatrix< Real >::Min(), and PackedMatrix< Real >::NumRows().

101  {
102  KALDI_ASSERT(A.NumRows() == B.NumRows());
103  PackedMatrix<Real> diff(A);
104  diff.AddPacked(1.0, B);
105  Real a = std::max(A.Max(), -A.Min()), b = std::max(B.Max(), -B.Min()),
106  d = std::max(diff.Max(), -diff.Min());
107  return (d <= tol * std::max(a, b));
108 }
MatrixIndexT NumRows() const
Packed matrix: base class for triangular and symmetric matrices.
Definition: matrix-common.h:64
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ApproxEqual() [3/6]

bool kaldi::ApproxEqual ( const CuSpMatrix< Real > &  A,
const CuSpMatrix< Real > &  B,
Real  tol = 0.001 
)
inline

Definition at line 141 of file cu-sp-matrix.h.

142  {
143  return A.ApproxEqual(B, tol);
144 }

◆ ApproxEqual() [4/6]

static bool kaldi::ApproxEqual ( float  a,
float  b,
float  relative_tolerance = 0.001 
)
inlinestatic

return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).

Definition at line 265 of file kaldi-math.h.

Referenced by AssertEqual(), MleAmSgmm2Accs::Check(), ComputeFmllrMatrixDiagGmmFull(), ComputeLatticeAlphasAndBetas(), CreateEigenvalueMatrix(), CuVectorUnitTestNorm(), CuVectorUnitTestScale(), DecisionTreeSplitter::DoSplitInternal(), EstPca(), kaldi::nnet3::ExampleApproxEqual(), FindBestSplitForKey(), LatticeForwardBackward(), LatticeForwardBackwardMpeVariants(), AmSgmm2::LogLikelihood(), main(), FullGmm::Merge(), DiagGmm::Merge(), FullGmm::MergePreselect(), NnetIo::operator==(), OnlinePreconditioner::PreconditionDirectionsInternal(), KlHmm::PropagateFnc(), MultiBasisComponent::PropagateFnc(), LatticeSimpleDecoder::PruneForwardLinksFinal(), LatticeFasterDecoderTpl< fst::StdFst, decoder::BackpointerToken >::PruneForwardLinksFinal(), LatticeBiglmFasterDecoder::PruneForwardLinksFinal(), LatticeIncrementalDecoderTpl< FST, decoder::BackpointerToken >::PruneForwardLinksFinal(), OnlinePitchFeatureImpl::RecomputeBacktraces(), ScoringTest(), TestCuMatrixCompObjfAndDeriv(), kaldi::nnet3::time_height_convolution::TestDataBackprop(), kaldi::nnet3::TestNnetComponentVectorizeUnVectorize(), kaldi::nnet3::time_height_convolution::TestParamsBackprop(), TestPushCompactLatticeWeights(), kaldi::nnet3::TestSimpleComponentDataDerivative(), kaldi::nnet3::TestSimpleComponentModelDerivative(), UnitTestApproxEqual(), UnitTestComplexFft2(), UnitTestCompressedMatrix2(), UnitTestCuBlockMatrixAddMatMat(), UnitTestCuDiffLogSoftmax(), UnitTestCuDiffSigmoid(), UnitTestCuDiffSoftmax(), UnitTestCuDiffTanh(), UnitTestCuDiffXent(), UnitTestCuLogSoftmax(), UnitTestCuMatrixAdd(), UnitTestCuMatrixAdd2(), UnitTestCuMatrixAddCols(), UnitTestCuMatrixAddDiagVecMat(), UnitTestCuMatrixAddElements(), UnitTestCuMatrixAddMat(), UnitTestCuMatrixAddMatBlocks1(), UnitTestCuMatrixAddMatBlocks1Trans(), UnitTestCuMatrixAddMatBlocks2(), UnitTestCuMatrixAddMatDiagVec(), UnitTestCuMatrixAddMatMat(), UnitTestCuMatrixAddMatMatBatched(), UnitTestCuMatrixAddMatMatElements(), UnitTestCuMatrixAddRowRanges(), UnitTestCuMatrixAddRows(), UnitTestCuMatrixAddToDiag(), UnitTestCuMatrixAddToElements(), UnitTestCuMatrixAddToRows(), UnitTestCuMatrixAddVecToCols(), UnitTestCuMatrixAddVecToRows(), UnitTestCuMatrixAddVecVec(), UnitTestCuMatrixApplyCeiling(), UnitTestCuMatrixApplyExp(), UnitTestCuMatrixApplyExpLimited(), UnitTestCuMatrixApplyExpSpecial(), UnitTestCuMatrixApplyFloor(), UnitTestCuMatrixApplyHeaviside(), UnitTestCuMatrixApplyLog(), UnitTestCuMatrixApplyPow(), UnitTestCuMatrixApplyPowAbs(), UnitTestCuMatrixCopyCols(), UnitTestCuMatrixCopyColsFromVec(), UnitTestCuMatrixCopyCross(), UnitTestCuMatrixCopyCross2(), UnitTestCuMatrixCopyRows(), UnitTestCuMatrixCopyRowsFromVec(), UnitTestCuMatrixCopyToRows(), UnitTestCuMatrixDiffGroupPnorm(), UnitTestCuMatrixDivElements(), UnitTestCuMatrixDivRowsVec(), UnitTestCuMatrixGroupMax(), UnitTestCuMatrixGroupMaxDeriv(), UnitTestCuMatrixGroupPnorm(), UnitTestCuMatrixHeaviside(), UnitTestCuMatrixInvertElements(), UnitTestCuMatrixIO(), UnitTestCuMatrixMax(), UnitTestCuMatrixMin(), UnitTestCuMatrixMulColsVec(), UnitTestCuMatrixMulElements(), UnitTestCuMatrixMulRows(), UnitTestCuMatrixMulRowsGroupMat(), UnitTestCuMatrixMulRowsVec(), UnitTestCuMatrixObjfDeriv(), UnitTestCuMatrixReduceMax(), UnitTestCuMatrixReduceMin(), UnitTestCuMatrixReduceSum(), UnitTestCuMatrixScale(), UnitTestCuMatrixSet(), UnitTestCuMatrixSetMatMatDivMat(), UnitTestCuMatrixSetRandn(), UnitTestCuMatrixSigmoid(), UnitTestCuMatrixSoftHinge(), UnitTestCuMatrixSumColumnRanges(), UnitTestCuMatrixSymAddMat2(), UnitTestCuMatrixSymInvertPosDef(), UnitTestCuMatrixTraceMatMat(), UnitTestCuMatrixTranspose(), UnitTestCuSigmoid(), UnitTestCuSoftmax(), UnitTestCuSpMatrixCopyFromMat(), UnitTestCuSpMatrixTraceSpSp(), UnitTestCuTanh(), UnitTestCuVectorAddColSumMat(), UnitTestCuVectorAddColSumMatLarge(), UnitTestCuVectorAddRowSumMat(), UnitTestCuVectorAddRowSumMatLarge(), UnitTestCuVectorAddTpVec(), UnitTestCuVectorAddVec(), UnitTestCuVectorInvertElements(), UnitTestCuVectorMulTp(), UnitTestCuVectorSum(), UnitTestDelay(), UnitTestEstimateDiagGmm(), UnitTestEstimateFullGmm(), UnitTestFmllrDiagGmm(), UnitTestFmllrDiagGmmDiagonal(), UnitTestFmllrDiagGmmOffset(), UnitTestLinearResample(), UnitTestLstmNonlinearity(), kaldi::nnet3::UnitTestNnetCompute(), kaldi::nnet2::UnitTestNnetDecodable(), kaldi::nnet3::UnitTestNnetInputDerivatives(), kaldi::nnet3::UnitTestNnetModelDerivatives(), kaldi::nnet3::UnitTestNnetOptimizeWithOptions(), UnitTestNorm(), UnitTestPieces(), UnitTestPosteriors(), UnitTestRange(), UnitTestReadConfig(), UnitTestSnipEdges(), UnitTestSplitRadixComplexFft2(), UnitTestSwapCu2Cu(), UnitTestSwapCu2M(), UnitTestTableRandomBothDouble(), UnitTestTableSequentialBaseFloatVectorBoth(), UnitTestTableSequentialDouble(), UnitTestTableSequentialDoubleBoth(), UnitTestTableSequentialDoubleMatrixBoth(), UnitTextCuMatrixAddMatSmat(), UnitTextCuMatrixAddSmat(), UnitTextCuMatrixAddSmatMat(), IvectorExtractorStats::UpdatePrior(), and MleSgmm2SpeakerAccs::UpdateWithU().

266  {
267  // a==b handles infinities.
268  if (a == b) return true;
269  float diff = std::abs(a-b);
270  if (diff == std::numeric_limits<float>::infinity()
271  || diff != diff) return false; // diff is +inf or nan.
272  return (diff <= relative_tolerance*(std::abs(a)+std::abs(b)));
273 }

◆ ApproxEqual() [5/6]

bool kaldi::ApproxEqual ( const CuVectorBase< Real > &  a,
const CuVectorBase< Real > &  b,
Real  tol = 0.01 
)

Definition at line 364 of file cu-vector.h.

365  {
366  return a.ApproxEqual(b, tol);
367 }

◆ ApproxEqual() [6/6]

bool kaldi::ApproxEqual ( const CuMatrixBase< Real > &  A,
const CuMatrixBase< Real > &  B,
Real  tol = 0.01 
)

Definition at line 937 of file cu-matrix.h.

938  {
939  return A.ApproxEqual(B, tol);
940 }

◆ AssertDiagEqual() [1/2]

static void kaldi::AssertDiagEqual ( const PackedMatrix< Real > &  A,
const CuPackedMatrix< Real > &  B,
float  value,
float  tol = 0.001 
)
static

Definition at line 68 of file cu-packed-matrix-test.cc.

References rnnlm::i, KALDI_ASSERT, and PackedMatrix< Real >::NumRows().

Referenced by UnitTestCuPackedMatrixAddToDiag().

71  {
72  for (MatrixIndexT i = 0; i < A.NumRows(); i++) {
73  KALDI_ASSERT(std::abs((A(i, i)+value) - B(i, i))
74  < tol * std::max(1.0, (double) (std::abs(A(i, i)) + std::abs(B(i, i) + value))));
75  }
76 }
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertDiagEqual() [2/2]

static void kaldi::AssertDiagEqual ( const PackedMatrix< Real > &  A,
const PackedMatrix< Real > &  B,
float  value,
float  tol = 0.001 
)
static

Definition at line 78 of file cu-packed-matrix-test.cc.

References rnnlm::i, KALDI_ASSERT, and PackedMatrix< Real >::NumRows().

81  {
82  for (MatrixIndexT i = 0; i < A.NumRows(); i++) {
83  KALDI_ASSERT(std::abs((A(i, i)+value) - B(i, i))
84  < tol * std::max(1.0, (double) (std::abs(A(i, i)) + std::abs(B(i, i) + value))));
85  }
86 }
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [1/12]

void kaldi::AssertEqual ( const std::vector< T > &  vec1,
const std::vector< T > &  vec2 
)

Definition at line 36 of file cu-array-test.cc.

References rnnlm::i, and KALDI_ASSERT.

37  {
38  // use this instead of "vec1 == vec2" because
39  // for doubles and floats, this can fail if we
40  // have NaNs, even if identical.
41  KALDI_ASSERT(vec1.size() == vec2.size());
42  if (vec1.size() > 0) {
43  const char *p1 = reinterpret_cast<const char*>(&(vec1[0]));
44  const char *p2 = reinterpret_cast<const char*>(&(vec2[0]));
45  size_t size = sizeof(T) * vec1.size();
46  for (size_t i = 0; i < size; i++)
47  KALDI_ASSERT(p1[i] == p2[i]);
48  }
49 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [2/12]

static void kaldi::AssertEqual ( const CuPackedMatrix< Real > &  A,
const CuPackedMatrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 41 of file cu-tp-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, and CuPackedMatrix< Real >::NumRows().

43  {
44  KALDI_ASSERT(A.NumRows() == B.NumRows());
45  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
46  for (MatrixIndexT j = 0; j <= i; j++)
47  KALDI_ASSERT(std::abs(A(i, j) - B(i, j))
48  < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j)))));
49 }
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [3/12]

static void kaldi::AssertEqual ( const CuPackedMatrix< Real > &  A,
const CuPackedMatrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 46 of file cu-packed-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, and CuPackedMatrix< Real >::NumRows().

48  {
49  KALDI_ASSERT(A.NumRows() == B.NumRows());
50  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
51  for (MatrixIndexT j = 0; j <= i; j++)
52  KALDI_ASSERT(std::abs(A(i, j) - B(i, j))
53  < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j)))));
54 }
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [4/12]

static void kaldi::AssertEqual ( const PackedMatrix< Real > &  A,
const PackedMatrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 52 of file cu-tp-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, and PackedMatrix< Real >::NumRows().

54  {
55  KALDI_ASSERT(A.NumRows() == B.NumRows());
56  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
57  for (MatrixIndexT j = 0; j <= i; j++)
58  KALDI_ASSERT(std::abs(A(i, j) - B(i, j))
59  < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j)))));
60 }
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [5/12]

static void kaldi::AssertEqual ( const PackedMatrix< Real > &  A,
const PackedMatrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 57 of file cu-packed-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, and PackedMatrix< Real >::NumRows().

59  {
60  KALDI_ASSERT(A.NumRows() == B.NumRows());
61  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
62  for (MatrixIndexT j = 0; j <= i; j++)
63  KALDI_ASSERT(std::abs(A(i, j) - B(i, j))
64  < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j)))));
65 }
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [6/12]

static void kaldi::AssertEqual ( const PackedMatrix< Real > &  A,
const CuPackedMatrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 63 of file cu-tp-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, PackedMatrix< Real >::NumRows(), and CuPackedMatrix< Real >::NumRows().

65  {
66  KALDI_ASSERT(A.NumRows() == B.NumRows());
67  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
68  for (MatrixIndexT j = 0; j <= i; j++)
69  KALDI_ASSERT(std::abs(A(i, j) - B(i, j))
70  < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j)))));
71 }
MatrixIndexT NumRows() const
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [7/12]

static void kaldi::AssertEqual ( const Matrix< Real > &  A,
const Matrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 69 of file online-feat-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

71  {
72  KALDI_ASSERT(A.NumRows() == B.NumRows()&&A.NumCols() == B.NumCols());
73  for (MatrixIndexT i = 0;i < A.NumRows();i++)
74  for (MatrixIndexT j = 0;j < A.NumCols();j++) {
75  KALDI_ASSERT(std::abs(A(i, j)-B(i, j)) < tol*std::max(1.0, (double) (std::abs(A(i, j))+std::abs(B(i, j)))));
76  }
77 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ AssertEqual() [8/12]

static void kaldi::AssertEqual ( const PackedMatrix< Real > &  A,
const CuPackedMatrix< Real > &  B,
float  tol = 0.001 
)
static

Definition at line 89 of file cu-packed-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, PackedMatrix< Real >::NumRows(), and CuPackedMatrix< Real >::NumRows().

91  {
92  KALDI_ASSERT(A.NumRows() == B.NumRows());
93  for (MatrixIndexT i = 0; i < A.NumRows(); i++)
94  for (MatrixIndexT j = 0; j <= i; j++)
95  KALDI_ASSERT(std::abs(A(i, j) - B(i, j))
96  < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j)))));
97 }
MatrixIndexT NumRows() const
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [9/12]

void kaldi::AssertEqual ( const CuSpMatrix< Real > &  A,
const CuSpMatrix< Real > &  B,
Real  tol = 0.001 
)
inline

Definition at line 147 of file cu-sp-matrix.h.

References CuSpMatrix< Real >::ApproxEqual(), and KALDI_ASSERT.

148  {
149  KALDI_ASSERT(ApproxEqual(A, B, tol));
150 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool ApproxEqual(const CuSpMatrix< Real > &A, const CuSpMatrix< Real > &B, Real tol=0.001)
Definition: cu-sp-matrix.h:141

◆ AssertEqual() [10/12]

static void kaldi::AssertEqual ( float  a,
float  b,
float  relative_tolerance = 0.001 
)
inlinestatic

assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))

Definition at line 276 of file kaldi-math.h.

References ApproxEqual(), KALDI_ASSERT, rnnlm::n, and RoundUpToNearestPowerOfTwo().

Referenced by AddToClustersOptimized(), CholeskyUnitTestTr(), CuCompressedMatrixTestSign(), CuVectorUnitTestAddColSumMat(), CuVectorUnitTestAddDiagMat2(), CuVectorUnitTestAddDiagMatMat(), CuVectorUnitTestAddMatVec(), CuVectorUnitTestAddRowSumMat(), CuVectorUnitTestAddSpVec(), CuVectorUnitTestAddVec(), CuVectorUnitTestAddVecCross(), CuVectorUnitTestAddVecExtra(), CuVectorUnitTestAddVecVec(), CuVectorUnitTestApplyCeiling(), CuVectorUnitTestApplyCeilingNoCount(), CuVectorUnitTestApplyFloor(), CuVectorUnitTestApplyFloorNoCount(), CuVectorUnitTestApplyPow(), CuVectorUnitTestApplySoftMax(), CuVectorUnitTestCopyCross(), CuVectorUnitTestCopyCross2(), CuVectorUnitTestCopyDiagFromMat(), CuVectorUnitTestCopyElements(), CuVectorUnitTestInvertElements(), CuVectorUnitTestVecVec(), RegressionTree::GatherStats(), PldaEstimator::GetOutput(), fst::LatticeWeightTest(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), test_flags_driven_update(), test_io(), TestAddToClusters(), TestAddToClustersOptimized(), TestAmDiagGmmAccsIO(), TestAmDiagGmmIO(), TestComponentAcc(), fst::TestContextFst(), TestCuMatrixCopyFromSp(), TestCuMatrixCopyFromTp(), TestCuMatrixCopyLowerToUpper(), TestCuMatrixCopyUpperToLower(), TestCuMatrixTransposeCross(), TestDistance(), TestMllrAccsIO(), TestObjfMinus(), TestObjfPlus(), TestOnlineMatrixCacheFeature(), TestOnlineMatrixInput(), TestOnlineMfcc(), TestOnlinePlp(), TestOnlineTransform(), TestRefineClusters(), TestSgmm2AccsIO(), TestSgmm2FmllrAccsIO(), TestSgmm2IncreaseDim(), TestSgmm2Init(), TestSgmm2IO(), TestSgmm2Substates(), kaldi::nnet3::TestSimpleComponentPropagateProperties(), TestSplitStates(), TestSum(), TestSumObjfAndSumNormalizer(), TestXformMean(), UnitTestAddDiagMat2(), UnitTestAddDiagMatMat(), UnitTestAddDiagVecMat(), UnitTestAddMat2(), UnitTestAddMat2Sp(), UnitTestAddMatDiagVec(), UnitTestAddMatMatElements(), UnitTestAddMatSelf(), UnitTestAddMatSmat(), UnitTestAddOuterProductPlusMinus(), UnitTestAddRows(), UnitTestAddSp(), UnitTestAddToDiag(), UnitTestAddToDiagMatrix(), UnitTestAddToRows(), UnitTestAddVec2Sp(), UnitTestAddVecCross(), UnitTestAddVecToCols(), UnitTestAddVecToRows(), UnitTestAddVecVec(), UnitTestApplyExpSpecial(), UnitTestAssertFunc(), kaldi::nnet3::attention::UnitTestAttentionDotProductAndAddScales(), UnitTestAxpy(), UnitTestBackpropLstmNonlinearity(), UnitTestCholesky(), UnitTestComplexFft(), UnitTestComplexFt(), UnitTestComplexPower(), UnitTestCompressedMatrix(), kaldi::nnet1::UnitTestConvolutionalComponent3x3(), kaldi::nnet1::UnitTestConvolutionalComponentUnity(), UnitTestCopyCols(), UnitTestCopyRows(), UnitTestCopySp(), UnitTestCopyToRows(), UnitTestCuArray(), UnitTestCuBlockMatrixAddMatBlock(), UnitTestCuBlockMatrixIO(), UnitTestCuDiffNormalizePerRow(), UnitTestCuMathComputeLstmNonlinearity(), UnitTestCuMathCopy(), UnitTestCuMathNormalizePerRow(), UnitTestCuMathNormalizePerRow_v2(), UnitTestCuMathRandomize(), UnitTestCuMathSplice(), UnitTestCuPackedMatrixConstructor(), UnitTestCuPackedMatrixCopy(), UnitTestCuPackedMatrixScale(), UnitTestCuPackedMatrixScaleDiag(), UnitTestCuPackedMatrixTrace(), UnitTestCuSparseMatrixConstructFromIndexes(), UnitTestCuSparseMatrixCopyToSmat(), UnitTestCuSparseMatrixFrobeniusNorm(), UnitTestCuSparseMatrixSelectRowsAndTranspose(), UnitTestCuSparseMatrixSwap(), UnitTestCuSparseMatrixTraceMatSmat(), UnitTestCuSpMatrixAddMat2(), UnitTestCuSpMatrixAddSp(), UnitTestCuSpMatrixAddToDiag(), UnitTestCuSpMatrixAddVec2(), UnitTestCuSpMatrixConstructor(), UnitTestCuSpMatrixInvert(), UnitTestCuSpMatrixIO(), UnitTestCuSpMatrixSetUnit(), UnitTestCuTpMatrixCopyFromMat(), UnitTestCuTpMatrixIO(), UnitTestCuVectorAddTp(), UnitTestCuVectorCopyFromVec(), UnitTestCuVectorIO(), UnitTestCuVectorMulTp(), UnitTestCuVectorReplaceValue(), UnitTestDeterminantSign(), UnitTestDiagGmm(), UnitTestDiagGmmGenerate(), kaldi::nnet1::UnitTestDropoutComponent(), UnitTestEig(), UnitTestEigSymmetric(), UnitTestEndless1(), UnitTestEndless2(), UnitTestEstimateDiagGmm(), UnitTestEstimateFullGmm(), UnitTestFFTbasedBlockConvolution(), UnitTestFFTbasedConvolution(), UnitTestFloorCeiling(), UnitTestFullGmm(), UnitTestGeneralMatrix(), UnitTestHtkIo(), UnitTestInnerProd(), UnitTestInvert(), UnitTestIo(), UnitTestIoCross(), UnitTestIoNew(), UnitTestIoPipe(), kaldi::nnet1::UnitTestLengthNorm(), UnitTestLinearResample2(), UnitTestMat2Vec(), UnitTestMatrixAddMatSmat(), UnitTestMatrixAddSmatMat(), UnitTestMatrixRandomizer(), UnitTestMax2(), UnitTestMaxAbsEig(), UnitTestMaxMin(), kaldi::nnet1::UnitTestMaxPoolingComponent(), UnitTestMmulSym(), UnitTestMono22K(), UnitTestMul(), UnitTestMulTp(), kaldi::nnet2::UnitTestNnetCompute(), kaldi::nnet2::UnitTestNnetComputeChunked(), UnitTestNonsymmetricPower(), UnitTestPca(), UnitTestPca2(), UnitTestPieces(), UnitTestPower(), UnitTestPowerAbs(), kaldi::nnet3::UnitTestPreconditionDirectionsOnline(), kaldi::nnet2::UnitTestPreconditionDirectionsOnline(), UnitTestRankNUpdate(), UnitTestRealFft(), UnitTestReplaceValue(), UnitTestResize(), UnitTestResizeCopyDataDifferentStrideType(), UnitTestRow(), UnitTestScaleDiag(), UnitTestSearch(), UnitTestSetDiag(), UnitTestSigmoid(), UnitTestSimple(), UnitTestSimpleForMat(), UnitTestSimpleForVec(), kaldi::nnet1::UnitTestSimpleSentenceAveragingComponent(), UnitTestSnipEdges(), UnitTestSoftHinge(), UnitTestSolve(), UnitTestSpAddDiagVec(), UnitTestSpAddVecVec(), UnitTestSparseMatrixAddToMat(), UnitTestSparseMatrixConstructor(), UnitTestSparseMatrixFrobeniusNorm(), UnitTestSparseMatrixSum(), UnitTestSparseMatrixTraceMatSmat(), UnitTestSparseVectorAddToVec(), UnitTestSparseVectorMax(), UnitTestSparseVectorSum(), UnitTestSpliceRows(), UnitTestSplitRadixComplexFft(), UnitTestSplitRadixRealFft(), UnitTestSpVec(), UnitTestStdVectorRandomizer(), UnitTestStereo8K(), UnitTestSubvector(), UnitTestSvd(), UnitTestSvdJustvec(), UnitTestSymAddMat2(), UnitTestTanh(), UnitTestTopEigs(), UnitTestTp2(), UnitTestTp2Sp(), UnitTestTrace(), UnitTestTraceSpSpLower(), UnitTestTranspose(), UnitTestTridiagonalize(), UnitTestTridiagonalizeAndQr(), UnitTestTriVecSolver(), UnitTestVecMatVec(), UnitTestVecmul(), UnitTestVector(), UnitTestVectorRandomizer(), UnitTestVtln(), FmllrSgmm2Accs::Update(), and AccumDiagGmm::variance_accumulator().

277  {
278  // a==b handles infinities.
279  KALDI_ASSERT(ApproxEqual(a, b, relative_tolerance));
280 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ AssertEqual() [11/12]

void kaldi::AssertEqual ( const CuVectorBase< Real > &  a,
const CuVectorBase< Real > &  b,
Real  tol = 0.01 
)
inline

Definition at line 370 of file cu-vector.h.

References KALDI_ASSERT.

371  {
372  KALDI_ASSERT(a.ApproxEqual(b, tol));
373 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AssertEqual() [12/12]

void kaldi::AssertEqual ( const CuMatrixBase< Real > &  A,
const CuMatrixBase< Real > &  B,
float  tol = 0.01 
)
inline

Definition at line 943 of file cu-matrix.h.

References KALDI_ASSERT.

944  {
945  KALDI_ASSERT(A.ApproxEqual(B, tol));
946 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ AttemptComplexPower() [1/2]

template bool kaldi::AttemptComplexPower ( float x_re,
float x_im,
float  power 
)

◆ AttemptComplexPower() [2/2]

template bool kaldi::AttemptComplexPower ( double *  x_re,
double *  x_im,
double  power 
)

◆ AugmentGmmFlags()

GmmFlagsType AugmentGmmFlags ( GmmFlagsType  f)

Returns "augmented" version of flags: e.g.

if just updating means, need weights too.

Definition at line 52 of file model-common.cc.

References KALDI_ASSERT, KALDI_WARN, kGmmAll, kGmmMeans, kGmmVariances, and kGmmWeights.

Referenced by DiagGmmToStats(), AccumFullGmm::Resize(), and AccumDiagGmm::Resize().

52  {
53 KALDI_ASSERT((flags & ~kGmmAll) == 0); // make sure only valid flags are present.
54  if (flags & kGmmVariances) flags |= kGmmMeans;
55  if (flags & kGmmMeans) flags |= kGmmWeights;
56  if (!(flags & kGmmWeights)) {
57  KALDI_WARN << "Adding in kGmmWeights (\"w\") to empty flags.";
58  flags |= kGmmWeights; // Just add this in regardless:
59  // if user wants no stats, this will stop programs from crashing due to dim mismatches.
60  }
61  return flags;
62 }
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ BiphoneContextDependencyFull()

ContextDependency* kaldi::BiphoneContextDependencyFull ( std::vector< std::vector< int32 > >  phone_sets,
const std::vector< int32 phone2num_pdf_classes,
const std::vector< int32 > &  ci_phones_list,
const std::vector< std::vector< int32 > > &  bi_counts,
int32  biphone_min_count,
const std::vector< int32 > &  mono_counts,
int32  mono_min_count 
)

Definition at line 180 of file gmm-init-biphone.cc.

References GetFullBiphoneStubMap(), rnnlm::i, and rnnlm::j.

Referenced by main().

186  {
187  // Remove all the CI phones from the phone sets
188  std::set<int32> ci_phones;
189  for (size_t i = 0; i < ci_phones_list.size(); i++)
190  ci_phones.insert(ci_phones_list[i]);
191  for (int32 i = phone_sets.size() - 1; i >= 0; i--) {
192  for (int32 j = phone_sets[i].size() - 1; j >= 0; j--) {
193  if (ci_phones.find(phone_sets[i][j]) != ci_phones.end()) { // Delete it
194  phone_sets[i].erase(phone_sets[i].begin() + j);
195  if (phone_sets[i].empty()) // If empty, delete the whole entry
196  phone_sets.erase(phone_sets.begin() + i);
197  }
198  }
199  }
200 
201  std::vector<bool> share_roots(phone_sets.size(), false); // Don't share roots
202  // N is context size, P = position of central phone (must be 0).
203  int32 P = 1, N = 2;
204  EventMap *pdf_map = GetFullBiphoneStubMap(phone_sets,
205  phone2num_pdf_classes,
206  ci_phones_list, bi_counts,
207  biphone_min_count, mono_counts,
208  mono_min_count);
209  return new ContextDependency(N, P, pdf_map);
210 }
kaldi::int32 int32
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
EventMap * GetFullBiphoneStubMap(const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< int32 > &ci_phones_list, const std::vector< std::vector< int32 > > &bi_counts, int32 biphone_min_count, const std::vector< int32 > &mono_counts, int32 mono_min_count)

◆ BuildConstArpaLm()

bool BuildConstArpaLm ( const ArpaParseOptions options,
const std::string &  arpa_rxfilename,
const std::string &  const_arpa_wxfilename 
)

Definition at line 1074 of file const-arpa-lm.cc.

References KALDI_LOG, ArpaFileParser::Read(), Input::Stream(), and WriteKaldiObject().

1076  {
1077  ConstArpaLmBuilder lm_builder(options);
1078  KALDI_LOG << "Reading " << arpa_rxfilename;
1079  Input ki(arpa_rxfilename);
1080  lm_builder.Read(ki.Stream());
1081  WriteKaldiObject(lm_builder, const_arpa_wxfilename, true);
1082  return true;
1083 }
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ CalBasisFmllrStepSize()

BaseFloat CalBasisFmllrStepSize ( const AffineXformStats spk_stats,
const Matrix< BaseFloat > &  spk_stats_tmp_K,
const std::vector< SpMatrix< BaseFloat > > &  spk_stats_tmp_G,
const Matrix< BaseFloat > &  delta,
const Matrix< BaseFloat > &  A,
const Matrix< BaseFloat > &  S,
int32  max_iters 
)
static

This function takes the step direction (delta) of fMLLR matrix as argument, and optimize step size using Newton's method.

This is an iterative method, where each iteration should not decrease the auxiliary function. Note that the resulting step size should be close to 1. If <<1 or >>1, there maybe problems with preconditioning or the speaker stats.

Definition at line 374 of file basis-fmllr-diag-gmm.cc.

References MatrixBase< Real >::AddMat(), MatrixBase< Real >::AddMatMat(), VectorBase< Real >::AddSpVec(), AffineXformStats::beta_, MatrixBase< Real >::CopyFromMat(), rnnlm::d, AffineXformStats::dim_, MatrixBase< Real >::InvertDouble(), KALDI_ASSERT, KALDI_WARN, kNoTrans, kTrans, MatrixBase< Real >::LogDet(), MatrixBase< Real >::NumRows(), MatrixBase< Real >::Row(), TraceMat(), TraceMatMat(), and VecVec().

Referenced by BasisFmllrEstimate::ComputeTransform().

380  {
381 
382  int32 dim = spk_stats.dim_;
383  KALDI_ASSERT(dim == delta.NumRows() && dim == S.NumRows());
384  // The first D columns of delta_W
385  SubMatrix<BaseFloat> delta_Dim(delta, 0, dim, 0, dim);
386  // Eq. (46): b = tr(delta K^T) - tr(delta S^T)
387  BaseFloat b = TraceMatMat(delta, spk_stats_tmp_K, kTrans)
388  - TraceMatMat(delta, S, kTrans);
389  // Eq. (47): c = sum_d tr(delta_{d} G_{d} delta_{d})
390  BaseFloat c = 0;
391  Vector<BaseFloat> G_row_delta(dim + 1);
392  for (int32 d = 0; d < dim; ++d) {
393  G_row_delta.AddSpVec(1.0, spk_stats_tmp_G[d], delta.Row(d), 0.0);
394  c += VecVec(G_row_delta, delta.Row(d));
395  }
396 
397  // Sometimes, the change of step size, d1/d2, may get tiny
398  // Due to numerical precision, we compute everything in double
399  BaseFloat step_size = 0.0;
400  BaseFloat obj_old, obj_new = 0.0;
401  Matrix<BaseFloat> N(dim, dim);
402  for (int32 iter_step = 1; iter_step <= max_iters; ++iter_step) {
403  if (iter_step == 1) {
404  // k = 0, auxf = beta logdet(A)
405  obj_old = spk_stats.beta_ * A.LogDet();
406  } else {
407  obj_old = obj_new;
408  }
409 
410  // Eq. (49): N = (A + k * delta_Dim)^{-1} delta_Dim
411  // In case of bad condition, careful preconditioning should be done. Maybe safer
412  // to use SolveQuadraticMatrixProblem. Future work for Yajie.
413  Matrix<BaseFloat> tmp_A(A);
414  tmp_A.AddMat(step_size, delta_Dim, kNoTrans);
415  tmp_A.InvertDouble();
416  N.AddMatMat(1.0, tmp_A, kNoTrans, delta_Dim, kNoTrans, 0.0);
417  // first-order derivative w.r.t. k
418  // Eq. (50): d1 = beta * trace(N) + b - k * c
419  BaseFloat d1 = spk_stats.beta_ * TraceMat(N) + b - step_size * c;
420  // second-order derivative w.r.t. k
421  // Eq. (51): d2 = -beta * tr(N N) - c
422  BaseFloat d2 = -c - spk_stats.beta_ * TraceMatMat(N, N, kNoTrans);
423  d2 = std::min((double)d2, -c / 10.0);
424  // convergence judgment from fmllr-sgmm.cc
425  // it seems to work well, though not sure whether 1e-06 is appropriate
426  // note from Dan: commenting this out after someone complained it was
427  // causing a test to behave weirdly. This doesn't dominate computation
428  // anyway, I don't think.
429  // if (std::fabs(d1 / d2) < 0.000001) { break; }
430 
431  // Eq. (52): update step_size
432  BaseFloat step_size_change = -(d1 / d2);
433  step_size += step_size_change;
434 
435  // Repeatedly check auxiliary function; halve step size change if auxf decreases.
436  // According to the paper, we should limit the number of repetitions. The
437  // following implementation seems to work well. But the termination condition/judgment
438  // should be optimized later.
439  do {
440  // Eq. (48): auxf = beta * logdet(A + k * delta_Dim) + kb - 0.5 * k * k * c
441  tmp_A.CopyFromMat(A);
442  tmp_A.AddMat(step_size, delta_Dim, kNoTrans);
443  obj_new = spk_stats.beta_ * tmp_A.LogDet() + step_size * b -
444  0.5 * step_size * step_size * c;
445 
446  if (obj_new - obj_old < -1.0e-04 * spk_stats.beta_) { // deal with numerical issues
447  KALDI_WARN << "Objective function decreased (" << obj_old << "->"
448  << obj_new << "). Halving step size change ( step size "
449  << step_size << " -> " << (step_size - (step_size_change/2))
450  << ")";
451  step_size_change /= 2;
452  step_size -= step_size_change;
453  }
454  } while (obj_new - obj_old < -1.0e-04 * spk_stats.beta_ && step_size_change > 1e-05);
455  }
456  return step_size;
457 }
double TraceMat(const MatrixBase< Real > &A)
Returns trace of matrix.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
#define KALDI_WARN
Definition: kaldi-error.h:150
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
Real LogDet(Real *det_sign=NULL) const
Returns logdet of matrix.
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ CalcFmllrStepSize()

static BaseFloat kaldi::CalcFmllrStepSize ( const AffineXformStats stats,
const AmSgmm2 sgmm,
const MatrixBase< BaseFloat > &  Delta,
const MatrixBase< BaseFloat > &  A,
const Matrix< BaseFloat > &  G,
int32  max_iters 
)
static

Definition at line 286 of file fmllr-sgmm2.cc.

References MatrixBase< Real >::AddMat(), MatrixBase< Real >::AddMatMat(), AffineXformStats::beta_, MatrixBase< Real >::CopyFromMat(), rnnlm::d, AmSgmm2::FeatureDim(), AffineXformStats::G_, AmSgmm2::GetInvCovars(), rnnlm::i, MatrixBase< Real >::InvertDouble(), AffineXformStats::K_, KALDI_WARN, kNoTrans, kTrans, MatrixBase< Real >::LogDet(), rnnlm::n, AmSgmm2::NumGauss(), TraceMat(), TraceMatMat(), and TraceMatSpMatSp().

Referenced by FmllrSgmm2Accs::Update().

291  {
292  int32 dim = sgmm.FeatureDim();
293  Matrix<double> Delta_d(Delta);
294  Matrix<double> G_d(G);
295  SubMatrix<double> Delta_C(Delta_d, 0, dim, 0, dim);
296 
297  // Eq. (B.28): m = tr(\Delta K^T) - tr(\Delta S^T)
298  BaseFloat m = TraceMatMat(Delta_d, stats.K_, kTrans)
299  - TraceMatMat(Delta_d, G_d, kTrans);
300  // Eq. (B.29): n = \sum_i tr(\Delta \Sigma_{i}^{-1} \Delta S_{i})
301  BaseFloat n = 0;
302  SpMatrix<double> inv_covar;
303  for (int32 i = 0, num_gauss = sgmm.NumGauss(); i < num_gauss; i++) {
304  sgmm.GetInvCovars(i, &inv_covar);
305  n += TraceMatSpMatSp(Delta_d, kTrans, inv_covar, Delta_d, kNoTrans,
306  stats.G_[i]);
307  }
308 
309  BaseFloat step_size = 0.0;
310  // initialize just to get rid of compile errors.
311  BaseFloat obj_step_old, obj_step_new = 0.0;
312  Matrix<double> new_A(dim, dim);
313  Matrix<double> B(dim, dim);
314  for (int32 iter_step = 0; iter_step < max_iters; iter_step++) {
315  if (iter_step == 0) {
316  obj_step_old = stats.beta_ * A.LogDet(); // Q_0 = \beta * log det(A)
317  } else {
318  obj_step_old = obj_step_new;
319  }
320 
321  // Eq. (B.30); B = (A + k\Delta^{-C})^{-1} \Delta^{-C}
322  new_A.CopyFromMat(A);
323  new_A.AddMat(step_size, Delta_C, kNoTrans);
324  new_A.InvertDouble();
325  B.AddMatMat(1.0, new_A, kNoTrans, Delta_C, kNoTrans, 0.0);
326 
327  BaseFloat d = m - step_size * n + stats.beta_ * TraceMat(B);
328  BaseFloat d2 = -n - stats.beta_ * TraceMatMat(B, B, kNoTrans);
329  if (std::fabs(d / d2) < 0.000001) { break; } // converged
330 
331  BaseFloat step_size_change = -(d / d2);
332  step_size += step_size_change; // Eq. (B.33)
333 
334  // Halve step size when the auxiliary function decreases.
335  do {
336  new_A.CopyFromMat(A);
337  new_A.AddMat(step_size, Delta_C, kNoTrans);
338  BaseFloat logdet = new_A.LogDet();
339  obj_step_new = stats.beta_ * logdet + step_size * m -
340  0.5 * step_size * step_size * n;
341 
342  if (obj_step_new - obj_step_old < -0.001) {
343  KALDI_WARN << "Objective function decreased (" << obj_step_old << "->"
344  << obj_step_new << "). Halving step size change ("
345  << step_size << " -> " << (step_size - (step_size_change/2))
346  << ")";
347  step_size_change /= 2;
348  step_size -= step_size_change; // take away half of our step
349  } // Facing numeric precision issues. Compute in double?
350  } while (obj_step_new - obj_step_old < -0.001 && step_size_change > 1e-05);
351  }
352  return step_size;
353 }
double TraceMat(const MatrixBase< Real > &A)
Returns trace of matrix.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
#define KALDI_WARN
Definition: kaldi-error.h:150
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
Real TraceMatSpMatSp(const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const MatrixBase< Real > &C, MatrixTransposeType transC, const SpMatrix< Real > &D)
Returns tr (A B C D) (A and C may be transposed as specified by transA and transB).
Definition: sp-matrix.cc:438

◆ cblas_Xasum() [1/2]

float kaldi::cblas_Xasum ( const int  N,
const float X,
const int  incX 
)
inline

Definition at line 48 of file cblas-wrappers.h.

48  {
49  return cblas_sasum(N, X, incX);
50 }

◆ cblas_Xasum() [2/2]

double kaldi::cblas_Xasum ( const int  N,
const double *  X,
const int  incX 
)
inline

Definition at line 52 of file cblas-wrappers.h.

52  {
53  return cblas_dasum(N, X, incX);
54 }

◆ cblas_Xaxpy() [1/2]

void kaldi::cblas_Xaxpy ( const int  N,
const float  alpha,
const float X,
const int  incX,
float Y,
const int  incY 
)
inline

◆ cblas_Xaxpy() [2/2]

void kaldi::cblas_Xaxpy ( const int  N,
const double  alpha,
const double *  X,
const int  incX,
double *  Y,
const int  incY 
)
inline

Definition at line 78 of file cblas-wrappers.h.

79  {
80  cblas_daxpy(N, alpha, X, incX, Y, incY);
81 }

◆ cblas_Xcopy() [1/2]

void kaldi::cblas_Xcopy ( const int  N,
const float X,
const int  incX,
float Y,
const int  incY 
)
inline

Definition at line 37 of file cblas-wrappers.h.

Referenced by VectorBase< float >::CopyDiagFromMat(), MatrixBase< float >::CopyRows(), and MatrixBase< float >::CopyToRows().

38  {
39  cblas_scopy(N, X, incX, Y, incY);
40 }

◆ cblas_Xcopy() [2/2]

void kaldi::cblas_Xcopy ( const int  N,
const double *  X,
const int  incX,
double *  Y,
const int  incY 
)
inline

Definition at line 42 of file cblas-wrappers.h.

43  {
44  cblas_dcopy(N, X, incX, Y, incY);
45 }

◆ cblas_Xdot() [1/2]

float kaldi::cblas_Xdot ( const int  N,
const float *const  X,
const int  incX,
const float *const  Y,
const int  incY 
)
inline

◆ cblas_Xdot() [2/2]

double kaldi::cblas_Xdot ( const int  N,
const double *const  X,
const int  incX,
const double *const  Y,
const int  incY 
)
inline

Definition at line 69 of file cblas-wrappers.h.

71  {
72  return cblas_ddot(N, X, incX, Y, incY);
73 }

◆ cblas_Xgbmv() [1/2]

void kaldi::cblas_Xgbmv ( MatrixTransposeType  trans,
MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
MatrixIndexT  num_below,
MatrixIndexT  num_above,
float  alpha,
const float Mdata,
MatrixIndexT  stride,
const float xdata,
MatrixIndexT  incX,
float  beta,
float ydata,
MatrixIndexT  incY 
)
inline

Definition at line 178 of file cblas-wrappers.h.

Referenced by VectorBase< float >::AddVecVec().

182  {
183  cblas_sgbmv(CblasRowMajor, static_cast<CBLAS_TRANSPOSE>(trans), num_rows,
184  num_cols, num_below, num_above, alpha, Mdata, stride, xdata,
185  incX, beta, ydata, incY);
186 }

◆ cblas_Xgbmv() [2/2]

void kaldi::cblas_Xgbmv ( MatrixTransposeType  trans,
MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
MatrixIndexT  num_below,
MatrixIndexT  num_above,
double  alpha,
const double *  Mdata,
MatrixIndexT  stride,
const double *  xdata,
MatrixIndexT  incX,
double  beta,
double *  ydata,
MatrixIndexT  incY 
)
inline

Definition at line 187 of file cblas-wrappers.h.

191  {
192  cblas_dgbmv(CblasRowMajor, static_cast<CBLAS_TRANSPOSE>(trans), num_rows,
193  num_cols, num_below, num_above, alpha, Mdata, stride, xdata,
194  incX, beta, ydata, incY);
195 }

◆ cblas_Xgemm() [1/2]

void kaldi::cblas_Xgemm ( const float  alpha,
MatrixTransposeType  transA,
const float Adata,
MatrixIndexT  a_num_rows,
MatrixIndexT  a_num_cols,
MatrixIndexT  a_stride,
MatrixTransposeType  transB,
const float Bdata,
MatrixIndexT  b_stride,
const float  beta,
float Mdata,
MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
MatrixIndexT  stride 
)
inline

Definition at line 224 of file cblas-wrappers.h.

References kNoTrans.

Referenced by MatrixBase< float >::AddMatMat().

232  {
233  cblas_sgemm(CblasRowMajor, static_cast<CBLAS_TRANSPOSE>(transA),
234  static_cast<CBLAS_TRANSPOSE>(transB),
235  num_rows, num_cols, transA == kNoTrans ? a_num_cols : a_num_rows,
236  alpha, Adata, a_stride, Bdata, b_stride,
237  beta, Mdata, stride);
238 }

◆ cblas_Xgemm() [2/2]

void kaldi::cblas_Xgemm ( const double  alpha,
MatrixTransposeType  transA,
const double *  Adata,
MatrixIndexT  a_num_rows,
MatrixIndexT  a_num_cols,
MatrixIndexT  a_stride,
MatrixTransposeType  transB,
const double *  Bdata,
MatrixIndexT  b_stride,
const double  beta,
double *  Mdata,
MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
MatrixIndexT  stride 
)
inline

Definition at line 239 of file cblas-wrappers.h.

References kNoTrans.

247  {
248  cblas_dgemm(CblasRowMajor, static_cast<CBLAS_TRANSPOSE>(transA),
249  static_cast<CBLAS_TRANSPOSE>(transB),
250  num_rows, num_cols, transA == kNoTrans ? a_num_cols : a_num_rows,
251  alpha, Adata, a_stride, Bdata, b_stride,
252  beta, Mdata, stride);
253 }

◆ cblas_Xgemv() [1/2]

void kaldi::cblas_Xgemv ( MatrixTransposeType  trans,
MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
float  alpha,
const float Mdata,
MatrixIndexT  stride,
const float xdata,
MatrixIndexT  incX,
float  beta,
float ydata,
MatrixIndexT  incY 
)
inline

Definition at line 162 of file cblas-wrappers.h.

Referenced by SpMatrix< float >::AddMat2Sp(), VectorBase< float >::AddMatVec(), and SpMatrix< float >::Tridiagonalize().

165  {
166  cblas_sgemv(CblasRowMajor, static_cast<CBLAS_TRANSPOSE>(trans), num_rows,
167  num_cols, alpha, Mdata, stride, xdata, incX, beta, ydata, incY);
168 }

◆ cblas_Xgemv() [2/2]

void kaldi::cblas_Xgemv ( MatrixTransposeType  trans,
MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
double  alpha,
const double *  Mdata,
MatrixIndexT  stride,
const double *  xdata,
MatrixIndexT  incX,
double  beta,
double *  ydata,
MatrixIndexT  incY 
)
inline

Definition at line 169 of file cblas-wrappers.h.

172  {
173  cblas_dgemv(CblasRowMajor, static_cast<CBLAS_TRANSPOSE>(trans), num_rows,
174  num_cols, alpha, Mdata, stride, xdata, incX, beta, ydata, incY);
175 }

◆ cblas_Xger() [1/2]

void kaldi::cblas_Xger ( MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
float  alpha,
const float xdata,
MatrixIndexT  incX,
const float ydata,
MatrixIndexT  incY,
float Mdata,
MatrixIndexT  stride 
)
inline

Definition at line 275 of file cblas-wrappers.h.

Referenced by MatrixBase< float >::AddVecVec(), and SpMatrix< float >::Tridiagonalize().

277  {
278  cblas_sger(CblasRowMajor, num_rows, num_cols, alpha, xdata, 1, ydata, 1,
279  Mdata, stride);
280 }

◆ cblas_Xger() [2/2]

void kaldi::cblas_Xger ( MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
double  alpha,
const double *  xdata,
MatrixIndexT  incX,
const double *  ydata,
MatrixIndexT  incY,
double *  Mdata,
MatrixIndexT  stride 
)
inline

Definition at line 281 of file cblas-wrappers.h.

283  {
284  cblas_dger(CblasRowMajor, num_rows, num_cols, alpha, xdata, 1, ydata, 1,
285  Mdata, stride);
286 }

◆ cblas_Xrot() [1/2]

void kaldi::cblas_Xrot ( const int  N,
float X,
const int  incX,
float Y,
const int  incY,
const float  c,
const float  s 
)
inline

Definition at line 56 of file cblas-wrappers.h.

Referenced by QrStep().

57  {
58  cblas_srot(N, X, incX, Y, incY, c, s);
59 }

◆ cblas_Xrot() [2/2]

void kaldi::cblas_Xrot ( const int  N,
double *  X,
const int  incX,
double *  Y,
const int  incY,
const double  c,
const double  s 
)
inline

Definition at line 60 of file cblas-wrappers.h.

61  {
62  cblas_drot(N, X, incX, Y, incY, c, s);
63 }

◆ cblas_Xsbmv1() [1/2]

void kaldi::cblas_Xsbmv1 ( const MatrixIndexT  dim,
const double *  A,
const double  alpha,
const double *  x,
const double  beta,
double *  y 
)
inline

matrix-vector multiply using a banded matrix; we always call this with b = 1 meaning we're multiplying by a diagonal matrix.

This is used for elementwise multiplication. We miss some of the arguments out of this wrapper.

Definition at line 317 of file cblas-wrappers.h.

323  {
324  cblas_dsbmv(CblasRowMajor, CblasLower, dim, 0, alpha, A,
325  1, x, 1, beta, y, 1);
326 }

◆ cblas_Xsbmv1() [2/2]

void kaldi::cblas_Xsbmv1 ( const MatrixIndexT  dim,
const float A,
const float  alpha,
const float x,
const float  beta,
float y 
)
inline

Definition at line 328 of file cblas-wrappers.h.

334  {
335  cblas_ssbmv(CblasRowMajor, CblasLower, dim, 0, alpha, A,
336  1, x, 1, beta, y, 1);
337 }

◆ cblas_Xscal() [1/2]

void kaldi::cblas_Xscal ( const int  N,
const float  alpha,
float data,
const int  inc 
)
inline

◆ cblas_Xscal() [2/2]

void kaldi::cblas_Xscal ( const int  N,
const double  alpha,
double *  data,
const int  inc 
)
inline

Definition at line 86 of file cblas-wrappers.h.

87  {
88  cblas_dscal(N, alpha, data, inc);
89 }

◆ cblas_Xspmv() [1/4]

void kaldi::cblas_Xspmv ( const float  alpha,
const int  num_rows,
const float Mdata,
const float v,
const int  v_inc,
const float  beta,
float y,
const int  y_inc 
)
inline

Definition at line 90 of file cblas-wrappers.h.

Referenced by SpMatrix< float >::AddMat2Sp(), VectorBase< float >::AddSpVec(), SpMatrix< float >::Tridiagonalize(), UnitTestTridiagonalize(), UnitTestTridiagonalizeAndQr(), and VecSpVec().

92  {
93  cblas_sspmv(CblasRowMajor, CblasLower, num_rows, alpha, Mdata, v, v_inc, beta, y, y_inc);
94 }

◆ cblas_Xspmv() [2/4]

void kaldi::cblas_Xspmv ( const double  alpha,
const int  num_rows,
const double *  Mdata,
const double *  v,
const int  v_inc,
const double  beta,
double *  y,
const int  y_inc 
)
inline

Definition at line 95 of file cblas-wrappers.h.

97  {
98  cblas_dspmv(CblasRowMajor, CblasLower, num_rows, alpha, Mdata, v, v_inc, beta, y, y_inc);
99 }

◆ cblas_Xspmv() [3/4]

void kaldi::cblas_Xspmv ( MatrixIndexT  dim,
float  alpha,
const float Mdata,
const float ydata,
MatrixIndexT  ystride,
float  beta,
float xdata,
MatrixIndexT  xstride 
)
inline

Definition at line 124 of file cblas-wrappers.h.

126  {
127  cblas_sspmv(CblasRowMajor, CblasLower, dim, alpha, Mdata,
128  ydata, ystride, beta, xdata, xstride);
129 }

◆ cblas_Xspmv() [4/4]

void kaldi::cblas_Xspmv ( MatrixIndexT  dim,
double  alpha,
const double *  Mdata,
const double *  ydata,
MatrixIndexT  ystride,
double  beta,
double *  xdata,
MatrixIndexT  xstride 
)
inline

Definition at line 130 of file cblas-wrappers.h.

132  {
133  cblas_dspmv(CblasRowMajor, CblasLower, dim, alpha, Mdata,
134  ydata, ystride, beta, xdata, xstride);
135 }

◆ cblas_Xspr() [1/2]

void kaldi::cblas_Xspr ( MatrixIndexT  dim,
float  alpha,
const float Xdata,
MatrixIndexT  incX,
float Adata 
)
inline

Definition at line 152 of file cblas-wrappers.h.

Referenced by SpMatrix< float >::AddMat2Vec(), and SpMatrix< float >::AddVec2().

153  {
154  cblas_sspr(CblasRowMajor, CblasLower, dim, alpha, Xdata, incX, Adata);
155 }

◆ cblas_Xspr() [2/2]

void kaldi::cblas_Xspr ( MatrixIndexT  dim,
double  alpha,
const double *  Xdata,
MatrixIndexT  incX,
double *  Adata 
)
inline

Definition at line 156 of file cblas-wrappers.h.

157  {
158  cblas_dspr(CblasRowMajor, CblasLower, dim, alpha, Xdata, incX, Adata);
159 }

◆ cblas_Xspr2() [1/2]

void kaldi::cblas_Xspr2 ( MatrixIndexT  dim,
float  alpha,
const float Xdata,
MatrixIndexT  incX,
const float Ydata,
MatrixIndexT  incY,
float Adata 
)
inline

Definition at line 138 of file cblas-wrappers.h.

Referenced by SpMatrix< float >::AddVecVec(), and SpMatrix< float >::Tridiagonalize().

140  {
141  cblas_sspr2(CblasRowMajor, CblasLower, dim, alpha, Xdata,
142  incX, Ydata, incY, Adata);
143 }

◆ cblas_Xspr2() [2/2]

void kaldi::cblas_Xspr2 ( MatrixIndexT  dim,
double  alpha,
const double *  Xdata,
MatrixIndexT  incX,
const double *  Ydata,
MatrixIndexT  incY,
double *  Adata 
)
inline

Definition at line 144 of file cblas-wrappers.h.

146  {
147  cblas_dspr2(CblasRowMajor, CblasLower, dim, alpha, Xdata,
148  incX, Ydata, incY, Adata);
149 }

◆ cblas_Xsymm() [1/2]

void kaldi::cblas_Xsymm ( const float  alpha,
MatrixIndexT  sz,
const float Adata,
MatrixIndexT  a_stride,
const float Bdata,
MatrixIndexT  b_stride,
const float  beta,
float Mdata,
MatrixIndexT  stride 
)
inline

Definition at line 256 of file cblas-wrappers.h.

Referenced by MatrixBase< float >::AddSpSp().

261  {
262  cblas_ssymm(CblasRowMajor, CblasLeft, CblasLower, sz, sz, alpha, Adata,
263  a_stride, Bdata, b_stride, beta, Mdata, stride);
264 }

◆ cblas_Xsymm() [2/2]

void kaldi::cblas_Xsymm ( const double  alpha,
MatrixIndexT  sz,
const double *  Adata,
MatrixIndexT  a_stride,
const double *  Bdata,
MatrixIndexT  b_stride,
const double  beta,
double *  Mdata,
MatrixIndexT  stride 
)
inline

Definition at line 265 of file cblas-wrappers.h.

270  {
271  cblas_dsymm(CblasRowMajor, CblasLeft, CblasLower, sz, sz, alpha, Adata,
272  a_stride, Bdata, b_stride, beta, Mdata, stride);
273 }

◆ cblas_Xsyrk() [1/2]

void kaldi::cblas_Xsyrk ( const MatrixTransposeType  trans,
const MatrixIndexT  dim_c,
const MatrixIndexT  other_dim_a,
const float  alpha,
const float A,
const MatrixIndexT  a_stride,
const float  beta,
float C,
const MatrixIndexT  c_stride 
)
inline

Definition at line 295 of file cblas-wrappers.h.

Referenced by SpMatrix< float >::AddMat2(), and MatrixBase< float >::SymAddMat2().

299  {
300  cblas_ssyrk(CblasRowMajor, CblasLower, static_cast<CBLAS_TRANSPOSE>(trans),
301  dim_c, other_dim_a, alpha, A, a_stride, beta, C, c_stride);
302 }

◆ cblas_Xsyrk() [2/2]

void kaldi::cblas_Xsyrk ( const MatrixTransposeType  trans,
const MatrixIndexT  dim_c,
const MatrixIndexT  other_dim_a,
const double  alpha,
const double *  A,
const MatrixIndexT  a_stride,
const double  beta,
double *  C,
const MatrixIndexT  c_stride 
)
inline

Definition at line 304 of file cblas-wrappers.h.

308  {
309  cblas_dsyrk(CblasRowMajor, CblasLower, static_cast<CBLAS_TRANSPOSE>(trans),
310  dim_c, other_dim_a, alpha, A, a_stride, beta, C, c_stride);
311 }

◆ cblas_Xtpmv() [1/2]

void kaldi::cblas_Xtpmv ( MatrixTransposeType  trans,
const float Mdata,
const int  num_rows,
float y,
const int  y_inc 
)
inline

Definition at line 100 of file cblas-wrappers.h.

Referenced by VectorBase< float >::MulTp().

101  {
102  cblas_stpmv(CblasRowMajor, CblasLower, static_cast<CBLAS_TRANSPOSE>(trans),
103  CblasNonUnit, num_rows, Mdata, y, y_inc);
104 }

◆ cblas_Xtpmv() [2/2]

void kaldi::cblas_Xtpmv ( MatrixTransposeType  trans,
const double *  Mdata,
const int  num_rows,
double *  y,
const int  y_inc 
)
inline

Definition at line 105 of file cblas-wrappers.h.

106  {
107  cblas_dtpmv(CblasRowMajor, CblasLower, static_cast<CBLAS_TRANSPOSE>(trans),
108  CblasNonUnit, num_rows, Mdata, y, y_inc);
109 }

◆ cblas_Xtpsv() [1/2]

void kaldi::cblas_Xtpsv ( MatrixTransposeType  trans,
const float Mdata,
const int  num_rows,
float y,
const int  y_inc 
)
inline

Definition at line 112 of file cblas-wrappers.h.

Referenced by VectorBase< float >::Solve().

113  {
114  cblas_stpsv(CblasRowMajor, CblasLower, static_cast<CBLAS_TRANSPOSE>(trans),
115  CblasNonUnit, num_rows, Mdata, y, y_inc);
116 }

◆ cblas_Xtpsv() [2/2]

void kaldi::cblas_Xtpsv ( MatrixTransposeType  trans,
const double *  Mdata,
const int  num_rows,
double *  y,
const int  y_inc 
)
inline

Definition at line 117 of file cblas-wrappers.h.

118  {
119  cblas_dtpsv(CblasRowMajor, CblasLower, static_cast<CBLAS_TRANSPOSE>(trans),
120  CblasNonUnit, num_rows, Mdata, y, y_inc);
121 }

◆ CharToString()

◆ CheckFst()

bool kaldi::CheckFst ( const fst::StdVectorFst fst,
string  name,
string  key 
)

Definition at line 151 of file lattice-oracle.cc.

Referenced by main().

151  {
152 #ifdef DEBUG
153  fst::StdArc::StateId numstates = fst.NumStates();
154  std::cerr << " " << name << " has " << numstates << " states" << std::endl;
155  std::stringstream ss;
156  ss << name << key << ".fst";
157  fst.Write(ss.str());
158  return(fst.Start() == fst::kNoStateId);
159 #else
160  return true;
161 #endif
162 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21

◆ CheckToken()

void kaldi::CheckToken ( const char *  token)

Definition at line 122 of file io-funcs.cc.

References KALDI_ERR.

Referenced by ExpectToken(), and WriteToken().

122  {
123  if (*token == '\0')
124  KALDI_ERR << "Token is empty (not a valid token)";
125  const char *orig_token = token;
126  while (*token != '\0') {
127  if (::isspace(*token))
128  KALDI_ERR << "Token is not a valid token (contains space): '"
129  << orig_token << "'";
130  token++;
131  }
132 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ CholeskyUnitTestTr()

static void kaldi::CholeskyUnitTestTr ( )
static

Definition at line 140 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::AddMatMat(), AssertEqual(), TpMatrix< Real >::Cholesky(), rnnlm::i, InitRandNonsingular(), TpMatrix< Real >::Invert(), MatrixBase< Real >::Invert(), MatrixBase< Real >::IsUnit(), KALDI_ASSERT, kNoTrans, and Rand().

140  {
141  for (MatrixIndexT i = 0; i < 5; i++) {
142  MatrixIndexT dimM = 2 + Rand() % 10;
143  Matrix<Real> M(dimM, dimM);
145  SpMatrix<Real> S(dimM);
146  S.AddMat2(1.0, M, kNoTrans, 0.0);
147  TpMatrix<Real> C(dimM);
148  C.Cholesky(S);
149  Matrix<Real> CM(C);
150  TpMatrix<Real> Cinv(C);
151  Cinv.Invert();
152  {
153  Matrix<Real> A(C), B(Cinv), AB(dimM, dimM);
154  AB.AddMatMat(1.0, A, kNoTrans, B, kNoTrans, 0.0);
155  KALDI_ASSERT(AB.IsUnit());
156  }
157  SpMatrix<Real> S2(dimM);
158  S2.AddMat2(1.0, CM, kNoTrans, 0.0);
159  AssertEqual(S, S2);
160  C.Invert();
161  Matrix<Real> CM2(C);
162  CM2.Invert();
163  SpMatrix<Real> S3(dimM);
164  S3.AddMat2(1.0, CM2, kNoTrans, 0.0);
165  AssertEqual(S, S3);
166  }
167 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
static void InitRandNonsingular(SpMatrix< Real > *M)

◆ clapack_Xgesvd() [1/2]

void kaldi::clapack_Xgesvd ( char *  v,
char *  u,
KaldiBlasInt *  num_cols,
KaldiBlasInt *  num_rows,
float Mdata,
KaldiBlasInt *  stride,
float sv,
float Vdata,
KaldiBlasInt *  vstride,
float Udata,
KaldiBlasInt *  ustride,
float p_work,
KaldiBlasInt *  l_work,
KaldiBlasInt *  result 
)
inline

Definition at line 415 of file cblas-wrappers.h.

Referenced by MatrixBase< float >::LapackGesvd().

419  {
420  sgesvd_(v, u,
421  num_cols, num_rows, Mdata, stride,
422  sv, Vdata, vstride, Udata, ustride,
423  p_work, l_work, result);
424 }

◆ clapack_Xgesvd() [2/2]

void kaldi::clapack_Xgesvd ( char *  v,
char *  u,
KaldiBlasInt *  num_cols,
KaldiBlasInt *  num_rows,
double *  Mdata,
KaldiBlasInt *  stride,
double *  sv,
double *  Vdata,
KaldiBlasInt *  vstride,
double *  Udata,
KaldiBlasInt *  ustride,
double *  p_work,
KaldiBlasInt *  l_work,
KaldiBlasInt *  result 
)
inline

Definition at line 425 of file cblas-wrappers.h.

429  {
430  dgesvd_(v, u,
431  num_cols, num_rows, Mdata, stride,
432  sv, Vdata, vstride, Udata, ustride,
433  p_work, l_work, result);
434 }

◆ clapack_Xgetrf2() [1/2]

void kaldi::clapack_Xgetrf2 ( KaldiBlasInt *  num_rows,
KaldiBlasInt *  num_cols,
float Mdata,
KaldiBlasInt *  stride,
KaldiBlasInt *  pivot,
KaldiBlasInt *  result 
)
inline

Definition at line 392 of file cblas-wrappers.h.

Referenced by MatrixBase< float >::Invert().

394  {
395  sgetrf_(num_rows, num_cols, Mdata, stride, pivot, result);
396 }

◆ clapack_Xgetrf2() [2/2]

void kaldi::clapack_Xgetrf2 ( KaldiBlasInt *  num_rows,
KaldiBlasInt *  num_cols,
double *  Mdata,
KaldiBlasInt *  stride,
KaldiBlasInt *  pivot,
KaldiBlasInt *  result 
)
inline

Definition at line 397 of file cblas-wrappers.h.

399  {
400  dgetrf_(num_rows, num_cols, Mdata, stride, pivot, result);
401 }

◆ clapack_Xgetri2() [1/2]

void kaldi::clapack_Xgetri2 ( KaldiBlasInt *  num_rows,
float Mdata,
KaldiBlasInt *  stride,
KaldiBlasInt *  pivot,
float p_work,
KaldiBlasInt *  l_work,
KaldiBlasInt *  result 
)
inline

Definition at line 404 of file cblas-wrappers.h.

Referenced by MatrixBase< float >::Invert().

406  {
407  sgetri_(num_rows, Mdata, stride, pivot, p_work, l_work, result);
408 }

◆ clapack_Xgetri2() [2/2]

void kaldi::clapack_Xgetri2 ( KaldiBlasInt *  num_rows,
double *  Mdata,
KaldiBlasInt *  stride,
KaldiBlasInt *  pivot,
double *  p_work,
KaldiBlasInt *  l_work,
KaldiBlasInt *  result 
)
inline

Definition at line 409 of file cblas-wrappers.h.

411  {
412  dgetri_(num_rows, Mdata, stride, pivot, p_work, l_work, result);
413 }

◆ clapack_Xsptrf() [1/2]

void kaldi::clapack_Xsptrf ( KaldiBlasInt *  num_rows,
float Mdata,
KaldiBlasInt *  ipiv,
KaldiBlasInt *  result 
)
inline

Definition at line 445 of file cblas-wrappers.h.

Referenced by SpMatrix< float >::Invert().

446  {
447  ssptrf_(const_cast<char *>("U"), num_rows, Mdata, ipiv, result);
448 }

◆ clapack_Xsptrf() [2/2]

void kaldi::clapack_Xsptrf ( KaldiBlasInt *  num_rows,
double *  Mdata,
KaldiBlasInt *  ipiv,
KaldiBlasInt *  result 
)
inline

Definition at line 449 of file cblas-wrappers.h.

450  {
451  dsptrf_(const_cast<char *>("U"), num_rows, Mdata, ipiv, result);
452 }

◆ clapack_Xsptri() [1/2]

void kaldi::clapack_Xsptri ( KaldiBlasInt *  num_rows,
float Mdata,
KaldiBlasInt *  ipiv,
float work,
KaldiBlasInt *  result 
)
inline

Definition at line 436 of file cblas-wrappers.h.

Referenced by SpMatrix< float >::Invert().

437  {
438  ssptri_(const_cast<char *>("U"), num_rows, Mdata, ipiv, work, result);
439 }

◆ clapack_Xsptri() [2/2]

void kaldi::clapack_Xsptri ( KaldiBlasInt *  num_rows,
double *  Mdata,
KaldiBlasInt *  ipiv,
double *  work,
KaldiBlasInt *  result 
)
inline

Definition at line 440 of file cblas-wrappers.h.

441  {
442  dsptri_(const_cast<char *>("U"), num_rows, Mdata, ipiv, work, result);
443 }

◆ clapack_Xtptri() [1/2]

void kaldi::clapack_Xtptri ( KaldiBlasInt *  num_rows,
float Mdata,
KaldiBlasInt *  result 
)
inline

Definition at line 385 of file cblas-wrappers.h.

Referenced by TpMatrix< float >::Invert().

385  {
386  stptri_(const_cast<char *>("U"), const_cast<char *>("N"), num_rows, Mdata, result);
387 }

◆ clapack_Xtptri() [2/2]

void kaldi::clapack_Xtptri ( KaldiBlasInt *  num_rows,
double *  Mdata,
KaldiBlasInt *  result 
)
inline

Definition at line 388 of file cblas-wrappers.h.

388  {
389  dtptri_(const_cast<char *>("U"), const_cast<char *>("N"), num_rows, Mdata, result);
390 }

◆ ClusterEventMapRestrictedHelper()

static int32 kaldi::ClusterEventMapRestrictedHelper ( const EventMap e_in,
const BuildTreeStatsType stats,
BaseFloat  thresh,
std::vector< EventKeyType keys,
std::vector< EventMap *> *  leaf_mapping 
)
static

Definition at line 803 of file build-tree-utils.cc.

References ClusterEventMapGetMapping(), rnnlm::i, and SplitStatsByKey().

Referenced by ClusterEventMapRestrictedByKeys().

807  {
808  if (keys.size() == 0) {
809  return ClusterEventMapGetMapping(e_in, stats, thresh, leaf_mapping);
810  } else { // split on the key.
811  int32 ans = 0;
812  std::vector<BuildTreeStatsType> split_stats;
813  SplitStatsByKey(stats, keys.back(), &split_stats);
814  keys.pop_back();
815  for (size_t i = 0; i< split_stats.size(); i++)
816  if (split_stats[i].size() != 0)
817  ans += ClusterEventMapRestrictedHelper(e_in, split_stats[i], thresh, keys, leaf_mapping);
818  return ans;
819  }
820 }
static int32 ClusterEventMapRestrictedHelper(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, std::vector< EventKeyType > keys, std::vector< EventMap *> *leaf_mapping)
kaldi::int32 int32
void SplitStatsByKey(const BuildTreeStatsType &stats_in, EventKeyType key, std::vector< BuildTreeStatsType > *stats_out)
SplitStatsByKey splits stats up according to the value of a particular key, which must be always defi...
int ClusterEventMapGetMapping(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, std::vector< EventMap *> *mapping)
"ClusterEventMapGetMapping" clusters the leaves of the EventMap, with "thresh" a delta-likelihood thr...

◆ ClusterKMeansOnce()

BaseFloat kaldi::ClusterKMeansOnce ( const std::vector< Clusterable *> &  points,
int32  num_clust,
std::vector< Clusterable *> *  clusters_out,
std::vector< int32 > *  assignments_out,
ClusterKMeansOptions cfg 
)

ClusterKMeansOnce is called internally by ClusterKMeans; it is equivalent to calling ClusterKMeans with cfg.num_tries == 1.

It returns the objective function improvement versus everything being in one cluster.

Definition at line 918 of file cluster-utils.cc.

References count, Gcd(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, KALDI_WARN, ClusterKMeansOptions::num_iters, Clusterable::Objf(), Rand(), ClusterKMeansOptions::refine_cfg, RefineClusters(), SumClusterable(), SumClusterableNormalizer(), SumClusterableObjf(), and ClusterKMeansOptions::verbose.

Referenced by ClusterKMeans().

922  {
923  std::vector<int32> my_assignments;
924  int32 num_points = points.size();
925  KALDI_ASSERT(clusters_out != NULL);
926  KALDI_ASSERT(num_points != 0);
927  KALDI_ASSERT(num_clust <= num_points);
928 
929  KALDI_ASSERT(clusters_out->empty()); // or we wouldn't know what to do with pointers in there.
930  clusters_out->resize(num_clust, (Clusterable*)NULL);
931  assignments_out->resize(num_points);
932 
933  { // This block assigns points to clusters.
934  // This is done pseudo-randomly using Rand() so that
935  // if we call ClusterKMeans multiple times we get different answers (so we can choose
936  // the best if we want).
937  int32 skip; // randomly choose a "skip" that's coprime to num_points.
938  if (num_points == 1) {
939  skip = 1;
940  } else {
941  skip = 1 + (Rand() % (num_points-1)); // a number between 1 and num_points-1.
942  while (Gcd(skip, num_points) != 1) { // while skip is not coprime to num_points...
943  if (skip == num_points-1) skip = 0;
944  skip++; // skip is now still betweeen 1 and num_points-1. will cycle through
945  // all of 1...num_points-1.
946  }
947  }
948  int32 i, j, count = 0;
949  for (i = 0, j = 0; count != num_points;i = (i+skip)%num_points, j = (j+1)%num_clust, count++) {
950  // i cycles pseudo-randomly through all points; j skips ahead by 1 each time
951  // modulo num_points.
952  // assign point i to cluster j.
953  if ((*clusters_out)[j] == NULL) (*clusters_out)[j] = points[i]->Copy();
954  else (*clusters_out)[j]->Add(*(points[i]));
955  (*assignments_out)[i] = j;
956  }
957  }
958 
959 
960  BaseFloat normalizer = SumClusterableNormalizer(*clusters_out);
961  BaseFloat ans;
962  { // work out initial value of "ans" (objective function improvement).
963  Clusterable *all_stats = SumClusterable(*clusters_out);
964  ans = SumClusterableObjf(*clusters_out) - all_stats->Objf(); // improvement just from the random
965  // initialization.
966  if (ans < -0.01 && ans < -0.01 * fabs(all_stats->Objf())) { // something bad happend.
967  KALDI_WARN << "ClusterKMeans: objective function after random assignment to clusters is worse than in single cluster: "<< (all_stats->Objf()) << " changed by " << ans << ". Perhaps your stats class has the wrong properties?";
968  }
969  delete all_stats;
970  }
971  for (int32 iter = 0;iter < cfg.num_iters;iter++) {
972  // Keep refining clusters by reassigning points.
973  BaseFloat objf_before;
974  if (cfg.verbose) objf_before =SumClusterableObjf(*clusters_out);
975  BaseFloat impr = RefineClusters(points, clusters_out, assignments_out, cfg.refine_cfg);
976  BaseFloat objf_after;
977  if (cfg.verbose) objf_after = SumClusterableObjf(*clusters_out);
978  ans += impr;
979  if (cfg.verbose)
980  KALDI_LOG << "ClusterKMeans: on iteration "<<(iter)<<", objf before = "<<(objf_before)<<", impr = "<<(impr)<<", objf after = "<<(objf_after)<<", normalized by "<<(normalizer)<<" = "<<(objf_after/normalizer);
981  if (impr == 0) break;
982  }
983  return ans;
984 }
BaseFloat RefineClusters(const std::vector< Clusterable *> &points, std::vector< Clusterable *> *clusters, std::vector< int32 > *assignments, RefineClustersOptions cfg)
RefineClusters is mainly used internally by other clustering algorithms.
BaseFloat SumClusterableNormalizer(const std::vector< Clusterable *> &vec)
Returns the total normalizer (usually count) of the cluster (pointers may be NULL).
I Gcd(I m, I n)
Definition: kaldi-math.h:297
kaldi::int32 int32
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
#define KALDI_LOG
Definition: kaldi-error.h:153
Clusterable * SumClusterable(const std::vector< Clusterable *> &vec)
Sums stats (ptrs may be NULL). Returns NULL if no non-NULL stats present.

◆ ClusterLattice()

bool ClusterLattice ( CompactLattice clat,
const std::vector< int32 > &  state_times 
)

Definition at line 40 of file kws-functions.cc.

References CompareInterval(), rnnlm::i, and Interval::Overlap().

Referenced by main().

41  {
42  using namespace fst;
44 
45  // Hashmap to store the cluster heads.
46  unordered_map<StateId, std::vector<Interval> > head;
47 
48  // Step 1: Iterate over the lattice to get the arcs
49  StateId max_id = 0;
50  for (StateIterator<CompactLattice> siter(*clat); !siter.Done();
51  siter.Next()) {
52  StateId state_id = siter.Value();
53  for (ArcIterator<CompactLattice> aiter(*clat, state_id); !aiter.Done();
54  aiter.Next()) {
55  CompactLatticeArc arc = aiter.Value();
56  if (state_id >= state_times.size() || arc.nextstate >= state_times.size())
57  return false;
58  if (state_id > max_id)
59  max_id = state_id;
60  if (arc.nextstate > max_id)
61  max_id = arc.nextstate;
62  head[arc.ilabel].push_back(Interval(state_times[state_id],
63  state_times[arc.nextstate]));
64  }
65  }
66  // Check if alignments and the states match
67  if (state_times.size() != max_id+1)
68  return false;
69 
70  // Step 2: Iterates over the hashmap to get the cluster heads.
71  // We sort all the words on their start-time, and the process for getting
72  // the cluster heads is to take the first one as a cluster head; then go
73  // till we find the next one that doesn't overlap in time with the current
74  // cluster head, and so on.
75  unordered_map<StateId, std::vector<Interval> >::iterator iter;
76  for (iter = head.begin(); iter != head.end(); ++iter) {
77  // For this ilabel, sort all the arcs on time, from first to last.
78  sort(iter->second.begin(), iter->second.end(), CompareInterval);
79  std::vector<Interval> tmp;
80  tmp.push_back(iter->second[0]);
81  for (int32 i = 1; i < iter->second.size(); i++) {
82  if (tmp.back().End() <= iter->second[i].Start())
83  tmp.push_back(iter->second[i]);
84  }
85  iter->second = tmp;
86  }
87 
88  // Step 3: Cluster arcs according to the maximum overlap: attach
89  // each arc to the cluster-head (as identified in Step 2) which
90  // has the most temporal overlap with the current arc.
91  for (StateIterator<CompactLattice> siter(*clat); !siter.Done();
92  siter.Next()) {
93  CompactLatticeArc::StateId state_id = siter.Value();
94  for (MutableArcIterator<CompactLattice> aiter(clat, state_id);
95  !aiter.Done(); aiter.Next()) {
96  CompactLatticeArc arc = aiter.Value();
97  // We don't cluster the epsilon arcs
98  if (arc.ilabel == 0)
99  continue;
100  // We cluster the non-epsilon arcs
101  Interval interval(state_times[state_id], state_times[arc.nextstate]);
102  int32 max_overlap = 0;
103  size_t olabel = 1;
104  for (int32 i = 0; i < head[arc.ilabel].size(); i++) {
105  int32 overlap = interval.Overlap(head[arc.ilabel][i]);
106  if (overlap > max_overlap) {
107  max_overlap = overlap;
108  olabel = i + 1; // need non-epsilon label.
109  }
110  }
111  arc.olabel = olabel;
112  aiter.SetValue(arc);
113  }
114  }
115 
116  return true;
117 }
fst::StdArc::StateId StateId
bool CompareInterval(const Interval &i1, const Interval &i2)
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ CompactLatticeDepth()

BaseFloat CompactLatticeDepth ( const CompactLattice clat,
int32 num_frames 
)

Returns the depth of the lattice, defined as the average number of arcs crossing any given frame.

Returns the depth of the lattice, defined as the average number of arcs (or final-prob strings) crossing any given frame.

Returns 1 for empty lattices. Requires that input is topologically sorted.

Returns 1 for empty lattices. Requires that clat is topologically sorted!

Definition at line 628 of file lattice-functions.cc.

References CompactLatticeStateTimes(), and KALDI_ERR.

Referenced by main().

629  {
631  if (clat.Properties(fst::kTopSorted, true) == 0) {
632  KALDI_ERR << "Lattice input to CompactLatticeDepth was not topologically "
633  << "sorted.";
634  }
635  if (clat.Start() == fst::kNoStateId) {
636  *num_frames = 0;
637  return 1.0;
638  }
639  size_t num_arc_frames = 0;
640  int32 t;
641  {
642  vector<int32> state_times;
643  t = CompactLatticeStateTimes(clat, &state_times);
644  }
645  if (num_frames != NULL)
646  *num_frames = t;
647  for (StateId s = 0; s < clat.NumStates(); s++) {
648  for (fst::ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done();
649  aiter.Next()) {
650  const CompactLatticeArc &arc = aiter.Value();
651  num_arc_frames += arc.weight.String().size();
652  }
653  num_arc_frames += clat.Final(s).String().size();
654  }
655  return num_arc_frames / static_cast<BaseFloat>(t);
656 }
fst::StdArc::StateId StateId
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147
int32 CompactLatticeStateTimes(const CompactLattice &lat, vector< int32 > *times)
As LatticeStateTimes, but in the CompactLattice format.
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ CompactLatticeDepthPerFrame()

void CompactLatticeDepthPerFrame ( const CompactLattice clat,
std::vector< int32 > *  depth_per_frame 
)

This function returns, for each frame, the number of arcs crossing that frame.

Definition at line 659 of file lattice-functions.cc.

References CompactLatticeStateTimes(), KALDI_ASSERT, and KALDI_ERR.

Referenced by main().

660  {
662  if (clat.Properties(fst::kTopSorted, true) == 0) {
663  KALDI_ERR << "Lattice input to CompactLatticeDepthPerFrame was not "
664  << "topologically sorted.";
665  }
666  if (clat.Start() == fst::kNoStateId) {
667  depth_per_frame->clear();
668  return;
669  }
670  vector<int32> state_times;
671  int32 T = CompactLatticeStateTimes(clat, &state_times);
672 
673  depth_per_frame->clear();
674  if (T <= 0) {
675  return;
676  } else {
677  depth_per_frame->resize(T, 0);
678  for (StateId s = 0; s < clat.NumStates(); s++) {
679  int32 start_time = state_times[s];
680  for (fst::ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done();
681  aiter.Next()) {
682  const CompactLatticeArc &arc = aiter.Value();
683  int32 len = arc.weight.String().size();
684  for (int32 t = start_time; t < start_time + len; t++) {
685  KALDI_ASSERT(t < T);
686  (*depth_per_frame)[t]++;
687  }
688  }
689  int32 final_len = clat.Final(s).String().size();
690  for (int32 t = start_time; t < start_time + final_len; t++) {
691  KALDI_ASSERT(t < T);
692  (*depth_per_frame)[t]++;
693  }
694  }
695  }
696 }
fst::StdArc::StateId StateId
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
int32 CompactLatticeStateTimes(const CompactLattice &lat, vector< int32 > *times)
As LatticeStateTimes, but in the CompactLattice format.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ CompactLatticeLimitDepth()

void CompactLatticeLimitDepth ( int32  max_arcs_per_frame,
CompactLattice clat 
)

This function limits the depth of the lattice, per frame: that means, it does not allow more than a specified number of arcs active on any given frame.

This can be used to reduce the size of the "very deep" portions of the lattice.

Definition at line 532 of file lattice-functions.cc.

References LatticeArcRecord::arc, CompactLatticeStateTimes(), ComputeLatticeAlphasAndBetas(), fst::ConvertToCost(), KALDI_ASSERT, KALDI_ERR, KALDI_WARN, LatticeArcRecord::logprob, LatticeArcRecord::state, and TopSortCompactLatticeIfNeeded().

Referenced by main().

533  {
534  typedef CompactLatticeArc Arc;
535  typedef Arc::Weight Weight;
536  typedef Arc::StateId StateId;
537 
538  if (clat->Start() == fst::kNoStateId) {
539  KALDI_WARN << "Limiting depth of empty lattice.";
540  return;
541  }
542  if (clat->Properties(fst::kTopSorted, true) == 0) {
543  if (!TopSort(clat))
544  KALDI_ERR << "Topological sorting of lattice failed.";
545  }
546 
547  vector<int32> state_times;
548  int32 T = CompactLatticeStateTimes(*clat, &state_times);
549 
550  // The alpha and beta quantities here are "viterbi" alphas and beta.
551  std::vector<double> alpha;
552  std::vector<double> beta;
553  bool viterbi = true;
554  double best_prob = ComputeLatticeAlphasAndBetas(*clat, viterbi,
555  &alpha, &beta);
556 
557  std::vector<std::vector<LatticeArcRecord> > arc_records(T);
558 
559  StateId num_states = clat->NumStates();
560  for (StateId s = 0; s < num_states; s++) {
561  for (fst::ArcIterator<CompactLattice> aiter(*clat, s); !aiter.Done();
562  aiter.Next()) {
563  const Arc &arc = aiter.Value();
564  LatticeArcRecord arc_record;
565  arc_record.state = s;
566  arc_record.arc = aiter.Position();
567  arc_record.logprob =
568  (alpha[s] + beta[arc.nextstate] - ConvertToCost(arc.weight))
569  - best_prob;
570  KALDI_ASSERT(arc_record.logprob < 0.1); // Should be zero or negative.
571  int32 num_frames = arc.weight.String().size(), start_t = state_times[s];
572  for (int32 t = start_t; t < start_t + num_frames; t++) {
573  KALDI_ASSERT(t < T);
574  arc_records[t].push_back(arc_record);
575  }
576  }
577  }
578  StateId dead_state = clat->AddState(); // A non-coaccesible state which we use
579  // to remove arcs (make them end
580  // there).
581  size_t max_depth = max_depth_per_frame;
582  for (int32 t = 0; t < T; t++) {
583  size_t size = arc_records[t].size();
584  if (size > max_depth) {
585  // we sort from worst to best, so we keep the later-numbered ones,
586  // and delete the lower-numbered ones.
587  size_t cutoff = size - max_depth;
588  std::nth_element(arc_records[t].begin(),
589  arc_records[t].begin() + cutoff,
590  arc_records[t].end());
591  for (size_t index = 0; index < cutoff; index++) {
592  LatticeArcRecord record(arc_records[t][index]);
593  fst::MutableArcIterator<CompactLattice> aiter(clat, record.state);
594  aiter.Seek(record.arc);
595  Arc arc = aiter.Value();
596  if (arc.nextstate != dead_state) { // not already killed.
597  arc.nextstate = dead_state;
598  aiter.SetValue(arc);
599  }
600  }
601  }
602  }
603  Connect(clat);
605 }
fst::StdArc::StateId StateId
kaldi::int32 int32
double ConvertToCost(const LatticeWeightTpl< Float > &w)
#define KALDI_ERR
Definition: kaldi-error.h:147
int32 CompactLatticeStateTimes(const CompactLattice &lat, vector< int32 > *times)
As LatticeStateTimes, but in the CompactLattice format.
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42
void TopSortCompactLatticeIfNeeded(CompactLattice *clat)
Topologically sort the compact lattice if not already topologically sorted.
template double ComputeLatticeAlphasAndBetas(const CompactLattice &lat, bool viterbi, vector< double > *alpha, vector< double > *beta)

◆ CompactLatticeNormalize()

bool kaldi::CompactLatticeNormalize ( CompactLattice clat,
BaseFloat  weight 
)

Definition at line 54 of file lattice-combine.cc.

References ComputeCompactLatticeBetas(), KALDI_WARN, Log(), LatticeWeightTpl< FloatType >::SetValue1(), CompactLatticeWeightTpl< WeightType, IntType >::SetWeight(), LatticeWeightTpl< FloatType >::Value1(), and CompactLatticeWeightTpl< WeightType, IntType >::Weight().

Referenced by main().

54  {
55  if (weight <= 0.0) {
56  KALDI_WARN << "Weights must be positive; found: " << weight;
57  return false;
58  }
59 
60  if (clat->Properties(fst::kTopSorted, false) == 0) {
61  if (fst::TopSort(clat) == false) {
62  KALDI_WARN << "Cycles detected in lattice: cannot normalize.";
63  return false;
64  }
65  }
66 
67  vector<double> beta;
68  if (!ComputeCompactLatticeBetas(*clat, &beta)) {
69  KALDI_WARN << "Failed to compute backward probabilities on lattice.";
70  return false;
71  }
72 
74  StateId start = clat->Start(); // Should be 0
75  BaseFloat total_backward_cost = beta[start];
76 
77  total_backward_cost -= Log(weight);
78 
79  for (fst::StateIterator<CompactLattice> sit(*clat); !sit.Done(); sit.Next()) {
80  CompactLatticeWeight f = clat->Final(sit.Value());
81  LatticeWeight w = f.Weight();
82  w.SetValue1(w.Value1() + total_backward_cost);
83  f.SetWeight(w);
84  clat->SetFinal(sit.Value(), f);
85  }
86  return true;
87 }
fst::StdArc::StateId StateId
float BaseFloat
Definition: kaldi-types.h:29
double Log(double x)
Definition: kaldi-math.h:100
bool ComputeCompactLatticeBetas(const CompactLattice &clat, vector< double > *beta)
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ CompactLatticeShortestPath()

void CompactLatticeShortestPath ( const CompactLattice clat,
CompactLattice shortest_path 
)

A form of the shortest-path/best-path algorithm that's specially coded for CompactLattice.

Requires that clat be acyclic.

Definition at line 1097 of file lattice-functions.cc.

References fst::ConvertToCost(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, and KALDI_WARN.

Referenced by DecodeUtteranceLatticeIncremental(), GetDiagnosticsAndPrintOutput(), LatticeToString(), and main().

1098  {
1099  using namespace fst;
1100  if (clat.Properties(fst::kTopSorted, true) == 0) {
1101  CompactLattice clat_copy(clat);
1102  if (!TopSort(&clat_copy))
1103  KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
1104  CompactLatticeShortestPath(clat_copy, shortest_path);
1105  return;
1106  }
1107  // Now we can assume it's topologically sorted.
1108  shortest_path->DeleteStates();
1109  if (clat.Start() == kNoStateId) return;
1110  typedef CompactLatticeArc Arc;
1111  typedef Arc::StateId StateId;
1112  typedef CompactLatticeWeight Weight;
1113  vector<std::pair<double, StateId> > best_cost_and_pred(clat.NumStates() + 1);
1114  StateId superfinal = clat.NumStates();
1115  for (StateId s = 0; s <= clat.NumStates(); s++) {
1116  best_cost_and_pred[s].first = std::numeric_limits<double>::infinity();
1117  best_cost_and_pred[s].second = fst::kNoStateId;
1118  }
1119  best_cost_and_pred[clat.Start()].first = 0;
1120  for (StateId s = 0; s < clat.NumStates(); s++) {
1121  double my_cost = best_cost_and_pred[s].first;
1122  for (ArcIterator<CompactLattice> aiter(clat, s);
1123  !aiter.Done();
1124  aiter.Next()) {
1125  const Arc &arc = aiter.Value();
1126  double arc_cost = ConvertToCost(arc.weight),
1127  next_cost = my_cost + arc_cost;
1128  if (next_cost < best_cost_and_pred[arc.nextstate].first) {
1129  best_cost_and_pred[arc.nextstate].first = next_cost;
1130  best_cost_and_pred[arc.nextstate].second = s;
1131  }
1132  }
1133  double final_cost = ConvertToCost(clat.Final(s)),
1134  tot_final = my_cost + final_cost;
1135  if (tot_final < best_cost_and_pred[superfinal].first) {
1136  best_cost_and_pred[superfinal].first = tot_final;
1137  best_cost_and_pred[superfinal].second = s;
1138  }
1139  }
1140  std::vector<StateId> states; // states on best path.
1141  StateId cur_state = superfinal, start_state = clat.Start();
1142  while (cur_state != start_state) {
1143  StateId prev_state = best_cost_and_pred[cur_state].second;
1144  if (prev_state == kNoStateId) {
1145  KALDI_WARN << "Failure in best-path algorithm for lattice (infinite costs?)";
1146  return; // return empty best-path.
1147  }
1148  states.push_back(prev_state);
1149  KALDI_ASSERT(cur_state != prev_state && "Lattice with cycles");
1150  cur_state = prev_state;
1151  }
1152  std::reverse(states.begin(), states.end());
1153  for (size_t i = 0; i < states.size(); i++)
1154  shortest_path->AddState();
1155  for (StateId s = 0; static_cast<size_t>(s) < states.size(); s++) {
1156  if (s == 0) shortest_path->SetStart(s);
1157  if (static_cast<size_t>(s + 1) < states.size()) { // transition to next state.
1158  bool have_arc = false;
1159  Arc cur_arc;
1160  for (ArcIterator<CompactLattice> aiter(clat, states[s]);
1161  !aiter.Done();
1162  aiter.Next()) {
1163  const Arc &arc = aiter.Value();
1164  if (arc.nextstate == states[s+1]) {
1165  if (!have_arc ||
1166  ConvertToCost(arc.weight) < ConvertToCost(cur_arc.weight)) {
1167  cur_arc = arc;
1168  have_arc = true;
1169  }
1170  }
1171  }
1172  KALDI_ASSERT(have_arc && "Code error.");
1173  shortest_path->AddArc(s, Arc(cur_arc.ilabel, cur_arc.olabel,
1174  cur_arc.weight, s+1));
1175  } else { // final-prob.
1176  shortest_path->SetFinal(s, clat.Final(states[s]));
1177  }
1178  }
1179 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
void CompactLatticeShortestPath(const CompactLattice &clat, CompactLattice *shortest_path)
A form of the shortest-path/best-path algorithm that&#39;s specially coded for CompactLattice.
double ConvertToCost(const LatticeWeightTpl< Float > &w)
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ CompactLatticeStateTimes() [1/2]

int32 kaldi::CompactLatticeStateTimes ( const CompactLattice clat,
std::vector< int32 > *  times 
)

As LatticeStateTimes, but in the CompactLattice format.

Note: must be topologically sorted. Returns length of the utterance in frames, which might not be the same as the maximum time in the lattice, due to frames in the final-prob.

Definition at line 111 of file lattice-functions.cc.

References KALDI_ASSERT, KALDI_ERR, KALDI_WARN, and CompactLatticeWeightTpl< WeightType, IntType >::Zero().

Referenced by DiscriminativeNnetExample::Check(), CompactLatticeDepth(), CompactLatticeDepthPerFrame(), CompactLatticeLimitDepth(), kaldi::nnet2::LatticeToDiscriminativeExample(), main(), ArcPosteriorComputer::OutputPosteriors(), MinimumBayesRisk::PrepareLatticeAndInitStats(), and RescoreCompactLatticeInternal().

111  {
112  if (!lat.Properties(fst::kTopSorted, true))
113  KALDI_ERR << "Input lattice must be topologically sorted.";
114  KALDI_ASSERT(lat.Start() == 0);
115  int32 num_states = lat.NumStates();
116  times->clear();
117  times->resize(num_states, -1);
118  (*times)[0] = 0;
119  int32 utt_len = -1;
120  for (int32 state = 0; state < num_states; state++) {
121  int32 cur_time = (*times)[state];
122  for (fst::ArcIterator<CompactLattice> aiter(lat, state); !aiter.Done();
123  aiter.Next()) {
124  const CompactLatticeArc &arc = aiter.Value();
125  int32 arc_len = static_cast<int32>(arc.weight.String().size());
126  if ((*times)[arc.nextstate] == -1)
127  (*times)[arc.nextstate] = cur_time + arc_len;
128  else
129  KALDI_ASSERT((*times)[arc.nextstate] == cur_time + arc_len);
130  }
131  if (lat.Final(state) != CompactLatticeWeight::Zero()) {
132  int32 this_utt_len = (*times)[state] + lat.Final(state).String().size();
133  if (utt_len == -1) utt_len = this_utt_len;
134  else {
135  if (this_utt_len != utt_len) {
136  KALDI_WARN << "Utterance does not "
137  "seem to have a consistent length.";
138  utt_len = std::max(utt_len, this_utt_len);
139  }
140  }
141  }
142  }
143  if (utt_len == -1) {
144  KALDI_WARN << "Utterance does not have a final-state.";
145  return 0;
146  }
147  return utt_len;
148 }
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ CompactLatticeStateTimes() [2/2]

int32 kaldi::CompactLatticeStateTimes ( const CompactLattice clat,
std::vector< int32 > *  times 
)

As LatticeStateTimes, but in the CompactLattice format.

Note: must be topologically sorted. Returns length of the utterance in frames, which might not be the same as the maximum time in the lattice, due to frames in the final-prob.

Definition at line 111 of file lattice-functions.cc.

References KALDI_ASSERT, KALDI_ERR, KALDI_WARN, and CompactLatticeWeightTpl< WeightType, IntType >::Zero().

Referenced by DiscriminativeNnetExample::Check(), CompactLatticeDepth(), CompactLatticeDepthPerFrame(), CompactLatticeLimitDepth(), kaldi::nnet2::LatticeToDiscriminativeExample(), main(), ArcPosteriorComputer::OutputPosteriors(), MinimumBayesRisk::PrepareLatticeAndInitStats(), and RescoreCompactLatticeInternal().

111  {
112  if (!lat.Properties(fst::kTopSorted, true))
113  KALDI_ERR << "Input lattice must be topologically sorted.";
114  KALDI_ASSERT(lat.Start() == 0);
115  int32 num_states = lat.NumStates();
116  times->clear();
117  times->resize(num_states, -1);
118  (*times)[0] = 0;
119  int32 utt_len = -1;
120  for (int32 state = 0; state < num_states; state++) {
121  int32 cur_time = (*times)[state];
122  for (fst::ArcIterator<CompactLattice> aiter(lat, state); !aiter.Done();
123  aiter.Next()) {
124  const CompactLatticeArc &arc = aiter.Value();
125  int32 arc_len = static_cast<int32>(arc.weight.String().size());
126  if ((*times)[arc.nextstate] == -1)
127  (*times)[arc.nextstate] = cur_time + arc_len;
128  else
129  KALDI_ASSERT((*times)[arc.nextstate] == cur_time + arc_len);
130  }
131  if (lat.Final(state) != CompactLatticeWeight::Zero()) {
132  int32 this_utt_len = (*times)[state] + lat.Final(state).String().size();
133  if (utt_len == -1) utt_len = this_utt_len;
134  else {
135  if (this_utt_len != utt_len) {
136  KALDI_WARN << "Utterance does not "
137  "seem to have a consistent length.";
138  utt_len = std::max(utt_len, this_utt_len);
139  }
140  }
141  }
142  }
143  if (utt_len == -1) {
144  KALDI_WARN << "Utterance does not have a final-state.";
145  return 0;
146  }
147  return utt_len;
148 }
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ CompactLatticeToWordAlignment()

bool CompactLatticeToWordAlignment ( const CompactLattice clat,
std::vector< int32 > *  words,
std::vector< int32 > *  begin_times,
std::vector< int32 > *  lengths 
)

This function takes a CompactLattice that should only contain a single linear sequence (e.g.

derived from lattice-1best), and that should have been processed so that the arcs in the CompactLattice align correctly with the word boundaries (e.g. by lattice-align-words). It outputs 3 vectors of the same size, which give, for each word in the lattice (in sequence), the word label and the begin time and length in frames. This is done even for zero (epsilon) words, generally corresponding to optional silence– if you don't want them, just ignore them in the output. This function will print a warning and return false, if the lattice did not have the correct format (e.g. if it is empty or it is not linear).

Definition at line 975 of file lattice-functions.cc.

References KALDI_WARN.

Referenced by main().

978  {
979  words->clear();
980  begin_times->clear();
981  lengths->clear();
982  typedef CompactLattice::Arc Arc;
983  typedef Arc::Label Label;
986  using namespace fst;
987  StateId state = clat.Start();
988  int32 cur_time = 0;
989  if (state == kNoStateId) {
990  KALDI_WARN << "Empty lattice.";
991  return false;
992  }
993  while (1) {
994  Weight final = clat.Final(state);
995  size_t num_arcs = clat.NumArcs(state);
996  if (final != Weight::Zero()) {
997  if (num_arcs != 0) {
998  KALDI_WARN << "Lattice is not linear.";
999  return false;
1000  }
1001  if (! final.String().empty()) {
1002  KALDI_WARN << "Lattice has alignments on final-weight: probably "
1003  "was not word-aligned (alignments will be approximate)";
1004  }
1005  return true;
1006  } else {
1007  if (num_arcs != 1) {
1008  KALDI_WARN << "Lattice is not linear: num-arcs = " << num_arcs;
1009  return false;
1010  }
1011  fst::ArcIterator<CompactLattice> aiter(clat, state);
1012  const Arc &arc = aiter.Value();
1013  Label word_id = arc.ilabel; // Note: ilabel==olabel, since acceptor.
1014  // Also note: word_id may be zero; we output it anyway.
1015  int32 length = arc.weight.String().size();
1016  words->push_back(word_id);
1017  begin_times->push_back(cur_time);
1018  lengths->push_back(length);
1019  cur_time += length;
1020  state = arc.nextstate;
1021  }
1022  }
1023 }
int32 words[kMaxOrder]
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Label Label
fst::StdArc::Weight Weight

◆ CompactLatticeToWordProns()

bool CompactLatticeToWordProns ( const TransitionModel tmodel,
const CompactLattice clat,
std::vector< int32 > *  words,
std::vector< int32 > *  begin_times,
std::vector< int32 > *  lengths,
std::vector< std::vector< int32 > > *  prons,
std::vector< std::vector< int32 > > *  phone_lengths 
)

This function takes a CompactLattice that should only contain a single linear sequence (e.g.

derived from lattice-1best), and that should have been processed so that the arcs in the CompactLattice align correctly with the word boundaries (e.g. by lattice-align-words). It outputs 4 vectors of the same size, which give, for each word in the lattice (in sequence), the word label, the begin time and length in frames, and the pronunciation (sequence of phones). This is done even for zero words, corresponding to optional silences – if you don't want them, just ignore them in the output. This function will print a warning and return false, if the lattice did not have the correct format (e.g. if it is empty or it is not linear).

Definition at line 1026 of file lattice-functions.cc.

References rnnlm::i, KALDI_ASSERT, KALDI_WARN, SplitToPhones(), and TransitionModel::TransitionIdToPhone().

Referenced by main().

1033  {
1034  words->clear();
1035  begin_times->clear();
1036  lengths->clear();
1037  prons->clear();
1038  phone_lengths->clear();
1039  typedef CompactLattice::Arc Arc;
1040  typedef Arc::Label Label;
1043  using namespace fst;
1044  StateId state = clat.Start();
1045  int32 cur_time = 0;
1046  if (state == kNoStateId) {
1047  KALDI_WARN << "Empty lattice.";
1048  return false;
1049  }
1050  while (1) {
1051  Weight final = clat.Final(state);
1052  size_t num_arcs = clat.NumArcs(state);
1053  if (final != Weight::Zero()) {
1054  if (num_arcs != 0) {
1055  KALDI_WARN << "Lattice is not linear.";
1056  return false;
1057  }
1058  if (! final.String().empty()) {
1059  KALDI_WARN << "Lattice has alignments on final-weight: probably "
1060  "was not word-aligned (alignments will be approximate)";
1061  }
1062  return true;
1063  } else {
1064  if (num_arcs != 1) {
1065  KALDI_WARN << "Lattice is not linear: num-arcs = " << num_arcs;
1066  return false;
1067  }
1068  fst::ArcIterator<CompactLattice> aiter(clat, state);
1069  const Arc &arc = aiter.Value();
1070  Label word_id = arc.ilabel; // Note: ilabel==olabel, since acceptor.
1071  // Also note: word_id may be zero; we output it anyway.
1072  int32 length = arc.weight.String().size();
1073  words->push_back(word_id);
1074  begin_times->push_back(cur_time);
1075  lengths->push_back(length);
1076  const std::vector<int32> &arc_alignment = arc.weight.String();
1077  std::vector<std::vector<int32> > split_alignment;
1078  SplitToPhones(tmodel, arc_alignment, &split_alignment);
1079  std::vector<int32> phones(split_alignment.size());
1080  std::vector<int32> plengths(split_alignment.size());
1081  for (size_t i = 0; i < split_alignment.size(); i++) {
1082  KALDI_ASSERT(!split_alignment[i].empty());
1083  phones[i] = tmodel.TransitionIdToPhone(split_alignment[i][0]);
1084  plengths[i] = split_alignment[i].size();
1085  }
1086  prons->push_back(phones);
1087  phone_lengths->push_back(plengths);
1088 
1089  cur_time += length;
1090  state = arc.nextstate;
1091  }
1092  }
1093 }
int32 words[kMaxOrder]
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
bool SplitToPhones(const TransitionModel &trans_model, const std::vector< int32 > &alignment, std::vector< std::vector< int32 > > *split_alignment)
SplitToPhones splits up the TransitionIds in "alignment" into their individual phones (one vector per...
Definition: hmm-utils.cc:723
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Label Label
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CompareInterval()

bool CompareInterval ( const Interval i1,
const Interval i2 
)

Definition at line 33 of file kws-functions.cc.

References Interval::End(), and Interval::Start().

Referenced by ClusterLattice().

34  {
35  return (i1.Start() < i2.Start() ? true :
36  i1.Start() > i2.Start() ? false:
37  i1.End() < i2.End() ? true: false);
38 }

◆ Compile()

ArpaLmCompiler* kaldi::Compile ( bool  seps,
const std::string &  infile 
)

Definition at line 75 of file arpa-lm-compiler-test.cc.

References ArpaParseOptions::bos_symbol, ArpaParseOptions::eos_symbol, ArpaParseOptions::kAddToSymbols, kBos, kDisambig, kEos, kEps, ArpaParseOptions::oov_handling, ArpaFileParser::Read(), and Input::Stream().

Referenced by CoverageTest(), ScoringTest(), and ThrowsExceptionTest().

75  {
76  ArpaParseOptions options;
77  fst::SymbolTable symbols;
78  // Use spaces on special symbols, so we rather fail than read them by mistake.
79  symbols.AddSymbol(" <eps>", kEps);
80  symbols.AddSymbol(" #0", kDisambig);
81  options.bos_symbol = symbols.AddSymbol("<s>", kBos);
82  options.eos_symbol = symbols.AddSymbol("</s>", kEos);
83  options.oov_handling = ArpaParseOptions::kAddToSymbols;
84 
85  // Tests in this form cannot be run with epsilon substitution, unless every
86  // random path is also fitted with a #0-transducing self-loop.
87  ArpaLmCompiler* lm_compiler =
88  new ArpaLmCompiler(options,
89  seps ? kDisambig : 0,
90  &symbols);
91  {
92  Input ki(infile);
93  lm_compiler->Read(ki.Stream());
94  }
95  return lm_compiler;
96 }

◆ ComplexFft() [1/2]

template void kaldi::ComplexFft ( VectorBase< float > *  v,
bool  forward,
Vector< float > *  tmp_in 
)

◆ ComplexFft() [2/2]

template void kaldi::ComplexFft ( VectorBase< double > *  v,
bool  forward,
Vector< double > *  tmp_in 
)

◆ ComplexFftRecursive()

void kaldi::ComplexFftRecursive ( Real *  data,
int  nffts,
int  N,
const int *  factor_begin,
const int *  factor_end,
bool  forward,
Vector< Real > *  tmp_vec 
)

ComplexFftRecursive is a recursive function that computes the complex FFT of size N.

The "nffts" arguments specifies how many separate FFTs to compute in parallel (we assume the data for each one is consecutive in memory). The "forward argument" specifies whether to do the FFT (true) or IFFT (false), although note that we do not include the factor of 1/N (the user should do this if required. The iterators factor_begin and factor_end point to the beginning and end (i.e. one past the last element) of an array of small factors of N (typically prime factors). See the comments below this code for the detailed equations of the recursion.

Definition at line 97 of file matrix-functions.cc.

References ComplexAddProduct(), ComplexImExp(), ComplexMul(), VectorBase< Real >::Data(), VectorBase< Real >::Dim(), KALDI_ASSERT, KALDI_COMPLEXFFT_BLOCKSIZE, M_2PI, rnnlm::n, and Vector< Real >::Resize().

Referenced by ComplexFft().

100  {
101  if (factor_begin == factor_end) {
102  KALDI_ASSERT(N == 1);
103  return;
104  }
105 
106  { // an optimization: compute in smaller blocks.
107  // this block of code could be removed and it would still work.
108  MatrixIndexT size_perblock = N * 2 * sizeof(Real);
109  if (nffts > 1 && size_perblock*nffts > KALDI_COMPLEXFFT_BLOCKSIZE) { // can break it up...
110  // Break up into multiple blocks. This is an optimization. We make
111  // no progress on the FFT when we do this.
112  int block_skip = KALDI_COMPLEXFFT_BLOCKSIZE / size_perblock; // n blocks per call
113  if (block_skip == 0) block_skip = 1;
114  if (block_skip < nffts) {
115  int blocks_left = nffts;
116  while (blocks_left > 0) {
117  int skip_now = std::min(blocks_left, block_skip);
118  ComplexFftRecursive(data, skip_now, N, factor_begin, factor_end, forward, tmp_vec);
119  blocks_left -= skip_now;
120  data += skip_now * N*2;
121  }
122  return;
123  } // else do the actual algorithm.
124  } // else do the actual algorithm.
125  }
126 
127  int P = *factor_begin;
128  KALDI_ASSERT(P > 1);
129  int Q = N / P;
130 
131 
132  if (P > 1 && Q > 1) { // Do the rearrangement. C.f. eq. (8) below. Transform
133  // (a) to (b).
134  Real *data_thisblock = data;
135  if (tmp_vec->Dim() < (MatrixIndexT)N) tmp_vec->Resize(N);
136  Real *data_tmp = tmp_vec->Data();
137  for (int thisfft = 0; thisfft < nffts; thisfft++, data_thisblock+=N*2) {
138  for (int offset = 0; offset < 2; offset++) { // 0 == real, 1 == im.
139  for (int p = 0; p < P; p++) {
140  for (int q = 0; q < Q; q++) {
141  int aidx = q*P + p, bidx = p*Q + q;
142  data_tmp[bidx] = data_thisblock[2*aidx+offset];
143  }
144  }
145  for (int n = 0;n < P*Q;n++) data_thisblock[2*n+offset] = data_tmp[n];
146  }
147  }
148  }
149 
150  { // Recurse.
151  ComplexFftRecursive(data, nffts*P, Q, factor_begin+1, factor_end, forward, tmp_vec);
152  }
153 
154  int exp_sign = (forward ? -1 : 1);
155  Real rootN_re, rootN_im; // Nth root of unity.
156  ComplexImExp(static_cast<Real>(exp_sign * M_2PI / N), &rootN_re, &rootN_im);
157 
158  Real rootP_re, rootP_im; // Pth root of unity.
159  ComplexImExp(static_cast<Real>(exp_sign * M_2PI / P), &rootP_re, &rootP_im);
160 
161  { // Do the multiplication
162  // could avoid a bunch of complex multiplies by moving the loop over data_thisblock
163  // inside.
164  if (tmp_vec->Dim() < (MatrixIndexT)(P*2)) tmp_vec->Resize(P*2);
165  Real *temp_a = tmp_vec->Data();
166 
167  Real *data_thisblock = data, *data_end = data+(N*2*nffts);
168  for (; data_thisblock != data_end; data_thisblock += N*2) { // for each separate fft.
169  Real qd_re = 1.0, qd_im = 0.0; // 1^(q'/N)
170  for (int qd = 0; qd < Q; qd++) {
171  Real pdQ_qd_re = qd_re, pdQ_qd_im = qd_im; // 1^((p'Q+q') / N) == 1^((p'/P) + (q'/N))
172  // Initialize to q'/N, corresponding to p' == 0.
173  for (int pd = 0; pd < P; pd++) { // pd == p'
174  { // This is the p = 0 case of the loop below [an optimization].
175  temp_a[pd*2] = data_thisblock[qd*2];
176  temp_a[pd*2 + 1] = data_thisblock[qd*2 + 1];
177  }
178  { // This is the p = 1 case of the loop below [an optimization]
179  // **** MOST OF THE TIME (>60% I think) gets spent here. ***
180  ComplexAddProduct(pdQ_qd_re, pdQ_qd_im,
181  data_thisblock[(qd+Q)*2], data_thisblock[(qd+Q)*2 + 1],
182  &(temp_a[pd*2]), &(temp_a[pd*2 + 1]));
183  }
184  if (P > 2) {
185  Real p_pdQ_qd_re = pdQ_qd_re, p_pdQ_qd_im = pdQ_qd_im; // 1^(p(p'Q+q')/N)
186  for (int p = 2; p < P; p++) {
187  ComplexMul(pdQ_qd_re, pdQ_qd_im, &p_pdQ_qd_re, &p_pdQ_qd_im); // p_pdQ_qd *= pdQ_qd.
188  int data_idx = p*Q + qd;
189  ComplexAddProduct(p_pdQ_qd_re, p_pdQ_qd_im,
190  data_thisblock[data_idx*2], data_thisblock[data_idx*2 + 1],
191  &(temp_a[pd*2]), &(temp_a[pd*2 + 1]));
192  }
193  }
194  if (pd != P-1)
195  ComplexMul(rootP_re, rootP_im, &pdQ_qd_re, &pdQ_qd_im); // pdQ_qd *= (rootP == 1^{1/P})
196  // (using 1/P == Q/N)
197  }
198  for (int pd = 0; pd < P; pd++) {
199  data_thisblock[(pd*Q + qd)*2] = temp_a[pd*2];
200  data_thisblock[(pd*Q + qd)*2 + 1] = temp_a[pd*2 + 1];
201  }
202  ComplexMul(rootN_re, rootN_im, &qd_re, &qd_im); // qd *= rootN.
203  }
204  }
205  }
206 }
void ComplexFftRecursive(Real *data, int nffts, int N, const int *factor_begin, const int *factor_end, bool forward, Vector< Real > *tmp_vec)
ComplexFftRecursive is a recursive function that computes the complex FFT of size N...
int32 MatrixIndexT
Definition: matrix-common.h:98
void ComplexAddProduct(const Real &a_re, const Real &a_im, const Real &b_re, const Real &b_im, Real *c_re, Real *c_im)
ComplexMul implements, inline, the complex operation c += (a * b).
struct rnnlm::@11::@12 n
void ComplexMul(const Real &a_re, const Real &a_im, Real *b_re, Real *b_im)
ComplexMul implements, inline, the complex multiplication b *= a.
#define KALDI_COMPLEXFFT_BLOCKSIZE
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define M_2PI
Definition: kaldi-math.h:52
void ComplexImExp(Real x, Real *a_re, Real *a_im)
ComplexImExp implements a <– exp(i x), inline.

◆ ComplexFt() [1/2]

template void kaldi::ComplexFt ( const VectorBase< float > &  in,
VectorBase< float > *  out,
bool  forward 
)

◆ ComplexFt() [2/2]

template void kaldi::ComplexFt ( const VectorBase< double > &  in,
VectorBase< double > *  out,
bool  forward 
)

◆ ComposeCompactLatticeDeterministic()

void ComposeCompactLatticeDeterministic ( const CompactLattice clat,
fst::DeterministicOnDemandFst< fst::StdArc > *  det_fst,
CompactLattice composed_clat 
)

This function Composes a CompactLattice format lattice with a DeterministicOnDemandFst<fst::StdFst> format fst, and outputs another CompactLattice format lattice.

The first element (the one that corresponds to LM weight) in CompactLatticeWeight is used for composition.

Note that the DeterministicOnDemandFst interface is not "const", therefore we cannot use "const" for <det_fst>.

Definition at line 1528 of file lattice-functions.cc.

References DeterministicOnDemandFst< Arc >::Final(), DeterministicOnDemandFst< Arc >::GetArc(), KALDI_ASSERT, and DeterministicOnDemandFst< Arc >::Start().

Referenced by main().

1531  {
1532  // StdFst::Arc and CompactLatticeArc has the same StateId type.
1533  typedef fst::StdArc::StateId StateId;
1534  typedef fst::StdArc::Weight Weight1;
1535  typedef CompactLatticeArc::Weight Weight2;
1536  typedef std::pair<StateId, StateId> StatePair;
1537  typedef unordered_map<StatePair, StateId, PairHasher<StateId> > MapType;
1538  typedef MapType::iterator IterType;
1539 
1540  // Empties the output FST.
1541  KALDI_ASSERT(composed_clat != NULL);
1542  composed_clat->DeleteStates();
1543 
1544  MapType state_map;
1545  std::queue<StatePair> state_queue;
1546 
1547  // Sets start state in <composed_clat>.
1548  StateId start_state = composed_clat->AddState();
1549  StatePair start_pair(clat.Start(), det_fst->Start());
1550  composed_clat->SetStart(start_state);
1551  state_queue.push(start_pair);
1552  std::pair<IterType, bool> result =
1553  state_map.insert(std::make_pair(start_pair, start_state));
1554  KALDI_ASSERT(result.second == true);
1555 
1556  // Starts composition here.
1557  while (!state_queue.empty()) {
1558  // Gets the first state in the queue.
1559  StatePair s = state_queue.front();
1560  StateId s1 = s.first;
1561  StateId s2 = s.second;
1562  state_queue.pop();
1563 
1564 
1565  Weight2 clat_final = clat.Final(s1);
1566  if (clat_final.Weight().Value1() !=
1567  std::numeric_limits<BaseFloat>::infinity()) {
1568  // Test for whether the final-prob of state s1 was zero.
1569  Weight1 det_fst_final = det_fst->Final(s2);
1570  if (det_fst_final.Value() !=
1571  std::numeric_limits<BaseFloat>::infinity()) {
1572  // Test for whether the final-prob of state s2 was zero. If neither
1573  // source-state final prob was zero, then we should create final state
1574  // in fst_composed. We compute the product manually since this is more
1575  // efficient.
1576  Weight2 final_weight(LatticeWeight(clat_final.Weight().Value1() +
1577  det_fst_final.Value(),
1578  clat_final.Weight().Value2()),
1579  clat_final.String());
1580  // we can assume final_weight is not Zero(), since neither of
1581  // the sources was zero.
1582  KALDI_ASSERT(state_map.find(s) != state_map.end());
1583  composed_clat->SetFinal(state_map[s], final_weight);
1584  }
1585  }
1586 
1587  // Loops over pair of edges at s1 and s2.
1588  for (fst::ArcIterator<CompactLattice> aiter(clat, s1);
1589  !aiter.Done(); aiter.Next()) {
1590  const CompactLatticeArc& arc1 = aiter.Value();
1591  fst::StdArc arc2;
1592  StateId next_state1 = arc1.nextstate, next_state2;
1593  bool matched = false;
1594 
1595  if (arc1.olabel == 0) {
1596  // If the symbol on <arc1> is <epsilon>, we transit to the next state
1597  // for <clat>, but keep <det_fst> at the current state.
1598  matched = true;
1599  next_state2 = s2;
1600  } else {
1601  // Otherwise try to find the matched arc in <det_fst>.
1602  matched = det_fst->GetArc(s2, arc1.olabel, &arc2);
1603  if (matched) {
1604  next_state2 = arc2.nextstate;
1605  }
1606  }
1607 
1608  // If matched arc is found in <det_fst>, then we have to add new arcs to
1609  // <composed_clat>.
1610  if (matched) {
1611  StatePair next_state_pair(next_state1, next_state2);
1612  IterType siter = state_map.find(next_state_pair);
1613  StateId next_state;
1614 
1615  // Adds composed state to <state_map>.
1616  if (siter == state_map.end()) {
1617  // If the composed state has not been created yet, create it.
1618  next_state = composed_clat->AddState();
1619  std::pair<const StatePair, StateId> next_state_map(next_state_pair,
1620  next_state);
1621  std::pair<IterType, bool> result = state_map.insert(next_state_map);
1622  KALDI_ASSERT(result.second);
1623  state_queue.push(next_state_pair);
1624  } else {
1625  // If the composed state is already in <state_map>, we can directly
1626  // use that.
1627  next_state = siter->second;
1628  }
1629 
1630  // Adds arc to <composed_clat>.
1631  if (arc1.olabel == 0) {
1632  composed_clat->AddArc(state_map[s],
1633  CompactLatticeArc(arc1.ilabel, 0,
1634  arc1.weight, next_state));
1635  } else {
1636  Weight2 composed_weight(
1637  LatticeWeight(arc1.weight.Weight().Value1() +
1638  arc2.weight.Value(),
1639  arc1.weight.Weight().Value2()),
1640  arc1.weight.String());
1641  composed_clat->AddArc(state_map[s],
1642  CompactLatticeArc(arc1.ilabel, arc2.olabel,
1643  composed_weight, next_state));
1644  }
1645  }
1646  }
1647  }
1648  fst::Connect(composed_clat);
1649 }
fst::StdArc::StateId StateId
virtual bool GetArc(StateId s, Label ilabel, Arc *oarc)=0
Note: ilabel must not be epsilon.
virtual Weight Final(StateId s)=0
fst::StdArc StdArc
virtual StateId Start()=0
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
LatticeWeightTpl< BaseFloat > LatticeWeight
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ ComposeCompactLatticePruned()

void ComposeCompactLatticePruned ( const ComposeLatticePrunedOptions opts,
const CompactLattice clat,
fst::DeterministicOnDemandFst< fst::StdArc > *  det_fst,
CompactLattice composed_clat 
)

Does pruned composition of a lattice 'clat' with a DeterministicOnDemandFst 'det_fst'; implements LM rescoring.

Parameters
[in]optsClass containing options
[in]clatThe input lattice, which is expected to already have a reasonable acoustic scale applied (e.g. 0.1 if it's a normal cross-entropy system, but 1.0 for a chain system); this scale affects the pruning.
[in]det_fstThe on-demand FST that we are composing with; its ilabels will correspond to words and it should be an acceptor in practice (ilabel == olabel). Will often contain a weighted difference of language model scores, with scores of the form alpha * new - alpha * old, where alpha is the interpolation weight for the 'new' language model (e.g. 0.5 or 0.8). It's non-const because 'det_fst' is on-demand.
[out]composed_clatThe output, which is a result of composing 'clat' with '*det_fst'. Notionally, '*det_fst' is on the right, although both are acceptors so it doesn't really matter in practice. Although the two FSTs are of different types, the code manually does the conversion. The weights in '*det_fst' will be interpreted as graph weights (Value1()) in the lattice semiring.

Definition at line 946 of file compose-lattice-pruned.cc.

References PrunedCompactLatticeComposer::Compose().

Referenced by main(), and ComposeLatticePrunedOptions::Register().

950  {
951  PrunedCompactLatticeComposer composer(opts, clat, det_fst, composed_clat);
952  composer.Compose();
953 }

◆ ComposeTransforms()

bool ComposeTransforms ( const Matrix< BaseFloat > &  a,
const Matrix< BaseFloat > &  b,
bool  b_is_affine,
Matrix< BaseFloat > *  c 
)

Definition at line 132 of file transform-common.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::CopyFromMat(), KALDI_ERR, KALDI_WARN, kNoTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and Matrix< Real >::Resize().

Referenced by AffineXformStats::AffineXformStats(), LinearVtln::ComputeTransform(), and main().

134  {
135  if (b.NumRows() == 0 || a.NumCols() == 0) {
136  KALDI_WARN << "Empty matrix in ComposeTransforms";
137  return false;
138  }
139  if (a.NumCols() == b.NumRows()) {
140  c->Resize(a.NumRows(), b.NumCols());
141  c->AddMatMat(1.0, a, kNoTrans, b, kNoTrans, 0.0); // c = a * b.
142  return true;
143  } else if (a.NumCols() == b.NumRows()+1) { // a is affine.
144  if (b_is_affine) { // append 0 0 0 0 ... 1 to b and multiply.
145  Matrix<BaseFloat> b_ext(b.NumRows()+1, b.NumCols());
146  SubMatrix<BaseFloat> b_part(b_ext, 0, b.NumRows(), 0, b.NumCols());
147  b_part.CopyFromMat(b);
148  b_ext(b.NumRows(), b.NumCols()-1) = 1.0; // so the last row is 0 0 0 0 ... 0 1
149  c->Resize(a.NumRows(), b.NumCols());
150  c->AddMatMat(1.0, a, kNoTrans, b_ext, kNoTrans, 0.0); // c = a * b_ext.
151  } else { // extend b by 1 row and column with all zeros except a 1 on diagonal.
152  Matrix<BaseFloat> b_ext(b.NumRows()+1, b.NumCols()+1);
153  SubMatrix<BaseFloat> b_part(b_ext, 0, b.NumRows(), 0, b.NumCols());
154  b_part.CopyFromMat(b);
155  b_ext(b.NumRows(), b.NumCols()) = 1.0; // so the last row is 0 0 0 0 ... 0 1;
156  // rest of last column is zero (this is the offset term)
157  c->Resize(a.NumRows(), b.NumCols()+1);
158  c->AddMatMat(1.0, a, kNoTrans, b_ext, kNoTrans, 0.0); // c = a * b_ext.
159  }
160  return true;
161  } else {
162  KALDI_ERR << "ComposeTransforms: mismatched dimensions, a has " << a.NumCols()
163  << " columns and b has " << b.NumRows() << " rows."; // this is fatal.
164  return false;
165  }
166 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
void AddMatMat(const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ ComputeAcousticScoresMap()

void ComputeAcousticScoresMap ( const Lattice lat,
unordered_map< std::pair< int32, int32 >, std::pair< BaseFloat, int32 >, PairHasher< int32 > > *  acoustic_scores 
)

This function computes the mapping from the pair (frame-index, transition-id) to the pair (sum-of-acoustic-scores, num-of-occurences) over all occurences of the transition-id in that frame.

frame-index in the lattice. This function is useful for retaining the acoustic scores in a non-compact lattice after a process like determinization where the frame-level acoustic scores are typically lost. The function ReplaceAcousticScoresFromMap is used to restore the acoustic scores computed by this function.

Parameters
[in]latInput lattice. Expected to be top-sorted. Otherwise the function will crash.
[out]acoustic_scoresPointer to a map from the pair (frame-index, transition-id) to a pair (sum-of-acoustic-scores, num-of-occurences). Usually the acoustic scores for a pdf-id (and hence transition-id) on a frame will be the same for all the occurences of the pdf-id in that frame. But if not, we will take the average of the acoustic scores. Hence, we store both the sum-of-acoustic-scores and the num-of-occurences of the transition-id in that frame.

Definition at line 1652 of file lattice-functions.cc.

References KALDI_ASSERT, KALDI_VLOG, LatticeStateTimes(), LatticeWeightTpl< FloatType >::Value2(), and LatticeWeightTpl< BaseFloat >::Zero().

Referenced by main().

1655  {
1656  // typedef the arc, weight types
1657  typedef Lattice::Arc Arc;
1658  typedef Arc::Weight LatticeWeight;
1659  typedef Arc::StateId StateId;
1660 
1661  acoustic_scores->clear();
1662 
1663  std::vector<int32> state_times;
1664  LatticeStateTimes(lat, &state_times); // Assumes the input is top sorted
1665 
1666  KALDI_ASSERT(lat.Start() == 0);
1667 
1668  for (StateId s = 0; s < lat.NumStates(); s++) {
1669  int32 t = state_times[s];
1670  for (fst::ArcIterator<Lattice> aiter(lat, s); !aiter.Done();
1671  aiter.Next()) {
1672  const Arc &arc = aiter.Value();
1673  const LatticeWeight &weight = arc.weight;
1674 
1675  int32 tid = arc.ilabel;
1676 
1677  if (tid != 0) {
1678  unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
1679  PairHasher<int32> >::iterator it = acoustic_scores->find(std::make_pair(t, tid));
1680  if (it == acoustic_scores->end()) {
1681  acoustic_scores->insert(std::make_pair(std::make_pair(t, tid),
1682  std::make_pair(weight.Value2(), 1)));
1683  } else {
1684  if (it->second.second == 2
1685  && it->second.first / it->second.second != weight.Value2()) {
1686  KALDI_VLOG(2) << "Transitions on the same frame have different "
1687  << "acoustic costs for tid " << tid << "; "
1688  << it->second.first / it->second.second
1689  << " vs " << weight.Value2();
1690  }
1691  it->second.first += weight.Value2();
1692  it->second.second++;
1693  }
1694  } else {
1695  // Arcs with epsilon input label (tid) must have 0 acoustic cost
1696  KALDI_ASSERT(weight.Value2() == 0);
1697  }
1698  }
1699 
1700  LatticeWeight f = lat.Final(s);
1701  if (f != LatticeWeight::Zero()) {
1702  // Final acoustic cost must be 0 as we are reading from
1703  // non-determinized, non-compact lattice
1704  KALDI_ASSERT(f.Value2() == 0.0);
1705  }
1706  }
1707 }
fst::StdArc::StateId StateId
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
kaldi::int32 int32
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
LatticeWeightTpl< BaseFloat > LatticeWeight

◆ ComputeAmGmmFeatureDeriv()

BaseFloat ComputeAmGmmFeatureDeriv ( const AmDiagGmm am_gmm,
const TransitionModel trans_model,
const Posterior posterior,
const MatrixBase< BaseFloat > &  features,
Matrix< BaseFloat > *  direct_deriv,
const AccumAmDiagGmm model_diff = NULL,
Matrix< BaseFloat > *  indirect_deriv = NULL 
)

Computes derivatives of the likelihood of these states (weighted), w.r.t.

the feature values. Used in fMPE training. Note, the weights "posterior" may be positive or negative– for MMI, MPE, etc., they will typically be of both signs. Will resize "deriv". Returns the sum of (GMM likelihood * weight), which may be used as an approximation to the objective function. Last two parameters are optional. See GetStatsDerivative() for or fMPE paper (ICASSP, 2005) more info on indirect derivative. Caution: if you supply the last two parameters, this function only works in the MMI case as it assumes the stats with positive weight are numerator == ml stats– this is only the same thing in the MMI case, not fMPE.

Definition at line 522 of file fmpe.cc.

References VectorBase< Real >::AddMatVec(), VectorBase< Real >::AddVec(), VectorBase< Real >::AddVecVec(), DiagGmm::ComponentPosteriors(), AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), rnnlm::i, DiagGmm::inv_vars(), rnnlm::j, KALDI_ASSERT, kTrans, AccumDiagGmm::mean_accumulator(), DiagGmm::means_invvars(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Matrix< Real >::Resize(), VectorBase< Real >::Scale(), TransitionModel::TransitionIdToPdf(), and AccumDiagGmm::variance_accumulator().

Referenced by main().

528  {
529  KALDI_ASSERT((model_diff != NULL) == (indirect_deriv != NULL));
530  BaseFloat ans = 0.0;
531  KALDI_ASSERT(posterior.size() == static_cast<size_t>(features.NumRows()));
532  direct_deriv->Resize(features.NumRows(), features.NumCols());
533  if (indirect_deriv != NULL)
534  indirect_deriv->Resize(features.NumRows(), features.NumCols());
535  Vector<BaseFloat> temp_vec(features.NumCols());
536  Vector<double> temp_vec_dbl(features.NumCols());
537  for (size_t i = 0; i < posterior.size(); i++) {
538  for (size_t j = 0; j < posterior[i].size(); j++) {
539  int32 tid = posterior[i][j].first, // transition identifier.
540  pdf_id = trans_model.TransitionIdToPdf(tid);
541  BaseFloat weight = posterior[i][j].second;
542  const DiagGmm &gmm = am_gmm.GetPdf(pdf_id);
543  Vector<BaseFloat> gauss_posteriors;
544  SubVector<BaseFloat> this_feat(features, i);
545  SubVector<BaseFloat> this_direct_deriv(*direct_deriv, i);
546  ans += weight *
547  gmm.ComponentPosteriors(this_feat, &gauss_posteriors);
548 
549  gauss_posteriors.Scale(weight);
550  // The next line does: to i'th row of deriv, add
551  // means_invvars^T * gauss_posteriors,
552  // where each row of means_invvars is the mean times
553  // diagonal inverse covariance... after transposing,
554  // this becomes a weighted of these rows, weighted by
555  // the posteriors. This comes from the term
556  // feat^T * inv_var * mean
557  // in the objective function.
558  this_direct_deriv.AddMatVec(1.0, gmm.means_invvars(), kTrans,
559  gauss_posteriors, 1.0);
560 
561  // next line does temp_vec == inv_vars^T * gauss_posteriors,
562  // which sets temp_vec to a weighted sum of the inv_vars,
563  // weighed by Gaussian posterior.
564  temp_vec.AddMatVec(1.0, gmm.inv_vars(), kTrans,
565  gauss_posteriors, 0.0);
566  // Add to the derivative, -(this_feat .* temp_vec),
567  // which is the term that comes from the -0.5 * inv_var^T feat_sq,
568  // in the objective function (where inv_var is a vector, and feat_sq
569  // is a vector of squares of the feature values).
570  // Note: we have to do some messing about with double-precision here
571  // because the stats only come in double precision.
572  this_direct_deriv.AddVecVec(-1.0, this_feat, temp_vec, 1.0);
573  if (model_diff != NULL && weight > 0.0) { // We need to get the indirect diff.
574  // This "weight > 0.0" checks that this is the numerator stats, as the
575  // fMPE indirect diff applies only to the ML stats-- CAUTION, this
576  // code will only work as-is for fMMI (and the stats should not be
577  // canceled), due to the assumption that ML stats == num stats.
578  Vector<double> gauss_posteriors_dbl(gauss_posteriors);
579  const AccumDiagGmm &deriv_acc = model_diff->GetAcc(pdf_id);
580  // part of the derivative. Note: we could just store the direct and
581  // indirect derivatives together in one matrix, but it makes it easier
582  // to accumulate certain diagnostics if we store them separately.
583  SubVector<BaseFloat> this_indirect_deriv(*indirect_deriv, i);
584  // note: deriv_acc.mean_accumulator() contains the derivative of
585  // the objective function w.r.t. the "x stats" accumulated for
586  // this GMM. variance_accumulator() is the same for the "x^2 stats".
587  temp_vec_dbl.AddMatVec(1.0, deriv_acc.mean_accumulator(), kTrans,
588  gauss_posteriors_dbl, 0.0);
589  this_indirect_deriv.AddVec(1.0, temp_vec_dbl);
590  temp_vec_dbl.AddMatVec(1.0, deriv_acc.variance_accumulator(), kTrans,
591  gauss_posteriors_dbl, 0.0);
592  temp_vec.CopyFromVec(temp_vec_dbl); // convert to float.
593  // next line because d(x^2 stats for Gaussian)/d(feature) =
594  // 2 * (gaussian posterior) * feature.
595  this_indirect_deriv.AddVecVec(2.0, this_feat, temp_vec, 1.0);
596  }
597  }
598  }
599  return ans;
600 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ ComputeAndSubtractMean()

void kaldi::ComputeAndSubtractMean ( std::map< std::string, Vector< BaseFloat > *>  utt2ivector,
Vector< BaseFloat > *  mean_out 
)

Definition at line 186 of file ivector-compute-lda.cc.

References VectorBase< Real >::AddVec(), VectorBase< Real >::CopyFromVec(), and Vector< Real >::Resize().

Referenced by main().

188  {
189  int32 dim = utt2ivector.begin()->second->Dim();
190  size_t num_ivectors = utt2ivector.size();
191  Vector<double> mean(dim);
192  std::map<std::string, Vector<BaseFloat> *>::iterator iter;
193  for (iter = utt2ivector.begin(); iter != utt2ivector.end(); ++iter)
194  mean.AddVec(1.0 / num_ivectors, *(iter->second));
195  mean_out->Resize(dim);
196  mean_out->CopyFromVec(mean);
197  for (iter = utt2ivector.begin(); iter != utt2ivector.end(); ++iter)
198  iter->second->AddVec(-1.0, *mean_out);
199 }
kaldi::int32 int32
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).

◆ ComputeCompactLatticeAlphas() [1/2]

bool kaldi::ComputeCompactLatticeAlphas ( const CompactLattice lat,
std::vector< double > *  alpha 
)

Definition at line 150 of file lattice-functions.cc.

References KALDI_WARN, kLogZeroDouble, and LogAdd().

Referenced by CreateFactorTransducer(), and ArcPosteriorComputer::OutputPosteriors().

151  {
152  using namespace fst;
153 
154  // typedef the arc, weight types
155  typedef CompactLattice::Arc Arc;
156  typedef Arc::Weight Weight;
157  typedef Arc::StateId StateId;
158 
159  //Make sure the lattice is topologically sorted.
160  if (clat.Properties(fst::kTopSorted, true) == 0) {
161  KALDI_WARN << "Input lattice must be topologically sorted.";
162  return false;
163  }
164  if (clat.Start() != 0) {
165  KALDI_WARN << "Input lattice must start from state 0.";
166  return false;
167  }
168 
169  int32 num_states = clat.NumStates();
170  (*alpha).resize(0);
171  (*alpha).resize(num_states, kLogZeroDouble);
172 
173  // Now propagate alphas forward. Note that we don't acount the weight of the
174  // final state to alpha[final_state] -- we acount it to beta[final_state];
175  (*alpha)[0] = 0.0;
176  for (StateId s = 0; s < num_states; s++) {
177  double this_alpha = (*alpha)[s];
178  for (ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done(); aiter.Next()) {
179  const Arc &arc = aiter.Value();
180  double arc_like = -(arc.weight.Weight().Value1() + arc.weight.Weight().Value2());
181  (*alpha)[arc.nextstate] = LogAdd((*alpha)[arc.nextstate], this_alpha + arc_like);
182  }
183  }
184 
185  return true;
186 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
double LogAdd(double x, double y)
Definition: kaldi-math.h:184
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ ComputeCompactLatticeAlphas() [2/2]

bool kaldi::ComputeCompactLatticeAlphas ( const CompactLattice clat,
vector< double > *  alpha 
)

Definition at line 150 of file lattice-functions.cc.

References KALDI_WARN, kLogZeroDouble, and LogAdd().

Referenced by CreateFactorTransducer(), and ArcPosteriorComputer::OutputPosteriors().

151  {
152  using namespace fst;
153 
154  // typedef the arc, weight types
155  typedef CompactLattice::Arc Arc;
156  typedef Arc::Weight Weight;
157  typedef Arc::StateId StateId;
158 
159  //Make sure the lattice is topologically sorted.
160  if (clat.Properties(fst::kTopSorted, true) == 0) {
161  KALDI_WARN << "Input lattice must be topologically sorted.";
162  return false;
163  }
164  if (clat.Start() != 0) {
165  KALDI_WARN << "Input lattice must start from state 0.";
166  return false;
167  }
168 
169  int32 num_states = clat.NumStates();
170  (*alpha).resize(0);
171  (*alpha).resize(num_states, kLogZeroDouble);
172 
173  // Now propagate alphas forward. Note that we don't acount the weight of the
174  // final state to alpha[final_state] -- we acount it to beta[final_state];
175  (*alpha)[0] = 0.0;
176  for (StateId s = 0; s < num_states; s++) {
177  double this_alpha = (*alpha)[s];
178  for (ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done(); aiter.Next()) {
179  const Arc &arc = aiter.Value();
180  double arc_like = -(arc.weight.Weight().Value1() + arc.weight.Weight().Value2());
181  (*alpha)[arc.nextstate] = LogAdd((*alpha)[arc.nextstate], this_alpha + arc_like);
182  }
183  }
184 
185  return true;
186 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
double LogAdd(double x, double y)
Definition: kaldi-math.h:184
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ ComputeCompactLatticeBetas() [1/2]

bool kaldi::ComputeCompactLatticeBetas ( const CompactLattice lat,
std::vector< double > *  beta 
)

Definition at line 188 of file lattice-functions.cc.

References KALDI_WARN, kLogZeroDouble, and LogAdd().

Referenced by CompactLatticeNormalize(), CreateFactorTransducer(), and ArcPosteriorComputer::OutputPosteriors().

189  {
190  using namespace fst;
191 
192  // typedef the arc, weight types
193  typedef CompactLattice::Arc Arc;
194  typedef Arc::Weight Weight;
195  typedef Arc::StateId StateId;
196 
197  // Make sure the lattice is topologically sorted.
198  if (clat.Properties(fst::kTopSorted, true) == 0) {
199  KALDI_WARN << "Input lattice must be topologically sorted.";
200  return false;
201  }
202  if (clat.Start() != 0) {
203  KALDI_WARN << "Input lattice must start from state 0.";
204  return false;
205  }
206 
207  int32 num_states = clat.NumStates();
208  (*beta).resize(0);
209  (*beta).resize(num_states, kLogZeroDouble);
210 
211  // Now propagate betas backward. Note that beta[final_state] contains the
212  // weight of the final state in the lattice -- compare that with alpha.
213  for (StateId s = num_states-1; s >= 0; s--) {
214  Weight f = clat.Final(s);
215  double this_beta = -(f.Weight().Value1()+f.Weight().Value2());
216  for (ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done(); aiter.Next()) {
217  const Arc &arc = aiter.Value();
218  double arc_like = -(arc.weight.Weight().Value1()+arc.weight.Weight().Value2());
219  double arc_beta = (*beta)[arc.nextstate] + arc_like;
220  this_beta = LogAdd(this_beta, arc_beta);
221  }
222  (*beta)[s] = this_beta;
223  }
224 
225  return true;
226 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
double LogAdd(double x, double y)
Definition: kaldi-math.h:184
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ ComputeCompactLatticeBetas() [2/2]

bool kaldi::ComputeCompactLatticeBetas ( const CompactLattice clat,
vector< double > *  beta 
)

Definition at line 188 of file lattice-functions.cc.

References KALDI_WARN, kLogZeroDouble, and LogAdd().

Referenced by CompactLatticeNormalize(), CreateFactorTransducer(), and ArcPosteriorComputer::OutputPosteriors().

189  {
190  using namespace fst;
191 
192  // typedef the arc, weight types
193  typedef CompactLattice::Arc Arc;
194  typedef Arc::Weight Weight;
195  typedef Arc::StateId StateId;
196 
197  // Make sure the lattice is topologically sorted.
198  if (clat.Properties(fst::kTopSorted, true) == 0) {
199  KALDI_WARN << "Input lattice must be topologically sorted.";
200  return false;
201  }
202  if (clat.Start() != 0) {
203  KALDI_WARN << "Input lattice must start from state 0.";
204  return false;
205  }
206 
207  int32 num_states = clat.NumStates();
208  (*beta).resize(0);
209  (*beta).resize(num_states, kLogZeroDouble);
210 
211  // Now propagate betas backward. Note that beta[final_state] contains the
212  // weight of the final state in the lattice -- compare that with alpha.
213  for (StateId s = num_states-1; s >= 0; s--) {
214  Weight f = clat.Final(s);
215  double this_beta = -(f.Weight().Value1()+f.Weight().Value2());
216  for (ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done(); aiter.Next()) {
217  const Arc &arc = aiter.Value();
218  double arc_like = -(arc.weight.Weight().Value1()+arc.weight.Weight().Value2());
219  double arc_beta = (*beta)[arc.nextstate] + arc_like;
220  this_beta = LogAdd(this_beta, arc_beta);
221  }
222  (*beta)[s] = this_beta;
223  }
224 
225  return true;
226 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
double LogAdd(double x, double y)
Definition: kaldi-math.h:184
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ ComputeCorrelation()

void kaldi::ComputeCorrelation ( const VectorBase< BaseFloat > &  wave,
int32  first_lag,
int32  last_lag,
int32  nccf_window_size,
VectorBase< BaseFloat > *  inner_prod,
VectorBase< BaseFloat > *  norm_prod 
)

This function computes some dot products that are required while computing the NCCF.

For each integer lag from start to end-1, this function outputs to (*inner_prod)(lag - start), the dot-product of a window starting at 0 with a window starting at lag. All windows are of length nccf_window_size. It outputs to (*norm_prod)(lag - start), e1 * e2, where e1 is the dot-product of the un-shifted window with itself, and d2 is the dot-product of the window shifted by "lag" with itself.

Definition at line 102 of file pitch-functions.cc.

References VectorBase< Real >::Add(), VectorBase< Real >::Sum(), and VecVec().

Referenced by OnlinePitchFeatureImpl::AcceptWaveform().

106  {
107  Vector<BaseFloat> zero_mean_wave(wave);
108  // TODO: possibly fix this, the mean normalization is done in a strange way.
109  SubVector<BaseFloat> wave_part(wave, 0, nccf_window_size);
110  // subtract mean-frame from wave
111  zero_mean_wave.Add(-wave_part.Sum() / nccf_window_size);
112  BaseFloat e1, e2, sum;
113  SubVector<BaseFloat> sub_vec1(zero_mean_wave, 0, nccf_window_size);
114  e1 = VecVec(sub_vec1, sub_vec1);
115  for (int32 lag = first_lag; lag <= last_lag; lag++) {
116  SubVector<BaseFloat> sub_vec2(zero_mean_wave, lag, nccf_window_size);
117  e2 = VecVec(sub_vec2, sub_vec2);
118  sum = VecVec(sub_vec1, sub_vec2);
119  (*inner_prod)(lag - first_lag) = sum;
120  (*norm_prod)(lag - first_lag) = e1 * e2;
121  }
122 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ ComputeDctMatrix() [1/2]

template void kaldi::ComputeDctMatrix ( Matrix< float > *  M)

◆ ComputeDctMatrix() [2/2]

template void kaldi::ComputeDctMatrix ( Matrix< double > *  M)

◆ ComputeEarlyReverbEnergy()

BaseFloat kaldi::ComputeEarlyReverbEnergy ( const Vector< BaseFloat > &  rir,
const Vector< BaseFloat > &  signal,
BaseFloat  samp_freq 
)

Definition at line 64 of file wav-reverberate.cc.

References VectorBase< Real >::Dim(), FFTbasedBlockConvolveSignals(), KALDI_VLOG, VectorBase< Real >::Max(), VectorBase< Real >::Range(), and VecVec().

Referenced by DoReverberation().

65  {
66  int32 peak_index = 0;
67  rir.Max(&peak_index);
68  KALDI_VLOG(1) << "peak index is " << peak_index;
69 
70  const float sec_before_peak = 0.001;
71  const float sec_after_peak = 0.05;
72  int32 early_rir_start_index = peak_index - sec_before_peak * samp_freq;
73  int32 early_rir_end_index = peak_index + sec_after_peak * samp_freq;
74  if (early_rir_start_index < 0) early_rir_start_index = 0;
75  if (early_rir_end_index > rir.Dim()) early_rir_end_index = rir.Dim();
76 
77  int32 duration = early_rir_end_index - early_rir_start_index;
78  Vector<BaseFloat> early_rir(rir.Range(early_rir_start_index, duration));
79  Vector<BaseFloat> early_reverb(signal);
80  FFTbasedBlockConvolveSignals(early_rir, &early_reverb);
81 
82  // compute the energy
83  return VecVec(early_reverb, early_reverb) / early_reverb.Dim();
84 }
kaldi::int32 int32
void FFTbasedBlockConvolveSignals(const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
Definition: signal.cc:77
Real Max() const
Returns the maximum value of any element, or -infinity for the empty vector.
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37
SubVector< Real > Range(const MatrixIndexT o, const MatrixIndexT l)
Returns a sub-vector of a vector (a range of elements).
Definition: kaldi-vector.h:94

◆ ComputeEer()

BaseFloat kaldi::ComputeEer ( std::vector< BaseFloat > *  target_scores,
std::vector< BaseFloat > *  nontarget_scores,
BaseFloat threshold 
)

ComputeEer computes the Equal Error Rate (EER) for the given scores and returns it as a proportion beween 0 and 1.

If we set the threshold at x, then the target error-rate is the proportion of target_scores below x; and the non-target error-rate is the proportion of non-target scores above x. We seek a threshold x for which these error rates are the same; this error rate is the EER.

We compute this by iterating over the positions in target_scores: 0, 1, 2, and so on, and for each position consider whether the cutoff could be here. For each of these position we compute the corresponding position in nontarget_scores where the cutoff would be if the EER were the same. For instance, if the vectors had the same length, this would be position length() - 1, length() - 2, and so on. As soon as the value at that position in nontarget_scores at that position is less than the value from target_scores, we have our EER.

In coding this we weren't particularly careful about edge cases or making sure whether it's actually n + 1 instead of n.

Definition at line 48 of file compute-eer.cc.

References KALDI_ASSERT.

Referenced by main().

50  {
51  KALDI_ASSERT(!target_scores->empty() && !nontarget_scores->empty());
52  std::sort(target_scores->begin(), target_scores->end());
53  std::sort(nontarget_scores->begin(), nontarget_scores->end());
54 
55  size_t target_position = 0,
56  target_size = target_scores->size();
57  for (; target_position + 1 < target_size; target_position++) {
58  ssize_t nontarget_size = nontarget_scores->size(),
59  nontarget_n = nontarget_size * target_position * 1.0 / target_size,
60  nontarget_position = nontarget_size - 1 - nontarget_n;
61  if (nontarget_position < 0)
62  nontarget_position = 0;
63  if ((*nontarget_scores)[nontarget_position] <
64  (*target_scores)[target_position])
65  break;
66  }
67  *threshold = (*target_scores)[target_position];
68  BaseFloat eer = target_position * 1.0 / target_size;
69  return eer;
70 }
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ComputeFeatureNormalizingTransform()

void ComputeFeatureNormalizingTransform ( const FullGmm gmm,
Matrix< BaseFloat > *  xform 
)

Computes the inverse of an LDA transform (without dimensionality reduction) The computed transform is used in initializing the phonetic and speaker subspaces, as well as while increasing the dimensions of those spaces.

Definition at line 1297 of file am-sgmm2.cc.

References SpMatrix< Real >::AddMat2Sp(), MatrixBase< Real >::AddMatMat(), SpMatrix< Real >::AddSp(), VectorBase< Real >::AddVec(), SpMatrix< Real >::AddVec2(), TpMatrix< Real >::Cholesky(), MatrixBase< Real >::CopyFromTp(), VectorBase< Real >::CopyFromVec(), FullGmm::Dim(), SpMatrix< Real >::Eig(), FullGmm::GetCovarsAndMeans(), rnnlm::i, TpMatrix< Real >::InvertDouble(), MatrixBase< Real >::InvertDouble(), KALDI_ASSERT, KALDI_WARN, kNoTrans, kTrans, FullGmm::NumGauss(), Matrix< Real >::Resize(), MatrixBase< Real >::Row(), PackedMatrix< Real >::Scale(), VectorBase< Real >::Scale(), SortSvd(), and FullGmm::weights().

Referenced by AmSgmm2::GetVarScaledSubstateSpeakerMean(), AmSgmm2::InitializeFromFullGmm(), main(), and TestSgmm2IncreaseDim().

1297  {
1298  int32 dim = gmm.Dim();
1299  int32 num_gauss = gmm.NumGauss();
1300  SpMatrix<BaseFloat> within_class_covar(dim);
1301  SpMatrix<BaseFloat> between_class_covar(dim);
1302  Vector<BaseFloat> global_mean(dim);
1303 
1304  // Accumulate LDA statistics from the GMM parameters.
1305  {
1306  BaseFloat total_weight = 0.0;
1307  Vector<BaseFloat> tmp_weight(num_gauss);
1308  Matrix<BaseFloat> tmp_means;
1309  std::vector< SpMatrix<BaseFloat> > tmp_covars;
1310  tmp_weight.CopyFromVec(gmm.weights());
1311  gmm.GetCovarsAndMeans(&tmp_covars, &tmp_means);
1312  for (int32 i = 0; i < num_gauss; i++) {
1313  BaseFloat w_i = tmp_weight(i);
1314  total_weight += w_i;
1315  within_class_covar.AddSp(w_i, tmp_covars[i]);
1316  between_class_covar.AddVec2(w_i, tmp_means.Row(i));
1317  global_mean.AddVec(w_i, tmp_means.Row(i));
1318  }
1319  KALDI_ASSERT(total_weight > 0);
1320  if (fabs(total_weight - 1.0) > 0.001) {
1321  KALDI_WARN << "Total weight across the GMMs is " << (total_weight)
1322  << ", renormalizing.";
1323  global_mean.Scale(1.0 / total_weight);
1324  within_class_covar.Scale(1.0 / total_weight);
1325  between_class_covar.Scale(1.0 / total_weight);
1326  }
1327  between_class_covar.AddVec2(-1.0, global_mean);
1328  }
1329 
1330  TpMatrix<BaseFloat> chol(dim);
1331  chol.Cholesky(within_class_covar); // Sigma_W = L L^T
1332  TpMatrix<BaseFloat> chol_inv(chol);
1333  chol_inv.InvertDouble();
1334  Matrix<BaseFloat> chol_full(dim, dim);
1335  chol_full.CopyFromTp(chol_inv);
1336  SpMatrix<BaseFloat> LBL(dim);
1337  // LBL = L^{-1} \Sigma_B L^{-T}
1338  LBL.AddMat2Sp(1.0, chol_full, kNoTrans, between_class_covar, 0.0);
1339  Vector<BaseFloat> Dvec(dim);
1340  Matrix<BaseFloat> U(dim, dim);
1341  LBL.Eig(&Dvec, &U);
1342  SortSvd(&Dvec, &U);
1343 
1344  xform->Resize(dim, dim);
1345  chol_full.CopyFromTp(chol);
1346  // T := L U, eq (23)
1347  xform->AddMatMat(1.0, chol_full, kNoTrans, U, kNoTrans, 0.0);
1348 
1349 #ifdef KALDI_PARANOID
1350  Matrix<BaseFloat> inv_xform(*xform);
1351  inv_xform.InvertDouble();
1352  { // Check that T*within_class_covar*T' = I.
1353  Matrix<BaseFloat> wc_covar_full(dim, dim), tmp(dim, dim);
1354  wc_covar_full.CopyFromSp(within_class_covar);
1355  tmp.AddMatMat(1.0, inv_xform, kNoTrans, wc_covar_full, kNoTrans, 0.0);
1356  wc_covar_full.AddMatMat(1.0, tmp, kNoTrans, inv_xform, kTrans, 0.0);
1357  KALDI_ASSERT(wc_covar_full.IsUnit(0.01));
1358  }
1359  { // Check that T*between_class_covar*T' = diagonal.
1360  Matrix<BaseFloat> bc_covar_full(dim, dim), tmp(dim, dim);
1361  bc_covar_full.CopyFromSp(between_class_covar);
1362  tmp.AddMatMat(1.0, inv_xform, kNoTrans, bc_covar_full, kNoTrans, 0.0);
1363  bc_covar_full.AddMatMat(1.0, tmp, kNoTrans, inv_xform, kTrans, 0.0);
1364  KALDI_ASSERT(bc_covar_full.IsDiagonal(0.01));
1365  }
1366 #endif
1367 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
void AddMatMat(const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
void SortSvd(VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt, bool sort_on_absolute_value)
Function to ensure that SVD is sorted.

◆ ComputeFmllrDiagGmm()

BaseFloat kaldi::ComputeFmllrDiagGmm ( const FmllrDiagGmmAccs accs,
const FmllrOptions opts,
Matrix< BaseFloat > *  out_fmllr,
BaseFloat logdet 
)

Referenced by InitFmllr().

◆ ComputeFmllrLogDet()

BaseFloat kaldi::ComputeFmllrLogDet ( const Matrix< BaseFloat > &  fmllr_mat)
inline

Definition at line 176 of file fmllr-diag-gmm.h.

References ApplyFeatureTransformToStats(), ApplyModelTransformToStats(), ComputeFmllrMatrixDiagGmm(), ComputeFmllrMatrixDiagGmmDiagonal(), ComputeFmllrMatrixDiagGmmDiagonal2(), ComputeFmllrMatrixDiagGmmFull(), ComputeFmllrMatrixDiagGmmOffset(), FmllrAuxfGradient(), FmllrAuxFuncDiagGmm(), FmllrInnerUpdate(), KALDI_ASSERT, MatrixBase< Real >::LogDet(), FmllrOptions::num_iters, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

176  {
177  KALDI_ASSERT(fmllr_mat.NumRows() != 0 && fmllr_mat.NumCols() == fmllr_mat.NumRows()+1);
178  SubMatrix<BaseFloat> tmp(fmllr_mat,
179  0, fmllr_mat.NumRows(),
180  0, fmllr_mat.NumRows());
181  return tmp.LogDet();
182 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ComputeFmllrMatrixDiagGmm()

BaseFloat ComputeFmllrMatrixDiagGmm ( const MatrixBase< BaseFloat > &  in_xform,
const AffineXformStats stats,
std::string  fmllr_type,
int32  num_iters,
MatrixBase< BaseFloat > *  out_xform 
)

This function internally calls ComputeFmllrMatrixDiagGmm{Full, Diagonal, Offset}, depending on "fmllr_type".

Definition at line 169 of file fmllr-diag-gmm.cc.

References ComputeFmllrMatrixDiagGmmDiagonal(), ComputeFmllrMatrixDiagGmmFull(), ComputeFmllrMatrixDiagGmmOffset(), MatrixBase< Real >::IsUnit(), KALDI_ERR, KALDI_WARN, and MatrixBase< Real >::SetUnit().

Referenced by ComputeFmllrLogDet(), and LinearVtln::ComputeTransform().

173  {
174  if (fmllr_type == "full") {
175  return ComputeFmllrMatrixDiagGmmFull(in_xform, stats, num_iters, out_xform);
176  } else if (fmllr_type == "diag") {
177  return ComputeFmllrMatrixDiagGmmDiagonal(in_xform, stats, out_xform);
178  } else if (fmllr_type == "offset") {
179  return ComputeFmllrMatrixDiagGmmOffset(in_xform, stats, out_xform);
180  } else if (fmllr_type == "none") {
181  if (!in_xform.IsUnit())
182  KALDI_WARN << "You set fMLLR type to \"none\" but your starting transform "
183  "is not unit [this is strange, and diagnostics will be wrong].";
184  out_xform->SetUnit();
185  return 0.0;
186  } else
187  KALDI_ERR << "Unknown fMLLR update type " << fmllr_type
188  << ", must be one of \"full\"|\"diag\"|\"offset\"|\"none\"";
189  return 0.0;
190 }
BaseFloat ComputeFmllrMatrixDiagGmmFull(const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, int32 num_iters, MatrixBase< BaseFloat > *out_xform)
Updates the FMLLR matrix using Mark Gales&#39; row-by-row update.
BaseFloat ComputeFmllrMatrixDiagGmmOffset(const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, MatrixBase< BaseFloat > *out_xform)
This does offset-only fMLLR, i.e. it only estimates an offset.
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
BaseFloat ComputeFmllrMatrixDiagGmmDiagonal(const MatrixBase< BaseFloat > &in_xform, const AffineXformStats &stats, MatrixBase< BaseFloat > *out_xform)
This does diagonal fMLLR (i.e.

◆ ComputeFmllrMatrixDiagGmmDiagonal()

BaseFloat ComputeFmllrMatrixDiagGmmDiagonal ( const MatrixBase< BaseFloat > &  in_xform,
const AffineXformStats stats,
MatrixBase< BaseFloat > *  out_xform 
)

This does diagonal fMLLR (i.e.

only estimate an offset and scale per dimension). The format of the output is the same as for the full case. Of course, these statistics are unnecessarily large for this case. Returns the objective function improvement, not normalized by number of frames.

Definition at line 275 of file fmllr-diag-gmm.cc.

References AffineXformStats::beta_, MatrixBase< Real >::CopyFromMat(), FmllrAuxFuncDiagGmm(), AffineXformStats::G_, rnnlm::i, AffineXformStats::K_, KALDI_ASSERT, KALDI_VLOG, KALDI_WARN, and MatrixBase< Real >::Range().

Referenced by ComputeFmllrLogDet(), ComputeFmllrMatrixDiagGmm(), FmllrDiagGmmAccs::Update(), and RegtreeFmllrDiagGmmAccs::Update().

277  {
278  // The "Diagonal" here means a diagonal fMLLR matrix, i.e. like W = [ A; b] where
279  // A is diagonal.
280  // We re-derived the math (see exponential transform paper) to get a simpler
281  // update rule.
282 
283  /*
284  Write out_xform as D, which is a d x d+1 matrix (where d is the feature dimension).
285  We are solving for s == d_{i,i}, and o == d_{i,d} [assuming zero-based indexing];
286  s is a scale, o is an offset.
287  The stats are K (dimension d x d+1) and G_i for i=0..d-1 (dimension: d+1 x d+1),
288  and the count beta.
289 
290  The auxf for the i'th row of the transform is (assuming zero-based indexing):
291 
292  s k_{i,i} + o k_{i,d}
293  - \frac{1}{2} s^2 g_{i,i,i} - \frac{1}{2} o^2 g_{i,d,d} - s o g_{i,d,i}
294  + \beta \log |s|
295 
296  Suppose we know s, we can solve for o:
297  o = (k_{i,d} - s g_{i,d,i}) / g_{i,d,d}
298  Substituting this expression for o into the auxf (and ignoring
299  terms that don't vary with s), we have the auxf:
300 
301  \frac{1}{2} s^2 ( g_{i,d,i}^2 / g_{i,d,d} - g_{i,i,i} )
302  + s ( k_{i,i} - g_{i,d,i} k_{i,d} / g_{i,d,d} )
303  + \beta \log |s|
304 
305  Differentiating w.r.t. s and assuming s is positive, we have
306  a s + b + c/s = 0
307  where
308  a = ( g_{i,d,i}^2 / g_{i,d,d} - g_{i,i,i} ),
309  b = ( k_{i,i} - g_{i,d,i} k_{i,d} / g_{i,d,d} )
310  c = beta
311  Multiplying by s, we have the equation
312  a s^2 + b s + c = 0, where we assume s > 0.
313  We solve it with:
314  s = (-b - \sqrt{b^2 - 4ac}) / 2a
315  [take the negative root because we know a is negative, and this gives
316  the more positive solution for s; the other one would be negative].
317  We then solve for o with the equation above, i.e.:
318  o = (k_{i,d} - s g_{i,d,i}) / g_{i,d,d})
319  */
320 
321  int32 dim = stats.G_.size();
322  double beta = stats.beta_;
323  out_xform->CopyFromMat(in_xform);
324  if (beta == 0.0) {
325  KALDI_WARN << "Computing diagonal fMLLR matrix: no stats [using original transform]";
326  return 0.0;
327  }
328  BaseFloat old_obj = FmllrAuxFuncDiagGmm(*out_xform, stats);
329  KALDI_ASSERT(out_xform->Range(0, dim, 0, dim).IsDiagonal()); // orig transform
330  // must be diagonal.
331  for(int32 i = 0; i < dim; i++) {
332  double k_ii = stats.K_(i, i), k_id = stats.K_(i, dim),
333  g_iii = stats.G_[i](i, i), g_idd = stats.G_[i](dim, dim),
334  g_idi = stats.G_[i](dim, i);
335  double a = g_idi*g_idi/g_idd - g_iii,
336  b = k_ii - g_idi*k_id/g_idd,
337  c = beta;
338  double s = (-b - std::sqrt(b*b - 4*a*c)) / (2*a);
339  KALDI_ASSERT(s > 0.0);
340  double o = (k_id - s*g_idi) / g_idd;
341  (*out_xform)(i, i) = s;
342  (*out_xform)(i, dim) = o;
343  }
344  BaseFloat new_obj = FmllrAuxFuncDiagGmm(*out_xform, stats);
345  KALDI_VLOG(2) << "fMLLR objective function improvement = "
346  << (new_obj - old_obj);
347  return new_obj - old_obj;
348 }
kaldi::int32 int32
double FmllrAuxFuncDiagGmm(const MatrixBase< double > &xform, const AffineXformStats &stats)
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ ComputeFmllrMatrixDiagGmmDiagonal2()

BaseFloat kaldi::ComputeFmllrMatrixDiagGmmDiagonal2 ( const MatrixBase< BaseFloat > &  in_xform,
const AffineXformStats stats,
MatrixBase< BaseFloat > *  out_xform 
)

Referenced by ComputeFmllrLogDet().

◆ ComputeFmllrMatrixDiagGmmFull()

BaseFloat ComputeFmllrMatrixDiagGmmFull ( const MatrixBase< BaseFloat > &  in_xform,
const AffineXformStats stats,
int32  num_iters,
MatrixBase< BaseFloat > *  out_xform 
)

Updates the FMLLR matrix using Mark Gales' row-by-row update.

Uses full fMLLR matrix (no structure). Returns the objective function improvement, not normalized by number of frames.

Definition at line 236 of file fmllr-diag-gmm.cc.

References ApproxEqual(), AffineXformStats::beta_, MatrixBase< Real >::CopyFromMat(), rnnlm::d, FmllrAuxFuncDiagGmm(), FmllrInnerUpdate(), AffineXformStats::G_, AffineXformStats::K_, KALDI_LOG, KALDI_WARN, and kNoTrans.

Referenced by ComputeFmllrLogDet(), ComputeFmllrMatrixDiagGmm(), FmllrDiagGmmAccs::Update(), and RegtreeFmllrDiagGmmAccs::Update().

239  {
240  int32 dim = static_cast<int32>(stats.G_.size());
241 
242  // Compute the inverse matrices of second-order statistics
243  vector< SpMatrix<double> > inv_g(dim);
244  for (int32 d = 0; d < dim; d++) {
245  inv_g[d].Resize(dim + 1);
246  inv_g[d].CopyFromSp(stats.G_[d]);
247  inv_g[d].Invert();
248  }
249 
250  Matrix<double> old_xform(in_xform), new_xform(in_xform);
251  BaseFloat old_objf = FmllrAuxFuncDiagGmm(old_xform, stats);
252 
253  for (int32 iter = 0; iter < num_iters; ++iter) {
254  for (int32 d = 0; d < dim; d++) {
255  SubVector<double> k_d(stats.K_, d);
256  FmllrInnerUpdate(inv_g[d], k_d, stats.beta_, d, &new_xform);
257  } // end of looping over rows
258  } // end of iterations
259 
260  BaseFloat new_objf = FmllrAuxFuncDiagGmm(new_xform, stats),
261  objf_improvement = new_objf - old_objf;
262  KALDI_LOG << "fMLLR objf improvement is "
263  << (objf_improvement / (stats.beta_ + 1.0e-10))
264  << " per frame over " << stats.beta_ << " frames.";
265  if (objf_improvement < 0.0 && !ApproxEqual(new_objf, old_objf)) {
266  KALDI_WARN << "No applying fMLLR transform change because objective "
267  << "function did not increase.";
268  return 0.0;
269  } else {
270  out_xform->CopyFromMat(new_xform, kNoTrans);
271  return objf_improvement;
272  }
273 }
kaldi::int32 int32
double FmllrAuxFuncDiagGmm(const MatrixBase< double > &xform, const AffineXformStats &stats)
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
void FmllrInnerUpdate(SpMatrix< double > &inv_G, VectorBase< double > &k, double beta, int32 row, MatrixBase< double > *transform)
This function does one row of the inner-loop fMLLR transform update.
#define KALDI_LOG
Definition: kaldi-error.h:153
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ ComputeFmllrMatrixDiagGmmOffset()

BaseFloat ComputeFmllrMatrixDiagGmmOffset ( const MatrixBase< BaseFloat > &  in_xform,
const AffineXformStats stats,
MatrixBase< BaseFloat > *  out_xform 
)

This does offset-only fMLLR, i.e. it only estimates an offset.

Definition at line 350 of file fmllr-diag-gmm.cc.

References MatrixBase< Real >::CopyFromMat(), AffineXformStats::G_, rnnlm::i, AffineXformStats::K_, KALDI_ASSERT, KALDI_WARN, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

Referenced by ComputeFmllrLogDet(), ComputeFmllrMatrixDiagGmm(), FmllrDiagGmmAccs::Update(), and RegtreeFmllrDiagGmmAccs::Update().

352  {
353  int32 dim = stats.G_.size();
354  KALDI_ASSERT(in_xform.NumRows() == dim && in_xform.NumCols() == dim+1);
355  SubMatrix<BaseFloat> square_part(in_xform, 0, dim, 0, dim);
356  KALDI_ASSERT(square_part.IsUnit());
357  BaseFloat objf_impr = 0.0;
358  out_xform->CopyFromMat(in_xform);
359  for (int32 i = 0; i < dim; i++) {
360  // auxf in this offset b_i is:
361  // -0.5 b_i^2 G_i(dim, dim) - b_i G_i(i, dim)*1.0 + b_i K(i, dim) (1)
362  // answer is:
363  // b_i = [K(i, dim) - G_i(i, dim)] / G_i(dim, dim)
364  // objf change is given by (1)
365  BaseFloat b_i = (*out_xform)(i, dim);
366  BaseFloat objf_before = -0.5 * b_i * b_i * stats.G_[i](dim, dim)
367  - b_i * stats.G_[i](i, dim) + b_i * stats.K_(i, dim);
368  b_i = (stats.K_(i, dim) - stats.G_[i](i, dim)) / stats.G_[i](dim, dim);
369  (*out_xform)(i, dim) = b_i;
370  BaseFloat objf_after = -0.5 * b_i * b_i * stats.G_[i](dim, dim)
371  - b_i * stats.G_[i](i, dim) + b_i * stats.K_(i, dim);
372  if (objf_after < objf_before)
373  KALDI_WARN << "Objf decrease in offset estimation:"
374  << objf_after << " < " << objf_before;
375  objf_impr += objf_after - objf_before;
376  }
377  return objf_impr;
378 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ComputeGconsts()

static void kaldi::ComputeGconsts ( const VectorBase< BaseFloat > &  weights,
const MatrixBase< BaseFloat > &  means,
const MatrixBase< BaseFloat > &  inv_vars,
VectorBase< BaseFloat > *  gconsts_out 
)
static

Definition at line 112 of file decodable-am-diag-gmm-regtree.cc.

References rnnlm::d, VectorBase< Real >::Dim(), KALDI_ASSERT, KALDI_ERR, KALDI_ISINF, KALDI_ISNAN, KALDI_WARN, Log(), M_LOG_2PI, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

Referenced by DecodableAmDiagGmmRegtreeMllr::GetXformedMeanInvVars().

115  {
116  int32 num_gauss = weights.Dim();
117  int32 dim = means.NumCols();
118  KALDI_ASSERT(means.NumRows() == num_gauss
119  && inv_vars.NumRows() == num_gauss && inv_vars.NumCols() == dim);
120  KALDI_ASSERT(gconsts_out->Dim() == num_gauss);
121 
122  BaseFloat offset = -0.5 * M_LOG_2PI * dim; // constant term in gconst.
123  int32 num_bad = 0;
124 
125  for (int32 gauss = 0; gauss < num_gauss; gauss++) {
126  KALDI_ASSERT(weights(gauss) >= 0); // Cannot have negative weights.
127  BaseFloat gc = Log(weights(gauss)) + offset; // May be -inf if weights == 0
128  for (int32 d = 0; d < dim; d++) {
129  gc += 0.5 * Log(inv_vars(gauss, d)) - 0.5 * means(gauss, d)
130  * means(gauss, d) * inv_vars(gauss, d); // diff from DiagGmm version.
131  }
132 
133  if (KALDI_ISNAN(gc)) { // negative infinity is OK but NaN is not acceptable
134  KALDI_ERR << "At component " << gauss
135  << ", not a number in gconst computation";
136  }
137  if (KALDI_ISINF(gc)) {
138  num_bad++;
139  // If positive infinity, make it negative infinity.
140  // Want to make sure the answer becomes -inf in the end, not NaN.
141  if (gc > 0) gc = -gc;
142  }
143  (*gconsts_out)(gauss) = gc;
144  }
145  if (num_bad > 0)
146  KALDI_WARN << num_bad << " unusable components found while computing "
147  << "gconsts.";
148 }
#define M_LOG_2PI
Definition: kaldi-math.h:60
#define KALDI_ISINF
Definition: kaldi-math.h:73
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ISNAN
Definition: kaldi-math.h:72
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ComputeInitialSplit()

BaseFloat kaldi::ComputeInitialSplit ( const std::vector< Clusterable *> &  summed_stats,
const Questions q_opts,
EventKeyType  key,
std::vector< EventValueType > *  yes_set 
)

Definition at line 297 of file build-tree-utils.cc.

References AddToClustersOptimized(), DeletePointers(), Questions::GetQuestionsOf(), rnnlm::i, QuestionsForKey::initial_questions, KALDI_ASSERT, KALDI_WARN, Clusterable::Objf(), SumClusterable(), and SumClusterableObjf().

Referenced by FindBestSplitForKey().

299  {
300  KALDI_ASSERT(yes_set != NULL);
301  yes_set->clear();
302  const QuestionsForKey &key_opts = q_opts.GetQuestionsOf(key);
303 
304  // "total" needed for optimization in AddToClustersOptimized,
305  // and also used to work otu total objf.
306  Clusterable *total = SumClusterable(summed_stats);
307  if (total == NULL) return 0.0; // because there were no stats or non-NULL stats.
308  BaseFloat unsplit_objf = total->Objf();
309 
310  const std::vector<std::vector<EventValueType> > &questions_of_this_key = key_opts.initial_questions;
311 
312  int32 best_idx = -1;
313  BaseFloat best_objf_change = 0;
314 
315  for (size_t i = 0; i < questions_of_this_key.size(); i++) {
316  const std::vector<EventValueType> &yes_set = questions_of_this_key[i];
317  std::vector<int32> assignments(summed_stats.size(), 0); // 0 is index of "no".
318  std::vector<Clusterable*> clusters(2); // no and yes clusters.
319  for (std::vector<EventValueType>::const_iterator iter = yes_set.begin(); iter != yes_set.end(); ++iter) {
320  KALDI_ASSERT(*iter>=0);
321  if (*iter < (EventValueType)assignments.size()) assignments[*iter] = 1;
322  }
323  kaldi::AddToClustersOptimized(summed_stats, assignments, *total, &clusters);
324  BaseFloat this_objf = SumClusterableObjf(clusters);
325 
326  if (this_objf < unsplit_objf- 0.001*std::abs(unsplit_objf)) { // got worse; should never happen.
327  // of course small differences can be caused by roundoff.
328  KALDI_WARN << "Objective function got worse when building tree: "<< this_objf << " < " << unsplit_objf;
329  KALDI_ASSERT(!(this_objf < unsplit_objf - 0.01*(200 + std::abs(unsplit_objf)))); // do assert on more stringent check.
330  }
331 
332  BaseFloat this_objf_change = this_objf - unsplit_objf;
333  if (this_objf_change > best_objf_change) {
334  best_objf_change = this_objf_change;
335  best_idx = i;
336  }
337  DeletePointers(&clusters);
338  }
339  delete total;
340  if (best_idx != -1)
341  *yes_set = questions_of_this_key[best_idx];
342  return best_objf_change;
343 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
void AddToClustersOptimized(const std::vector< Clusterable *> &stats, const std::vector< int32 > &assignments, const Clusterable &total, std::vector< Clusterable *> *clusters)
AddToClustersOptimized does the same as AddToClusters (it sums up the stats within each cluster...
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
Clusterable * SumClusterable(const std::vector< Clusterable *> &vec)
Sums stats (ptrs may be NULL). Returns NULL if no non-NULL stats present.

◆ ComputeKaldiPitchFirstPass()

void kaldi::ComputeKaldiPitchFirstPass ( const PitchExtractionOptions opts,
const VectorBase< BaseFloat > &  wave,
Matrix< BaseFloat > *  output 
)

This function is called from ComputeKaldiPitch when the user specifies opts.simulate_first_pass_online == true.

It gives the "first-pass" version of the features, which you would get on the first decoding pass in an online setting. These may differ slightly from the final features due to both the way the Viterbi traceback works (this is affected by opts.max_frames_latency), and the online way we compute the average signal energy.

Definition at line 1248 of file pitch-functions.cc.

References OnlinePitchFeature::AcceptWaveform(), VectorBase< Real >::Dim(), PitchExtractionOptions::frame_shift_ms, PitchExtractionOptions::frames_per_chunk, OnlinePitchFeature::GetFrame(), OnlinePitchFeature::InputFinished(), KALDI_ASSERT, KALDI_WARN, kCopyData, OnlinePitchFeature::NumFramesReady(), Matrix< Real >::Resize(), MatrixBase< Real >::RowRange(), and PitchExtractionOptions::samp_freq.

Referenced by ComputeKaldiPitch().

1251  {
1252 
1253  int32 cur_rows = 100;
1254  Matrix<BaseFloat> feats(cur_rows, 2);
1255 
1256  OnlinePitchFeature pitch_extractor(opts);
1257  KALDI_ASSERT(opts.frames_per_chunk > 0 &&
1258  "--simulate-first-pass-online option does not make sense "
1259  "unless you specify --frames-per-chunk");
1260 
1261  int32 cur_offset = 0, cur_frame = 0, samp_per_chunk =
1262  opts.frames_per_chunk * opts.samp_freq * opts.frame_shift_ms / 1000.0f;
1263 
1264  while (cur_offset < wave.Dim()) {
1265  int32 num_samp = std::min(samp_per_chunk, wave.Dim() - cur_offset);
1266  SubVector<BaseFloat> wave_chunk(wave, cur_offset, num_samp);
1267  pitch_extractor.AcceptWaveform(opts.samp_freq, wave_chunk);
1268  cur_offset += num_samp;
1269  if (cur_offset == wave.Dim())
1270  pitch_extractor.InputFinished();
1271  // Get each frame as soon as it is ready.
1272  for (; cur_frame < pitch_extractor.NumFramesReady(); cur_frame++) {
1273  if (cur_frame >= cur_rows) {
1274  cur_rows *= 2;
1275  feats.Resize(cur_rows, 2, kCopyData);
1276  }
1277  SubVector<BaseFloat> row(feats, cur_frame);
1278  pitch_extractor.GetFrame(cur_frame, &row);
1279  }
1280  }
1281  if (cur_frame == 0) {
1282  KALDI_WARN << "No features output since wave file too short";
1283  output->Resize(0, 0);
1284  } else {
1285  *output = feats.RowRange(0, cur_frame);
1286  }
1287 }
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
SubMatrix< Real > RowRange(const MatrixIndexT row_offset, const MatrixIndexT num_rows) const
Definition: kaldi-matrix.h:209
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ ComputeLatticeAlphasAndBetas() [1/4]

double kaldi::ComputeLatticeAlphasAndBetas ( const LatticeType &  lat,
bool  viterbi,
std::vector< double > *  alpha,
std::vector< double > *  beta 
)

Definition at line 452 of file lattice-functions.cc.

References ApproxEqual(), ComputeLatticeAlphasAndBetas(), fst::ConvertToCost(), KALDI_ASSERT, KALDI_WARN, kLogZeroDouble, and LogAddOrMax().

Referenced by CompactLatticeLimitDepth(), ComputeLatticeAlphasAndBetas(), and DiscriminativeSupervisionSplitter::ComputeLatticeScores().

455  {
456  typedef typename LatticeType::Arc Arc;
457  typedef typename Arc::Weight Weight;
458  typedef typename Arc::StateId StateId;
459 
460  StateId num_states = lat.NumStates();
461  KALDI_ASSERT(lat.Properties(fst::kTopSorted, true) == fst::kTopSorted);
462  KALDI_ASSERT(lat.Start() == 0);
463  alpha->clear();
464  beta->clear();
465  alpha->resize(num_states, kLogZeroDouble);
466  beta->resize(num_states, kLogZeroDouble);
467 
468  double tot_forward_prob = kLogZeroDouble;
469  (*alpha)[0] = 0.0;
470  // Propagate alphas forward.
471  for (StateId s = 0; s < num_states; s++) {
472  double this_alpha = (*alpha)[s];
473  for (fst::ArcIterator<LatticeType> aiter(lat, s); !aiter.Done();
474  aiter.Next()) {
475  const Arc &arc = aiter.Value();
476  double arc_like = -ConvertToCost(arc.weight);
477  (*alpha)[arc.nextstate] = LogAddOrMax(viterbi, (*alpha)[arc.nextstate],
478  this_alpha + arc_like);
479  }
480  Weight f = lat.Final(s);
481  if (f != Weight::Zero()) {
482  double final_like = this_alpha - ConvertToCost(f);
483  tot_forward_prob = LogAddOrMax(viterbi, tot_forward_prob, final_like);
484  }
485  }
486  for (StateId s = num_states-1; s >= 0; s--) { // it's guaranteed signed.
487  double this_beta = -ConvertToCost(lat.Final(s));
488  for (fst::ArcIterator<LatticeType> aiter(lat, s); !aiter.Done();
489  aiter.Next()) {
490  const Arc &arc = aiter.Value();
491  double arc_like = -ConvertToCost(arc.weight),
492  arc_beta = (*beta)[arc.nextstate] + arc_like;
493  this_beta = LogAddOrMax(viterbi, this_beta, arc_beta);
494  }
495  (*beta)[s] = this_beta;
496  }
497  double tot_backward_prob = (*beta)[lat.Start()];
498  if (!ApproxEqual(tot_forward_prob, tot_backward_prob, 1e-8)) {
499  KALDI_WARN << "Total forward probability over lattice = " << tot_forward_prob
500  << ", while total backward probability = " << tot_backward_prob;
501  }
502  // Split the difference when returning... they should be the same.
503  return 0.5 * (tot_backward_prob + tot_forward_prob);
504 }
fst::StdArc::StateId StateId
double ConvertToCost(const LatticeWeightTpl< Float > &w)
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
const double kLogZeroDouble
Definition: kaldi-math.h:129
static double LogAddOrMax(bool viterbi, double a, double b)
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ ComputeLatticeAlphasAndBetas() [2/4]

double kaldi::ComputeLatticeAlphasAndBetas ( const LatticeType &  lat,
bool  viterbi,
vector< double > *  alpha,
vector< double > *  beta 
)

Definition at line 452 of file lattice-functions.cc.

References ApproxEqual(), ComputeLatticeAlphasAndBetas(), fst::ConvertToCost(), KALDI_ASSERT, KALDI_WARN, kLogZeroDouble, and LogAddOrMax().

Referenced by CompactLatticeLimitDepth(), ComputeLatticeAlphasAndBetas(), and DiscriminativeSupervisionSplitter::ComputeLatticeScores().

455  {
456  typedef typename LatticeType::Arc Arc;
457  typedef typename Arc::Weight Weight;
458  typedef typename Arc::StateId StateId;
459 
460  StateId num_states = lat.NumStates();
461  KALDI_ASSERT(lat.Properties(fst::kTopSorted, true) == fst::kTopSorted);
462  KALDI_ASSERT(lat.Start() == 0);
463  alpha->clear();
464  beta->clear();
465  alpha->resize(num_states, kLogZeroDouble);
466  beta->resize(num_states, kLogZeroDouble);
467 
468  double tot_forward_prob = kLogZeroDouble;
469  (*alpha)[0] = 0.0;
470  // Propagate alphas forward.
471  for (StateId s = 0; s < num_states; s++) {
472  double this_alpha = (*alpha)[s];
473  for (fst::ArcIterator<LatticeType> aiter(lat, s); !aiter.Done();
474  aiter.Next()) {
475  const Arc &arc = aiter.Value();
476  double arc_like = -ConvertToCost(arc.weight);
477  (*alpha)[arc.nextstate] = LogAddOrMax(viterbi, (*alpha)[arc.nextstate],
478  this_alpha + arc_like);
479  }
480  Weight f = lat.Final(s);
481  if (f != Weight::Zero()) {
482  double final_like = this_alpha - ConvertToCost(f);
483  tot_forward_prob = LogAddOrMax(viterbi, tot_forward_prob, final_like);
484  }
485  }
486  for (StateId s = num_states-1; s >= 0; s--) { // it's guaranteed signed.
487  double this_beta = -ConvertToCost(lat.Final(s));
488  for (fst::ArcIterator<LatticeType> aiter(lat, s); !aiter.Done();
489  aiter.Next()) {
490  const Arc &arc = aiter.Value();
491  double arc_like = -ConvertToCost(arc.weight),
492  arc_beta = (*beta)[arc.nextstate] + arc_like;
493  this_beta = LogAddOrMax(viterbi, this_beta, arc_beta);
494  }
495  (*beta)[s] = this_beta;
496  }
497  double tot_backward_prob = (*beta)[lat.Start()];
498  if (!ApproxEqual(tot_forward_prob, tot_backward_prob, 1e-8)) {
499  KALDI_WARN << "Total forward probability over lattice = " << tot_forward_prob
500  << ", while total backward probability = " << tot_backward_prob;
501  }
502  // Split the difference when returning... they should be the same.
503  return 0.5 * (tot_backward_prob + tot_forward_prob);
504 }
fst::StdArc::StateId StateId
double ConvertToCost(const LatticeWeightTpl< Float > &w)
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
const double kLogZeroDouble
Definition: kaldi-math.h:129
static double LogAddOrMax(bool viterbi, double a, double b)
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ ComputeLatticeAlphasAndBetas() [3/4]

template double kaldi::ComputeLatticeAlphasAndBetas ( const Lattice lat,
bool  viterbi,
vector< double > *  alpha,
vector< double > *  beta 
)

◆ ComputeLatticeAlphasAndBetas() [4/4]

template double kaldi::ComputeLatticeAlphasAndBetas ( const CompactLattice lat,
bool  viterbi,
vector< double > *  alpha,
vector< double > *  beta 
)

◆ ComputeLdaTransform()

void kaldi::ComputeLdaTransform ( const std::map< std::string, Vector< BaseFloat > *> &  utt2ivector,
const std::map< std::string, std::vector< std::string > > &  spk2utt,
BaseFloat  total_covariance_factor,
BaseFloat  covariance_floor,
MatrixBase< BaseFloat > *  lda_out 
)

Definition at line 107 of file ivector-compute-lda.cc.

References CovarianceStats::AccStats(), SpMatrix< Real >::AddMat2Sp(), MatrixBase< Real >::AddMatMat(), SpMatrix< Real >::AddSp(), ComputeNormalizingTransform(), MatrixBase< Real >::CopyFromMat(), SpMatrix< Real >::Eig(), CovarianceStats::Empty(), CovarianceStats::GetTotalCovar(), CovarianceStats::GetWithinCovar(), CovarianceStats::Info(), KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, rnnlm::n, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), MatrixBase< Real >::Row(), CovarianceStats::SingularTotCovar(), and SortSvd().

Referenced by main().

112  {
113  KALDI_ASSERT(!utt2ivector.empty());
114  int32 lda_dim = lda_out->NumRows(), dim = lda_out->NumCols();
115  KALDI_ASSERT(dim == utt2ivector.begin()->second->Dim());
116  KALDI_ASSERT(lda_dim > 0 && lda_dim <= dim);
117 
118  CovarianceStats stats(dim);
119 
120  std::map<std::string, std::vector<std::string> >::const_iterator iter;
121  for (iter = spk2utt.begin(); iter != spk2utt.end(); ++iter) {
122  const std::vector<std::string> &uttlist = iter->second;
123  KALDI_ASSERT(!uttlist.empty());
124 
125  int32 N = uttlist.size(); // number of utterances.
126  Matrix<double> utts_of_this_spk(N, dim);
127  for (int32 n = 0; n < N; n++) {
128  std::string utt = uttlist[n];
129  KALDI_ASSERT(utt2ivector.count(utt) != 0);
130  utts_of_this_spk.Row(n).CopyFromVec(
131  *(utt2ivector.find(utt)->second));
132  }
133  stats.AccStats(utts_of_this_spk);
134  }
135 
136  KALDI_LOG << "Stats have " << stats.Info();
137  KALDI_ASSERT(!stats.Empty());
138  KALDI_ASSERT(!stats.SingularTotCovar() &&
139  "Too little data for iVector dimension.");
140 
141 
142  SpMatrix<double> total_covar;
143  stats.GetTotalCovar(&total_covar);
144  SpMatrix<double> within_covar;
145  stats.GetWithinCovar(&within_covar);
146 
147 
148  SpMatrix<double> mat_to_normalize(dim);
149  mat_to_normalize.AddSp(total_covariance_factor, total_covar);
150  mat_to_normalize.AddSp(1.0 - total_covariance_factor, within_covar);
151 
152  Matrix<double> T(dim, dim);
153  ComputeNormalizingTransform(mat_to_normalize,
154  static_cast<double>(covariance_floor), &T);
155 
156  SpMatrix<double> between_covar(total_covar);
157  between_covar.AddSp(-1.0, within_covar);
158 
159  SpMatrix<double> between_covar_proj(dim);
160  between_covar_proj.AddMat2Sp(1.0, T, kNoTrans, between_covar, 0.0);
161 
162  Matrix<double> U(dim, dim);
163  Vector<double> s(dim);
164  between_covar_proj.Eig(&s, &U);
165  bool sort_on_absolute_value = false; // any negative ones will go last (they
166  // shouldn't exist anyway so doesn't
167  // really matter)
168  SortSvd(&s, &U, static_cast<Matrix<double>*>(NULL),
169  sort_on_absolute_value);
170 
171  KALDI_LOG << "Singular values of between-class covariance after projecting "
172  << "with interpolated [total/within] covariance with a weight of "
173  << total_covariance_factor << " on the total covariance, are: " << s;
174 
175  // U^T is the transform that will diagonalize the between-class covariance.
176  // U_part is just the part of U that corresponds to the kept dimensions.
177  SubMatrix<double> U_part(U, 0, dim, 0, lda_dim);
178 
179  // We first transform by T and then by U_part^T. This means T
180  // goes on the right.
181  Matrix<double> temp(lda_dim, dim);
182  temp.AddMatMat(1.0, U_part, kTrans, T, kNoTrans, 0.0);
183  lda_out->CopyFromMat(temp);
184 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
void ComputeNormalizingTransform(const SpMatrix< Real > &covar, Real floor, MatrixBase< Real > *proj)
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
#define KALDI_LOG
Definition: kaldi-error.h:153
Sub-matrix representation.
Definition: kaldi-matrix.h:988
void SortSvd(VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt, bool sort_on_absolute_value)
Function to ensure that SVD is sorted.

◆ ComputeLocalCost()

void kaldi::ComputeLocalCost ( const VectorBase< BaseFloat > &  nccf_pitch,
const VectorBase< BaseFloat > &  lags,
const PitchExtractionOptions opts,
VectorBase< BaseFloat > *  local_cost 
)

This function computes the local-cost for the Viterbi computation, see eq.

(5) in the paper.

Parameters
optsThe options as provided by the user
nccf_pitchThe nccf as computed for the pitch computation (with ballast).
lagsThe log-spaced lags at which nccf_pitch is sampled.
local_costWe output the local-cost to here.

Definition at line 178 of file pitch-functions.cc.

References VectorBase< Real >::AddVec(), VectorBase< Real >::AddVecVec(), VectorBase< Real >::Dim(), KALDI_ASSERT, VectorBase< Real >::Set(), and PitchExtractionOptions::soft_min_f0.

Referenced by PitchFrameInfo::ComputeBacktraces().

181  {
182  // from the paper, eq. 5, local_cost = 1 - Phi(t,i)(1 - soft_min_f0 L_i)
183  // nccf is the nccf on this frame measured at the lags in "lags".
184  KALDI_ASSERT(nccf_pitch.Dim() == local_cost->Dim() &&
185  nccf_pitch.Dim() == lags.Dim());
186  local_cost->Set(1.0);
187  // add the term -Phi(t,i):
188  local_cost->AddVec(-1.0, nccf_pitch);
189  // add the term soft_min_f0 Phi(t,i) L_i
190  local_cost->AddVecVec(opts.soft_min_f0, lags, nccf_pitch, 1.0);
191 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ComputeMllrMatrix()

static void kaldi::ComputeMllrMatrix ( const Matrix< double > &  K,
const vector< SpMatrix< double > > &  G,
Matrix< BaseFloat > *  out 
)
static

Definition at line 283 of file regtree-mllr-diag-gmm.cc.

References MatrixBase< Real >::CopyFromMat(), rnnlm::d, SpMatrix< Real >::Invert(), KALDI_WARN, kNoTrans, MatrixBase< Real >::Row(), and MatrixBase< Real >::SetUnit().

Referenced by RegtreeMllrDiagGmmAccs::Update().

285  {
286  int32 dim = G.size();
287  Matrix<double> tmp_out(dim, dim+1);
288  for (int32 d = 0; d < dim; d++) {
289  if (G[d].Cond() > 1.0e+9) {
290  KALDI_WARN << "Dim " << d << ": Badly conditioned stats. Setting MLLR "
291  << "transform to unit.";
292  tmp_out.SetUnit();
293  break;
294  }
295  SpMatrix<double> inv_g(G[d]);
296 // KALDI_LOG << "Dim " << d << ": G: max = " << inv_g.Max() << ", min = "
297 // << inv_g.Min() << ", log det = " << inv_g.LogDet(NULL)
298 // << ", cond = " << inv_g.Cond();
299  inv_g.Invert();
300 // KALDI_LOG << "Inv G: max = " << inv_g.Max() << ", min = " << inv_g.Min()
301 // << ", log det = " << inv_g.LogDet(NULL) << ", cond = "
302 // << inv_g.Cond();
303  tmp_out.Row(d).AddSpVec(1.0, inv_g, K.Row(d), 0.0);
304  }
305  out->CopyFromMat(tmp_out, kNoTrans);
306 }
kaldi::int32 int32
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ ComputeNccf()

void kaldi::ComputeNccf ( const VectorBase< BaseFloat > &  inner_prod,
const VectorBase< BaseFloat > &  norm_prod,
BaseFloat  nccf_ballast,
VectorBase< BaseFloat > *  nccf_vec 
)

Computes the NCCF as a fraction of the numerator term (a dot product between two vectors) and a denominator term which equals sqrt(e1*e2 + nccf_ballast) where e1 and e2 are both dot-products of bits of the wave with themselves, and e1*e2 is supplied as "norm_prod".

These quantities are computed by "ComputeCorrelation".

Definition at line 131 of file pitch-functions.cc.

References VectorBase< Real >::Dim(), and KALDI_ASSERT.

Referenced by OnlinePitchFeatureImpl::AcceptWaveform().

134  {
135  KALDI_ASSERT(inner_prod.Dim() == norm_prod.Dim() &&
136  inner_prod.Dim() == nccf_vec->Dim());
137  for (int32 lag = 0; lag < inner_prod.Dim(); lag++) {
138  BaseFloat numerator = inner_prod(lag),
139  denominator = pow(norm_prod(lag) + nccf_ballast, 0.5),
140  nccf;
141  if (denominator != 0.0) {
142  nccf = numerator / denominator;
143  } else {
144  KALDI_ASSERT(numerator == 0.0);
145  nccf = 0.0;
146  }
147  KALDI_ASSERT(nccf < 1.01 && nccf > -1.01);
148  (*nccf_vec)(lag) = nccf;
149  }
150 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ComputeNewPhoneLengths()

static bool kaldi::ComputeNewPhoneLengths ( const HmmTopology topology,
const std::vector< int32 > &  mapped_phones,
const std::vector< int32 > &  old_lengths,
int32  conversion_shift,
int32  subsample_factor,
std::vector< int32 > *  new_lengths 
)
static

This function, called from ConvertAlignmentInternal(), works out suitable new lengths of phones in the case where subsample_factor != 1.

The input vectors 'mapped_phones' and 'old_lengths' must be the same size– the length of the phone sequence. The 'topology' object and 'mapped_phones' are needed to work out the minimum length of each phone in the sequence. Returns false only if it could not assign lengths (because the topology was too long relative to the number of frames).

Parameters
topology[in] The new phone lengths are computed with regard to this topology
mapped_phones[in] The phones for which this function computes new lengths
old_lengths[in] The old lengths
conversion_shift[in] This will normally equal subsample_factor - 1 but may be less than that if the 'repeat_frames' option is true; it's used for generating 'frame-shifted' versions of alignments that we will later interpolate. This helps us keep the phone boundaries of the subsampled and interpolated alignments the same as the original alignment.
subsample_factor[in] The frame subsampling factor... normally 1, but might be > 1 if we're converting to a reduced-frame-rate system.
new_lengths[out] The vector for storing new lengths.

Definition at line 849 of file hmm-utils.cc.

References rnnlm::i, rnnlm::j, and HmmTopology::MinLength().

Referenced by ConvertAlignmentInternal().

854  {
855  int32 phone_sequence_length = old_lengths.size();
856  std::vector<int32> min_lengths(phone_sequence_length);
857  new_lengths->resize(phone_sequence_length);
858  for (int32 i = 0; i < phone_sequence_length; i++)
859  min_lengths[i] = topology.MinLength(mapped_phones[i]);
860  int32 cur_time_elapsed = 0;
861  for (int32 i = 0; i < phone_sequence_length; i++) {
862  // Note: the '+ subsample_factor - 1' here is needed so that
863  // the subsampled alignments have the same length as features
864  // subsampled with 'subsample-feats'.
865  int32 subsampled_time =
866  (cur_time_elapsed + conversion_shift) / subsample_factor;
867  cur_time_elapsed += old_lengths[i];
868  int32 next_subsampled_time =
869  (cur_time_elapsed + conversion_shift) / subsample_factor;
870  (*new_lengths)[i] = next_subsampled_time - subsampled_time;
871  }
872  bool changed = true;
873  while (changed) {
874  changed = false;
875  for (int32 i = 0; i < phone_sequence_length; i++) {
876  if ((*new_lengths)[i] < min_lengths[i]) {
877  changed = true;
878  // we need at least one extra frame.. just try to get one frame for now.
879  // Get it from the left or the right, depending which one has the closest
880  // availability of a 'spare' frame.
881  int32 min_distance = std::numeric_limits<int32>::max(),
882  best_other_phone_index = -1,
883  cur_distance = 0;
884  // first try to the left.
885  for (int32 j = i - 1; j >= 0; j--) {
886  if ((*new_lengths)[j] > min_lengths[j]) {
887  min_distance = cur_distance;
888  best_other_phone_index = j;
889  break;
890  } else {
891  cur_distance += (*new_lengths)[j];
892  }
893  }
894  // .. now to the right.
895  cur_distance = 0;
896  for (int32 j = i + 1; j < phone_sequence_length; j++) {
897  if ((*new_lengths)[j] > min_lengths[j]) {
898  if (cur_distance < min_distance) {
899  min_distance = cur_distance;
900  best_other_phone_index = j;
901  }
902  break;
903  } else {
904  cur_distance += (*new_lengths)[j];
905  }
906  }
907  if (best_other_phone_index == -1)
908  return false;
909  // assign an extra frame to this phone...
910  (*new_lengths)[i]++;
911  // and borrow it from the place that we found.
912  (*new_lengths)[best_other_phone_index]--;
913  }
914  }
915  }
916  return true;
917 }
kaldi::int32 int32

◆ ComputeNormalizingTransform() [1/2]

static void kaldi::ComputeNormalizingTransform ( const SpMatrix< Real > &  covar,
MatrixBase< Real > *  proj 
)
static

This function computes a projection matrix that when applied makes the covariance unit (i.e.

all 1).

Definition at line 46 of file plda.cc.

References TpMatrix< Real >::Cholesky(), MatrixBase< Real >::CopyFromTp(), TpMatrix< Real >::Invert(), kNoTrans, and PackedMatrix< Real >::NumRows().

Referenced by Plda::ApplyTransform(), ComputeLdaTransform(), and PldaEstimator::GetOutput().

47  {
48  int32 dim = covar.NumRows();
49  TpMatrix<Real> C(dim); // Cholesky of covar, covar = C C^T
50  C.Cholesky(covar);
51  C.Invert(); // The matrix that makes covar unit is C^{-1}, because
52  // C^{-1} covar C^{-T} = C^{-1} C C^T C^{-T} = I.
53  proj->CopyFromTp(C, kNoTrans); // set "proj" to C^{-1}.
54 }
kaldi::int32 int32

◆ ComputeNormalizingTransform() [2/2]

void kaldi::ComputeNormalizingTransform ( const SpMatrix< Real > &  covar,
Real  floor,
MatrixBase< Real > *  proj 
)

Definition at line 84 of file ivector-compute-lda.cc.

References MatrixBase< Real >::AddDiagVecMat(), VectorBase< Real >::ApplyFloor(), VectorBase< Real >::ApplyPow(), SpMatrix< Real >::Eig(), KALDI_WARN, kTrans, PackedMatrix< Real >::NumRows(), and SortSvd().

86  {
87  int32 dim = covar.NumRows();
88  Matrix<Real> U(dim, dim);
89  Vector<Real> s(dim);
90  covar.Eig(&s, &U);
91  // Sort eigvenvalues from largest to smallest.
92  SortSvd(&s, &U);
93  // Floor eigenvalues to a small positive value.
94  int32 num_floored;
95  floor *= s(0); // Floor relative to the largest eigenvalue
96  s.ApplyFloor(floor, &num_floored);
97  if (num_floored > 0) {
98  KALDI_WARN << "Floored " << num_floored << " eigenvalues of covariance "
99  << "to " << floor;
100  }
101  // Next two lines computes projection proj, such that
102  // proj * covar * proj^T = I.
103  s.ApplyPow(-0.5);
104  proj->AddDiagVecMat(1.0, s, U, kTrans, 0.0);
105 }
kaldi::int32 int32
void Eig(VectorBase< Real > *s, MatrixBase< Real > *P=NULL) const
Solves the symmetric eigenvalue problem: at end we should have (*this) = P * diag(s) * P^T...
Definition: qr.cc:433
A class for storing matrices.
Definition: kaldi-matrix.h:823
MatrixIndexT NumRows() const
#define KALDI_WARN
Definition: kaldi-error.h:150
A class representing a vector.
Definition: kaldi-vector.h:406
void AddDiagVecMat(const Real alpha, const VectorBase< Real > &v, const MatrixBase< Real > &M, MatrixTransposeType transM, Real beta=1.0)
*this = beta * *this + alpha * diag(v) * M [or M^T].
void SortSvd(VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt, bool sort_on_absolute_value)
Function to ensure that SVD is sorted.

◆ ComputePca() [1/2]

template void kaldi::ComputePca ( const MatrixBase< float > &  X,
MatrixBase< float > *  U,
MatrixBase< float > *  A,
bool  print_eigs,
bool  exact 
)

◆ ComputePca() [2/2]

template void kaldi::ComputePca ( const MatrixBase< double > &  X,
MatrixBase< double > *  U,
MatrixBase< double > *  A,
bool  print_eigs,
bool  exact 
)

◆ ComputeTreeMapping()

static void kaldi::ComputeTreeMapping ( const EventMap small_tree,
const EventMap big_tree,
const BuildTreeStatsType stats,
std::vector< int32 > *  leaf_map 
)
static

Definition at line 320 of file build-tree.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_ERR, KALDI_WARN, EventMap::Map(), EventMap::MaxResult(), and SplitStatsByMap().

Referenced by BuildTreeTwoLevel().

323  {
324  std::vector<BuildTreeStatsType> split_stats_small; // stats split by small tree
325  int32 num_leaves_big = big_tree.MaxResult() + 1,
326  num_leaves_small = small_tree.MaxResult() + 1;
327  SplitStatsByMap(stats, small_tree, &split_stats_small);
328  KALDI_ASSERT(static_cast<int32>(split_stats_small.size()) <=
329  num_leaves_small);
330  leaf_map->clear();
331  leaf_map->resize(num_leaves_big, -1); // fill with -1.
332 
333  std::vector<int32> small_leaves_unseen; // a list of small leaves that had no stats..
334  // this is used as a workaround for when there are no stats at leaves...
335  // it's really an error condition and it will cause errors later (e.g. when
336  // you initialize your model), but at this point we will try to handle it
337  // gracefully.
338 
339  for (int32 i = 0; i < num_leaves_small; i++) {
340  if (static_cast<size_t>(i) >= split_stats_small.size() ||
341  split_stats_small[i].empty()) {
342  KALDI_WARN << "No stats mapping to " << i << " in small tree. "
343  << "Continuing but this is a serious error.";
344  small_leaves_unseen.push_back(i);
345  } else {
346  for (size_t j = 0; j < split_stats_small[i].size(); j++) {
347  int32 leaf = 0; // = 0 to keep compiler happy. Leaf in big tree.
348  bool ok = big_tree.Map(split_stats_small[i][j].first, &leaf);
349  if (!ok)
350  KALDI_ERR << "Could not map stats with big tree: probable code error.";
351  if (leaf < 0 || leaf >= num_leaves_big)
352  KALDI_ERR << "Leaf out of range: " << leaf << " vs. " << num_leaves_big;
353  if ((*leaf_map)[leaf] != -1 && (*leaf_map)[leaf] != i)
354  KALDI_ERR << "Inconsistent mapping for big tree: "
355  << i << " vs. " << (*leaf_map)[leaf];
356  (*leaf_map)[leaf] = i;
357  }
358  }
359  }
360  // Now make sure that all leaves in the big tree have a leaf in the small tree
361  // assigned to them. If not we try to clean up... this should never normally
362  // happen and if it does it's due to trying to assign tree roots to unseen phones,
363  // which will anyway cause an error in a later stage of system building.
364  for (int32 leaf = 0; leaf < num_leaves_big; leaf++) {
365  int32 small_leaf = (*leaf_map)[leaf];
366  if (small_leaf == -1) {
367  KALDI_WARN << "In ComputeTreeMapping, could not get mapping from leaf "
368  << leaf;
369  if (!small_leaves_unseen.empty()) {
370  small_leaf = small_leaves_unseen.back();
371  KALDI_WARN << "Assigning it to unseen small-tree leaf " << small_leaf;
372  small_leaves_unseen.pop_back();
373  (*leaf_map)[leaf] = small_leaf;
374  } else {
375  KALDI_WARN << "Could not find any unseen small-tree leaf to assign "
376  << "it to. Making it zero, but this is bad. ";
377  (*leaf_map)[leaf] = 0;
378  }
379  } else if (small_leaf < 0 || small_leaf >= num_leaves_small)
380  KALDI_ERR << "Leaf in leaf mapping out of range: for big-map leaf "
381  << leaf << ", mapped to " << small_leaf << ", vs. "
382  << num_leaves_small;
383  }
384 }
void SplitStatsByMap(const BuildTreeStatsType &stats, const EventMap &e, std::vector< BuildTreeStatsType > *stats_out)
Splits stats according to the EventMap, indexing them at output by the leaf type. ...
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ComputeVadEnergy()

void ComputeVadEnergy ( const VadEnergyOptions opts,
const MatrixBase< BaseFloat > &  input_features,
Vector< BaseFloat > *  output_voiced 
)

Compute voice-activity vector for a file: 1 if we judge the frame as voiced, 0 otherwise.

There are no continuity constraints. This method is a very simple energy-based method which only looks at the first coefficient of "input_features", which is assumed to be a log-energy or something similar. A cutoff is set– we use a formula of the general type: cutoff = 5.0 + 0.5 * (average log-energy in this file), and for each frame the decision is based on the proportion of frames in a context window around the current frame, which are above this cutoff.

Definition at line 27 of file voice-activity-detection.cc.

References VectorBase< Real >::CopyColFromMat(), VectorBase< Real >::Data(), KALDI_ASSERT, KALDI_WARN, MatrixBase< Real >::NumRows(), Vector< Real >::Resize(), VectorBase< Real >::Sum(), VadEnergyOptions::vad_energy_mean_scale, VadEnergyOptions::vad_energy_threshold, VadEnergyOptions::vad_frames_context, and VadEnergyOptions::vad_proportion_threshold.

Referenced by main(), and VadEnergyOptions::Register().

29  {
30  int32 T = feats.NumRows();
31  output_voiced->Resize(T);
32  if (T == 0) {
33  KALDI_WARN << "Empty features";
34  return;
35  }
36  Vector<BaseFloat> log_energy(T);
37  log_energy.CopyColFromMat(feats, 0); // column zero is log-energy.
38 
39  BaseFloat energy_threshold = opts.vad_energy_threshold;
40  if (opts.vad_energy_mean_scale != 0.0) {
41  KALDI_ASSERT(opts.vad_energy_mean_scale > 0.0);
42  energy_threshold += opts.vad_energy_mean_scale * log_energy.Sum() / T;
43  }
44 
45  KALDI_ASSERT(opts.vad_frames_context >= 0);
46  KALDI_ASSERT(opts.vad_proportion_threshold > 0.0 &&
47  opts.vad_proportion_threshold < 1.0);
48  for (int32 t = 0; t < T; t++) {
49  const BaseFloat *log_energy_data = log_energy.Data();
50  int32 num_count = 0, den_count = 0, context = opts.vad_frames_context;
51  for (int32 t2 = t - context; t2 <= t + context; t2++) {
52  if (t2 >= 0 && t2 < T) {
53  den_count++;
54  if (log_energy_data[t2] > energy_threshold)
55  num_count++;
56  }
57  }
58  if (num_count >= den_count * opts.vad_proportion_threshold)
59  (*output_voiced)(t) = 1.0;
60  else
61  (*output_voiced)(t) = 0.0;
62  }
63 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ConcatFeats()

void kaldi::ConcatFeats ( const std::vector< Matrix< BaseFloat > > &  in,
Matrix< BaseFloat > *  out 
)

Definition at line 35 of file concat-feats.cc.

References rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::Range(), and Matrix< Real >::Resize().

Referenced by main().

36  {
37  KALDI_ASSERT(in.size() >= 1);
38  int32 tot_len = in[0].NumRows(),
39  dim = in[0].NumCols();
40  for (int32 i = 1; i < in.size(); i++) {
41  KALDI_ASSERT(in[i].NumCols() == dim);
42  tot_len += in[i].NumRows();
43  }
44  out->Resize(tot_len, dim);
45  int32 len_offset = 0;
46  for (int32 i = 0; i < in.size(); i++) {
47  int32 this_len = in[i].NumRows();
48  out->Range(len_offset, this_len, 0, dim).CopyFromMat(
49  in[i]);
50  len_offset += this_len;
51  }
52 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
SubMatrix< Real > Range(const MatrixIndexT row_offset, const MatrixIndexT num_rows, const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
Return a sub-part of matrix.
Definition: kaldi-matrix.h:202
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ ContainsNullPointers()

bool kaldi::ContainsNullPointers ( const std::vector< A *> &  v)

Returns true if the vector of pointers contains NULL pointers.

Definition at line 197 of file stl-utils.h.

Referenced by ClusterBottomUp(), ClusterBottomUpCompartmentalized(), ClusterKMeans(), RefineClusters(), TestContainsNullPointers(), and TreeCluster().

197  {
198  typename std::vector<A*>::const_iterator iter = v.begin(), end = v.end();
199  for (; iter != end; ++iter)
200  if (*iter == static_cast<A*> (NULL)) return true;
201  return false;
202 }

◆ ConvertAddShiftComponent()

nnet2::Component* kaldi::ConvertAddShiftComponent ( const nnet1::Component nnet1_component)

Definition at line 99 of file nnet1-to-raw-nnet.cc.

References AddShift::GetParams(), FixedBiasComponent::Init(), KALDI_ASSERT, and AddShift::NumParams().

Referenced by ConvertComponent().

100  {
101  const nnet1::AddShift *add_shift =
102  dynamic_cast<const nnet1::AddShift*>(&nnet1_component);
103  KALDI_ASSERT(add_shift != NULL);
104  Vector<BaseFloat> bias(add_shift->NumParams());
105 
106  add_shift->GetParams(&bias);
107  CuVector<BaseFloat> cu_bias(bias);
108 
110  res->Init(cu_bias);
111  return res;
112 }
void Init(const CuVectorBase< BaseFloat > &scales)
void GetParams(VectorBase< BaseFloat > *params) const
Get the trainable parameters reshaped as a vector,.
Definition: nnet-various.h:344
int32 NumParams() const
Number of trainable parameters,.
Definition: nnet-various.h:337
Adds shift to all the lines of the matrix (can be used for global mean normalization) ...
Definition: nnet-various.h:291
FixedBiasComponent applies a fixed per-element bias; it&#39;s similar to the AddShift component in the nn...
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ConvertAffineTransformComponent()

nnet2::Component* kaldi::ConvertAffineTransformComponent ( const nnet1::Component nnet1_component,
const bool  use_preconditioned_affine_component 
)

Definition at line 32 of file nnet1-to-raw-nnet.cc.

References AffineTransform::GetBias(), AffineTransform::GetLinearity(), and KALDI_ASSERT.

Referenced by ConvertComponent().

34  {
35  const nnet1::AffineTransform *affine =
36  dynamic_cast<const nnet1::AffineTransform*>(&nnet1_component);
37  KALDI_ASSERT(affine != NULL);
38  // default learning rate is 1.0e-05, you can use the --learning-rate or
39  // --learning-rates option to nnet-am-copy to change it if you need.
40  BaseFloat learning_rate = 1.0e-05;
41  if (use_preconditioned_affine_component) {
42  int32 rank_in = 20,
43  rank_out = 80,
44  update_period = 4;
45  BaseFloat num_samples_history = 2000.,
46  alpha = 4.;
49  affine->GetBias(),
50  learning_rate),
51  rank_in,
52  rank_out,
53  update_period,
54  num_samples_history,
55  alpha);
56  } else {
57  return new nnet2::AffineComponent(affine->GetLinearity(),
58  affine->GetBias(),
59  learning_rate);
60  }
61 }
const CuMatrixBase< BaseFloat > & GetLinearity() const
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
const CuVectorBase< BaseFloat > & GetBias() const
Accessors to the component parameters,.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Keywords: natural gradient descent, NG-SGD, naturalgradient.

◆ ConvertAlignmentForPhone()

static void kaldi::ConvertAlignmentForPhone ( const TransitionModel old_trans_model,
const TransitionModel new_trans_model,
const ContextDependencyInterface new_ctx_dep,
const std::vector< int32 > &  old_phone_alignment,
const std::vector< int32 > &  new_phone_window,
bool  old_is_reordered,
bool  new_is_reordered,
std::vector< int32 > *  new_phone_alignment 
)
inlinestatic

This function is used internally inside ConvertAlignment; it converts the alignment for a single phone.

'new_phone_window' is the window of phones as required by the tree. The size of 'new_phone_alignment' is the length requested, which may not always equal 'old_phone_alignment' (in case the 'subsample' value is not 1).

Definition at line 742 of file hmm-utils.cc.

References ContextDependencyInterface::CentralPosition(), ChangeReorderingOfAlignment(), ContextDependencyInterface::Compute(), GetRandomAlignmentForPhone(), TransitionModel::GetTopo(), rnnlm::j, KALDI_ASSERT, KALDI_ERR, KALDI_WARN, TransitionModel::PairToTransitionId(), HmmTopology::TopologyForPhone(), TransitionModel::TransitionIdToHmmState(), TransitionModel::TransitionIdToPhone(), TransitionModel::TransitionIdToTransitionIndex(), TransitionModel::TransitionIdToTransitionState(), TransitionModel::TransitionStateToForwardPdfClass(), TransitionModel::TransitionStateToSelfLoopPdfClass(), TransitionModel::TupleToTransitionState(), and WriteIntegerVector().

Referenced by ConvertAlignmentInternal().

750  {
751  int32 alignment_size = old_phone_alignment.size();
752  static bool warned_topology = false;
753  int32 P = new_ctx_dep.CentralPosition(),
754  old_central_phone = old_trans_model.TransitionIdToPhone(
755  old_phone_alignment[0]),
756  new_central_phone = new_phone_window[P];
757  const HmmTopology &old_topo = old_trans_model.GetTopo(),
758  &new_topo = new_trans_model.GetTopo();
759 
760  bool topology_mismatch = !(old_topo.TopologyForPhone(old_central_phone) ==
761  new_topo.TopologyForPhone(new_central_phone));
762  if (topology_mismatch) {
763  if (!warned_topology) {
764  warned_topology = true;
765  KALDI_WARN << "Topology mismatch detected; automatically converting. "
766  << "Won't warn again.";
767  }
768  }
769  bool length_mismatch =
770  (new_phone_alignment->size() != old_phone_alignment.size());
771  if (length_mismatch || topology_mismatch) {
772  // We generate a random path from this FST, ignoring the
773  // old alignment.
774  GetRandomAlignmentForPhone(new_ctx_dep, new_trans_model,
775  new_phone_window, new_phone_alignment);
776  if (new_is_reordered)
777  ChangeReorderingOfAlignment(new_trans_model, new_phone_alignment);
778  return;
779  }
780 
781  KALDI_ASSERT(!old_phone_alignment.empty());
782 
783  int32 new_num_pdf_classes = new_topo.NumPdfClasses(new_central_phone);
784  std::vector<int32> pdf_ids(new_num_pdf_classes); // Indexed by pdf-class
785  for (int32 pdf_class = 0; pdf_class < new_num_pdf_classes; pdf_class++) {
786  if (!new_ctx_dep.Compute(new_phone_window, pdf_class,
787  &(pdf_ids[pdf_class]))) {
788  std::ostringstream ss;
789  WriteIntegerVector(ss, false, new_phone_window);
790  KALDI_ERR << "tree did not succeed in converting phone window "
791  << ss.str();
792  }
793  }
794 
795  // the topologies and lengths match -> we can directly transfer
796  // the alignment.
797  for (int32 j = 0; j < alignment_size; j++) {
798  int32 old_tid = old_phone_alignment[j],
799  old_tstate = old_trans_model.TransitionIdToTransitionState(old_tid);
800  int32 forward_pdf_class =
801  old_trans_model.TransitionStateToForwardPdfClass(old_tstate),
802  self_loop_pdf_class =
803  old_trans_model.TransitionStateToSelfLoopPdfClass(old_tstate);
804  int32 hmm_state = old_trans_model.TransitionIdToHmmState(old_tid);
805  int32 trans_idx = old_trans_model.TransitionIdToTransitionIndex(old_tid);
806  int32 new_forward_pdf = pdf_ids[forward_pdf_class];
807  int32 new_self_loop_pdf = pdf_ids[self_loop_pdf_class];
808  int32 new_trans_state =
809  new_trans_model.TupleToTransitionState(new_central_phone, hmm_state,
810  new_forward_pdf, new_self_loop_pdf);
811  int32 new_tid =
812  new_trans_model.PairToTransitionId(new_trans_state, trans_idx);
813  (*new_phone_alignment)[j] = new_tid;
814  }
815 
816  if (new_is_reordered != old_is_reordered)
817  ChangeReorderingOfAlignment(new_trans_model, new_phone_alignment);
818 }
void GetRandomAlignmentForPhone(const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, const std::vector< int32 > &phone_window, std::vector< int32 > *alignment)
Definition: hmm-utils.cc:1207
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void WriteIntegerVector(std::ostream &os, bool binary, const std::vector< T > &v)
Function for writing STL vectors of integer types.
Definition: io-funcs-inl.h:198
void ChangeReorderingOfAlignment(const TransitionModel &trans_model, std::vector< int32 > *alignment)
Definition: hmm-utils.cc:1260

◆ ConvertAlignmentInternal()

static bool kaldi::ConvertAlignmentInternal ( const TransitionModel old_trans_model,
const TransitionModel new_trans_model,
const ContextDependencyInterface new_ctx_dep,
const std::vector< int32 > &  old_alignment,
int32  conversion_shift,
int32  subsample_factor,
bool  new_is_reordered,
const std::vector< int32 > *  phone_map,
std::vector< int32 > *  new_alignment 
)
static

This function is the same as 'ConvertAligment', but instead of the 'repeat_frames' option it supports the 'conversion_shift' option; see the documentation of ComputeNewPhoneLengths() for what 'conversion_shift' is for.

Definition at line 926 of file hmm-utils.cc.

References ContextDependencyInterface::CentralPosition(), ComputeNewPhoneLengths(), ContextDependencyInterface::ContextWidth(), ConvertAlignmentForPhone(), TransitionModel::GetTopo(), rnnlm::i, IsReordered(), KALDI_ASSERT, KALDI_ERR, KALDI_WARN, SplitToPhones(), and TransitionModel::TransitionIdToPhone().

Referenced by ConvertAlignment().

934  {
935  KALDI_ASSERT(0 <= conversion_shift && conversion_shift < subsample_factor);
936  bool old_is_reordered = IsReordered(old_trans_model, old_alignment);
937  KALDI_ASSERT(new_alignment != NULL);
938  new_alignment->clear();
939  new_alignment->reserve(old_alignment.size());
940  std::vector<std::vector<int32> > old_split; // split into phones.
941  if (!SplitToPhones(old_trans_model, old_alignment, &old_split))
942  return false;
943  int32 phone_sequence_length = old_split.size();
944  std::vector<int32> mapped_phones(phone_sequence_length);
945  for (size_t i = 0; i < phone_sequence_length; i++) {
946  KALDI_ASSERT(!old_split[i].empty());
947  mapped_phones[i] = old_trans_model.TransitionIdToPhone(old_split[i][0]);
948  if (phone_map != NULL) { // Map the phone sequence.
949  int32 sz = phone_map->size();
950  if (mapped_phones[i] < 0 || mapped_phones[i] >= sz ||
951  (*phone_map)[mapped_phones[i]] == -1)
952  KALDI_ERR << "ConvertAlignment: could not map phone " << mapped_phones[i];
953  mapped_phones[i] = (*phone_map)[mapped_phones[i]];
954  }
955  }
956 
957  // the sizes of each element of 'new_split' indicate the length of alignment
958  // that we want for each phone in the new sequence.
959  std::vector<std::vector<int32> > new_split(phone_sequence_length);
960  if (subsample_factor == 1 &&
961  old_trans_model.GetTopo() == new_trans_model.GetTopo()) {
962  // we know the old phone lengths will be fine.
963  for (size_t i = 0; i < phone_sequence_length; i++)
964  new_split[i].resize(old_split[i].size());
965  } else {
966  // .. they may not be fine.
967  std::vector<int32> old_lengths(phone_sequence_length), new_lengths;
968  for (int32 i = 0; i < phone_sequence_length; i++)
969  old_lengths[i] = old_split[i].size();
970  if (!ComputeNewPhoneLengths(new_trans_model.GetTopo(),
971  mapped_phones, old_lengths, conversion_shift,
972  subsample_factor, &new_lengths)) {
973  KALDI_WARN << "Failed to produce suitable phone lengths";
974  return false;
975  }
976  for (int32 i = 0; i < phone_sequence_length; i++)
977  new_split[i].resize(new_lengths[i]);
978  }
979 
980  int32 N = new_ctx_dep.ContextWidth(),
981  P = new_ctx_dep.CentralPosition();
982 
983  // by starting at -N and going to phone_sequence_length + N, we're
984  // being generous and not bothering to work out the exact
985  // array bounds.
986  for (int32 win_start = -N;
987  win_start < static_cast<int32>(phone_sequence_length + N);
988  win_start++) { // start of a context window.
989  int32 central_pos = win_start + P;
990  if (static_cast<size_t>(central_pos) < phone_sequence_length) {
991  // i.e. if (central_pos >= 0 && central_pos < phone_sequence_length)
992  std::vector<int32> new_phone_window(N, 0);
993  for (int32 offset = 0; offset < N; offset++)
994  if (static_cast<size_t>(win_start+offset) < phone_sequence_length)
995  new_phone_window[offset] = mapped_phones[win_start+offset];
996  const std::vector<int32> &old_alignment_for_phone = old_split[central_pos];
997  std::vector<int32> &new_alignment_for_phone = new_split[central_pos];
998 
999  ConvertAlignmentForPhone(old_trans_model, new_trans_model, new_ctx_dep,
1000  old_alignment_for_phone, new_phone_window,
1001  old_is_reordered, new_is_reordered,
1002  &new_alignment_for_phone);
1003  new_alignment->insert(new_alignment->end(),
1004  new_alignment_for_phone.begin(),
1005  new_alignment_for_phone.end());
1006  }
1007  }
1008  KALDI_ASSERT(new_alignment->size() ==
1009  (old_alignment.size() + conversion_shift)/subsample_factor);
1010  return true;
1011 }
static bool IsReordered(const TransitionModel &trans_model, const std::vector< int32 > &alignment)
Definition: hmm-utils.cc:625
kaldi::int32 int32
bool SplitToPhones(const TransitionModel &trans_model, const std::vector< int32 > &alignment, std::vector< std::vector< int32 > > *split_alignment)
SplitToPhones splits up the TransitionIds in "alignment" into their individual phones (one vector per...
Definition: hmm-utils.cc:723
static bool ComputeNewPhoneLengths(const HmmTopology &topology, const std::vector< int32 > &mapped_phones, const std::vector< int32 > &old_lengths, int32 conversion_shift, int32 subsample_factor, std::vector< int32 > *new_lengths)
This function, called from ConvertAlignmentInternal(), works out suitable new lengths of phones in th...
Definition: hmm-utils.cc:849
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
static void ConvertAlignmentForPhone(const TransitionModel &old_trans_model, const TransitionModel &new_trans_model, const ContextDependencyInterface &new_ctx_dep, const std::vector< int32 > &old_phone_alignment, const std::vector< int32 > &new_phone_window, bool old_is_reordered, bool new_is_reordered, std::vector< int32 > *new_phone_alignment)
This function is used internally inside ConvertAlignment; it converts the alignment for a single phon...
Definition: hmm-utils.cc:742
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ConvertCompactLatticeToPhones()

void ConvertCompactLatticeToPhones ( const TransitionModel trans_model,
CompactLattice clat 
)

Given a lattice, and a transition model to map pdf-ids to phones, replace the sequences of transition-ids with sequences of phones.

Note that this is different from ConvertLatticeToPhones, in that we replace the transition-ids not the words.

Definition at line 700 of file lattice-functions.cc.

References TransitionModel::IsFinal(), and TransitionModel::TransitionIdToPhone().

Referenced by main().

701  {
702  typedef CompactLatticeArc Arc;
703  typedef Arc::Weight Weight;
704  int32 num_states = clat->NumStates();
705  for (int32 state = 0; state < num_states; state++) {
706  for (fst::MutableArcIterator<CompactLattice> aiter(clat, state);
707  !aiter.Done();
708  aiter.Next()) {
709  Arc arc(aiter.Value());
710  std::vector<int32> phone_seq;
711  const std::vector<int32> &tid_seq = arc.weight.String();
712  for (std::vector<int32>::const_iterator iter = tid_seq.begin();
713  iter != tid_seq.end(); ++iter) {
714  if (trans.IsFinal(*iter))// note: there is one of these per phone...
715  phone_seq.push_back(trans.TransitionIdToPhone(*iter));
716  }
717  arc.weight.SetString(phone_seq);
718  aiter.SetValue(arc);
719  } // end looping over arcs
720  Weight f = clat->Final(state);
721  if (f != Weight::Zero()) {
722  std::vector<int32> phone_seq;
723  const std::vector<int32> &tid_seq = f.String();
724  for (std::vector<int32>::const_iterator iter = tid_seq.begin();
725  iter != tid_seq.end(); ++iter) {
726  if (trans.IsFinal(*iter))// note: there is one of these per phone...
727  phone_seq.push_back(trans.TransitionIdToPhone(*iter));
728  }
729  f.SetString(phone_seq);
730  clat->SetFinal(state, f);
731  }
732  } // end looping over states
733 }
kaldi::int32 int32
fst::StdArc::Weight Weight
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ ConvertComponent()

nnet2::Component* kaldi::ConvertComponent ( const nnet1::Component nnet1_component,
const bool  use_preconditioned_affine_component 
)

Definition at line 130 of file nnet1-to-raw-nnet.cc.

References ConvertAddShiftComponent(), ConvertAffineTransformComponent(), ConvertRescaleComponent(), ConvertSigmoidComponent(), ConvertSoftmaxComponent(), ConvertSpliceComponent(), Component::GetType(), Component::kAddShift, Component::kAffineTransform, KALDI_ERR, Component::kRescale, Component::kSigmoid, Component::kSoftmax, Component::kSplice, and Component::TypeToMarker().

Referenced by ConvertNnet1ToNnet2().

131  {
132  nnet1::Component::ComponentType type_in = nnet1_component.GetType();
133  switch (type_in) {
134  case nnet1::Component::kAffineTransform:
135  return ConvertAffineTransformComponent(nnet1_component,
136  use_preconditioned_affine_component);
137  case nnet1::Component::kSoftmax:
138  return ConvertSoftmaxComponent(nnet1_component);
139  case nnet1::Component::kSigmoid:
140  return ConvertSigmoidComponent(nnet1_component);
141  case nnet1::Component::kSplice:
142  return ConvertSpliceComponent(nnet1_component); // note, this will for now only handle the
143  // special case nnet1::Component::where all splice indexes in nnet1_component are contiguous, e.g.
144  // -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 .
145  case nnet1::Component::kAddShift:
146  return ConvertAddShiftComponent(nnet1_component); // convert to FixedBiasComponent
147  case nnet1::Component::kRescale:
148  return ConvertRescaleComponent(nnet1_component); // convert to FixedScaleComponent
149  default: KALDI_ERR << "Un-handled nnet1 component type "
150  << nnet1::Component::TypeToMarker(type_in);
151  return NULL;
152  }
153 }
nnet2::Component * ConvertSoftmaxComponent(const nnet1::Component &nnet1_component)
ComponentType
Component type identification mechanism,.
nnet2::Component * ConvertSpliceComponent(const nnet1::Component &nnet1_component)
nnet2::Component * ConvertRescaleComponent(const nnet1::Component &nnet1_component)
#define KALDI_ERR
Definition: kaldi-error.h:147
nnet2::Component * ConvertAddShiftComponent(const nnet1::Component &nnet1_component)
nnet2::Component * ConvertAffineTransformComponent(const nnet1::Component &nnet1_component, const bool use_preconditioned_affine_component)
virtual ComponentType GetType() const =0
Get Type Identification of the component,.
nnet2::Component * ConvertSigmoidComponent(const nnet1::Component &nnet1_component)

◆ ConvertIntToString()

std::string kaldi::ConvertIntToString ( const int &  number)

Definition at line 38 of file pitch-functions-test.cc.

Referenced by UnitTestComputeGPE(), UnitTestDiffSampleRate(), UnitTestKeele(), UnitTestKeeleNccfBallast(), UnitTestPenaltyFactor(), UnitTestPitchExtractionSpeed(), UnitTestPitchExtractorCompareKeele(), and UnitTestProcess().

38  {
39  std::stringstream ss; // create a stringstream
40  ss << number; // add number to the stream
41  return ss.str(); // return a string with the contents of the stream
42 }

◆ ConvertLatticeToPhones()

void ConvertLatticeToPhones ( const TransitionModel trans_model,
Lattice lat 
)

Given a lattice, and a transition model to map pdf-ids to phones, replace the output symbols (presumably words), with phones; we use the TransitionModel to work out the phone sequence.

Note that the phone labels are not exactly aligned with the phone boundaries. We put a phone label to coincide with any transition to the final, nonemitting state of a phone (this state always exists, we ensure this in HmmTopology::Check()). This would be the last transition-id in the phone if reordering is not done (but typically we do reorder). Also see PhoneAlignLattice, in phone-align-lattice.h.

Definition at line 423 of file lattice-functions.cc.

References TransitionModel::IsSelfLoop(), TransitionModel::TransitionIdToHmmState(), and TransitionModel::TransitionIdToPhone().

Referenced by main().

424  {
425  typedef LatticeArc Arc;
426  int32 num_states = lat->NumStates();
427  for (int32 state = 0; state < num_states; state++) {
428  for (fst::MutableArcIterator<Lattice> aiter(lat, state); !aiter.Done();
429  aiter.Next()) {
430  Arc arc(aiter.Value());
431  arc.olabel = 0; // remove any word.
432  if ((arc.ilabel != 0) // has a transition-id on input..
433  && (trans.TransitionIdToHmmState(arc.ilabel) == 0)
434  && (!trans.IsSelfLoop(arc.ilabel))) {
435  // && trans.IsFinal(arc.ilabel)) // there is one of these per phone...
436  arc.olabel = trans.TransitionIdToPhone(arc.ilabel);
437  }
438  aiter.SetValue(arc);
439  } // end looping over arcs
440  } // end looping over states
441 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
kaldi::int32 int32

◆ ConvertLatticeToUnweightedAcceptor()

void kaldi::ConvertLatticeToUnweightedAcceptor ( const kaldi::Lattice ilat,
const LabelPairVector wildcards,
fst::StdVectorFst ofst 
)

Definition at line 63 of file lattice-oracle.cc.

References fst::ConvertLattice().

Referenced by main().

65  {
66  // first convert from lattice to normal FST
67  fst::ConvertLattice(ilat, ofst);
68  // remove weights, project to output, sort according to input arg
69  fst::Map(ofst, fst::RmWeightMapper<fst::StdArc>());
70  fst::Project(ofst, fst::PROJECT_OUTPUT); // The words are on the output side
71  fst::Relabel(ofst, wildcards, wildcards);
72  fst::RmEpsilon(ofst); // Don't tolerate epsilons as they make it hard to
73  // tally errors
74  fst::ArcSort(ofst, fst::StdILabelCompare());
75 }
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.

◆ ConvertNnet1ToNnet2()

nnet2::Nnet* kaldi::ConvertNnet1ToNnet2 ( const nnet1::Nnet nnet1,
const bool  use_preconditioned_affine_component 
)

Definition at line 156 of file nnet1-to-raw-nnet.cc.

References ConvertComponent(), Nnet::GetComponent(), rnnlm::i, and Nnet::NumComponents().

Referenced by main().

157  {
158  // get a vector of nnet2::Component pointers and initialize the nnet2::Nnet with it.
159  size_t size = nnet1.NumComponents();
160  std::vector<nnet2::Component*> *components = new std::vector<nnet2::Component*>();
161  components->resize(size);
162  for (size_t i = 0; i < size; i++) {
163  (*components)[i] = ConvertComponent(nnet1.GetComponent(i),
164  use_preconditioned_affine_component);
165  }
166 
167  nnet2::Nnet *res = new nnet2::Nnet();
168  res->Init(components);
169  delete components;
170  return res;
171 }
int32 NumComponents() const
Returns the number of &#39;Components&#39; which form the NN.
Definition: nnet-nnet.h:66
const Component & GetComponent(int32 c) const
Component accessor,.
Definition: nnet-nnet.cc:153
nnet2::Component * ConvertComponent(const nnet1::Component &nnet1_component, const bool use_preconditioned_affine_component)

◆ ConvertPostToGaussInfo()

static void kaldi::ConvertPostToGaussInfo ( const std::vector< std::vector< std::pair< int32, BaseFloat > > > &  gauss_post,
std::unordered_map< int32, GaussInfo > *  gauss_info 
)
static

Definition at line 594 of file ivector-extractor.cc.

References GaussInfo::frame_weights, and GaussInfo::tot_weight.

Referenced by OnlineIvectorEstimationStats::AccStats().

596  {
597  int32 num_frames = gauss_post.size();
598  for (int32 t = 0; t < num_frames; t++) {
599  const std::vector<std::pair<int32, BaseFloat> > &this_post = gauss_post[t];
600  auto iter = this_post.begin(), end = this_post.end();
601  for (; iter != end; ++iter) {
602  int32 gauss_idx = iter->first;
603  GaussInfo &info = (*gauss_info)[gauss_idx];
604  BaseFloat weight = iter->second;
605  info.tot_weight += weight;
606  info.frame_weights.push_back(std::pair<int32, BaseFloat>(t, weight));
607  }
608  }
609 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29

◆ ConvertRescaleComponent()

nnet2::Component* kaldi::ConvertRescaleComponent ( const nnet1::Component nnet1_component)

Definition at line 114 of file nnet1-to-raw-nnet.cc.

References Rescale::GetParams(), FixedScaleComponent::Init(), KALDI_ASSERT, and Rescale::NumParams().

Referenced by ConvertComponent().

115  {
116  const nnet1::Rescale *rescale =
117  dynamic_cast<const nnet1::Rescale*>(&nnet1_component);
118  KALDI_ASSERT(rescale != NULL);
119 
120  Vector<BaseFloat> scale(rescale->NumParams());
121  rescale->GetParams(&scale);
122 
123  CuVector<BaseFloat> cu_scale(scale);
124 
126  res->Init(cu_scale);
127  return res;
128 }
Rescale the data column-wise by a vector (can be used for global variance normalization) ...
Definition: nnet-various.h:404
FixedScaleComponent applies a fixed per-element scale; it&#39;s similar to the Rescale component in the n...
void GetParams(VectorBase< BaseFloat > *params) const
Get the trainable parameters reshaped as a vector,.
Definition: nnet-various.h:457
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Init(const CuVectorBase< BaseFloat > &scales)
int32 NumParams() const
Number of trainable parameters,.
Definition: nnet-various.h:450

◆ ConvertSigmoidComponent()

nnet2::Component* kaldi::ConvertSigmoidComponent ( const nnet1::Component nnet1_component)

Definition at line 71 of file nnet1-to-raw-nnet.cc.

References Component::InputDim(), and KALDI_ASSERT.

Referenced by ConvertComponent().

72  {
73  const nnet1::Sigmoid *sigmoid =
74  dynamic_cast<const nnet1::Sigmoid*>(&nnet1_component);
75  KALDI_ASSERT(sigmoid != NULL);
76  return new nnet2::SigmoidComponent(sigmoid->InputDim());
77 }
int32 InputDim() const
Get the dimension of the input,.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ConvertSoftmaxComponent()

nnet2::Component* kaldi::ConvertSoftmaxComponent ( const nnet1::Component nnet1_component)

Definition at line 63 of file nnet1-to-raw-nnet.cc.

References Component::InputDim(), and KALDI_ASSERT.

Referenced by ConvertComponent().

64  {
65  const nnet1::Softmax *softmax =
66  dynamic_cast<const nnet1::Softmax*>(&nnet1_component);
67  KALDI_ASSERT(softmax != NULL);
68  return new nnet2::SoftmaxComponent(softmax->InputDim());
69 }
int32 InputDim() const
Get the dimension of the input,.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ConvertSpliceComponent()

nnet2::Component* kaldi::ConvertSpliceComponent ( const nnet1::Component nnet1_component)

Definition at line 79 of file nnet1-to-raw-nnet.cc.

References SpliceComponent::Init(), Component::InputDim(), KALDI_ASSERT, ReadIntegerVector(), and Splice::WriteData().

Referenced by ConvertComponent().

80  {
81  const nnet1::Splice *splice =
82  dynamic_cast<const nnet1::Splice*>(&nnet1_component);
83  KALDI_ASSERT(splice != NULL);
84 // int32 low, high;
85  std::vector<int32> frame_offsets;
86 
87  std::ostringstream ostr;
88  splice->WriteData(ostr, false);
89 
90  std::istringstream istr(ostr.str());
91  ReadIntegerVector(istr, false, &frame_offsets);
92 
94  res->Init(splice->InputDim(), frame_offsets);
95  return res;
96 }
void Init(int32 input_dim, std::vector< int32 > context, int32 const_component_dim=0)
void ReadIntegerVector(std::istream &is, bool binary, std::vector< T > *v)
Function for reading STL vector of integer types.
Definition: io-funcs-inl.h:232
Splices the time context of the input features in N, out k*N, FrameOffset o_1,o_2,...,o_k FrameOffset example 11frames: -5 -4 -3 -2 -1 0 1 2 3 4 5.
Definition: nnet-various.h:42
int32 InputDim() const
Get the dimension of the input,.
void WriteData(std::ostream &os, bool binary) const
Writes the component content.
Definition: nnet-various.h:94
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Splices a context window of frames together [over time].

◆ ConvertStringToInteger()

bool kaldi::ConvertStringToInteger ( const std::string &  str,
Int *  out 
)

Converts a string into an integer via strtoll and returns false if there was any kind of problem (i.e.

the string was not an integer or contained extra non-whitespace junk, or the integer was too large to fit into the type it is being converted into). Only sets *out if everything was OK and it returns true.

Definition at line 118 of file text-utils.h.

References ConvertStringToReal(), rnnlm::i, IsLine(), IsToken(), KALDI_ASSERT_IS_INTEGER_TYPE, KALDI_STRTOLL, SplitStringOnFirstSpace(), StringsApproxEqual(), and Trim().

Referenced by ExampleMergingConfig::ComputeDerived(), ConfigLine::GetValue(), WordBoundaryInfo::Init(), MultiTaskLoss::InitFromString(), main(), GeneralDescriptor::ParseConst(), kaldi::nnet2::ParseFromString(), kaldi::nnet3::ProcessRangeFile(), ArpaFileParser::Read(), HmmTopology::Read(), fst::ReadFstKaldi(), kaldi::nnet3::ReadIntegerToken(), ReadPosterior(), LatticeReader::ReadText(), kaldi::nnet3::SelectFromExample(), Fmpe::SetContexts(), OffsetFileInputImpl::SplitFilename(), TestConvertStringToInteger(), ParseOptions::ToInt(), and ParseOptions::ToUint().

119  {
121  const char *this_str = str.c_str();
122  char *end = NULL;
123  errno = 0;
124  int64 i = KALDI_STRTOLL(this_str, &end);
125  if (end != this_str)
126  while (isspace(*end)) end++;
127  if (end == this_str || *end != '\0' || errno != 0)
128  return false;
129  Int iInt = static_cast<Int>(i);
130  if (static_cast<int64>(iInt) != i ||
131  (i < 0 && !std::numeric_limits<Int>::is_signed)) {
132  return false;
133  }
134  *out = iInt;
135  return true;
136 }
#define KALDI_ASSERT_IS_INTEGER_TYPE(I)
Definition: kaldi-utils.h:133
#define KALDI_STRTOLL(cur_cstr, end_cstr)
Definition: kaldi-utils.h:152

◆ ConvertStringToReal() [1/3]

bool ConvertStringToReal ( const std::string &  str,
T *  out 
)

ConvertStringToReal converts a string into either float or double and returns false if there was any kind of problem (i.e.

the string was not a floating point number or contained extra non-whitespace junk). Be careful- this function will successfully read inf's or nan's.

Definition at line 238 of file text-utils.cc.

References rnnlm::i.

Referenced by ConvertStringToInteger(), kaldi::nnet3::DescriptorTokenize(), ConfigLine::GetValue(), MultiTaskLoss::InitFromString(), main(), GeneralDescriptor::ParseConst(), kaldi::nnet2::ParseFromString(), GeneralDescriptor::ParseScale(), ArpaFileParser::Read(), ReadCommaSeparatedCommand(), Fmpe::SetContexts(), SplitStringToFloats(), TestConvertStringToReal(), TestInf(), TestNan(), ParseOptions::ToDouble(), and ParseOptions::ToFloat().

239  {
240  std::istringstream iss(str);
241 
242  NumberIstream<T> i(iss);
243 
244  i >> *out;
245 
246  if (iss.fail()) {
247  // Number conversion failed.
248  return false;
249  }
250 
251  return true;
252 }

◆ ConvertStringToReal() [2/3]

template bool kaldi::ConvertStringToReal ( const std::string &  str,
float out 
)

◆ ConvertStringToReal() [3/3]

template bool kaldi::ConvertStringToReal ( const std::string &  str,
double *  out 
)

◆ ConvertToCompactLattice() [1/2]

CompactLattice* kaldi::ConvertToCompactLattice ( fst::VectorFst< OrigWeightType > *  ifst)

Converts lattice types if necessary, deleting its input.

Definition at line 29 of file kaldi-lattice.cc.

References fst::ConvertLattice().

Referenced by ReadCompactLattice(), and ReadCompactLatticeText().

29  {
30  if (!ifst) return NULL;
31  CompactLattice *ofst = new CompactLattice();
32  ConvertLattice(*ifst, ofst);
33  delete ifst;
34  return ofst;
35 }
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46

◆ ConvertToCompactLattice() [2/2]

CompactLattice* kaldi::ConvertToCompactLattice ( CompactLattice ifst)

Definition at line 40 of file kaldi-lattice.cc.

40  {
41  return ifst;
42 }

◆ ConvertToLattice() [1/2]

Lattice* kaldi::ConvertToLattice ( fst::VectorFst< OrigWeightType > *  ifst)

Converts lattice types if necessary, deleting its input.

Definition at line 46 of file kaldi-lattice.cc.

References fst::ConvertLattice().

Referenced by ReadLattice(), and ReadLatticeText().

46  {
47  if (!ifst) return NULL;
48  Lattice *ofst = new Lattice();
49  ConvertLattice(*ifst, ofst);
50  delete ifst;
51  return ofst;
52 }
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44

◆ ConvertToLattice() [2/2]

Lattice* kaldi::ConvertToLattice ( Lattice ifst)

Definition at line 57 of file kaldi-lattice.cc.

57  {
58  return ifst;
59 }

◆ ConvolveSignals()

void ConvolveSignals ( const Vector< BaseFloat > &  filter,
Vector< BaseFloat > *  signal 
)

Definition at line 34 of file signal.cc.

References VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Dim(), rnnlm::i, rnnlm::j, Vector< Real >::Resize(), and VectorBase< Real >::SetZero().

Referenced by UnitTestFFTbasedConvolution().

34  {
35  int32 signal_length = signal->Dim();
36  int32 filter_length = filter.Dim();
37  int32 output_length = signal_length + filter_length - 1;
38  Vector<BaseFloat> signal_padded(output_length);
39  signal_padded.SetZero();
40  for (int32 i = 0; i < signal_length; i++) {
41  for (int32 j = 0; j < filter_length; j++) {
42  signal_padded(i + j) += (*signal)(i) * filter(j);
43  }
44  }
45  signal->Resize(output_length);
46  signal->CopyFromVec(signal_padded);
47 }
kaldi::int32 int32

◆ CopyMapKeysToSet()

void kaldi::CopyMapKeysToSet ( const std::map< A, B > &  m,
std::set< A > *  s 
)

Copies the keys in a map to a set.

Definition at line 150 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by TestCopyMapKeysToSet(), and TestFindAllKeys().

150  {
151  KALDI_ASSERT(s != NULL);
152  s->clear();
153  typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
154  for (; miter != mend; ++miter) {
155  s->insert(s->end(), miter->first);
156  }
157 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyMapKeysToVector()

void kaldi::CopyMapKeysToVector ( const std::map< A, B > &  m,
std::vector< A > *  v 
)

Copies the keys in a map to a vector.

Definition at line 126 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by Questions::GetKeysWithQuestions(), TestCopyMapKeysToSet(), and TestCopyMapKeysToVector().

126  {
127  KALDI_ASSERT(v != NULL);
128  v->resize(m.size());
129  typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
130  typename std::vector<A>::iterator viter = v->begin();
131  for (; miter != mend; ++miter, ++viter) {
132  *viter = miter->first;
133  }
134 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyMapToVector()

void kaldi::CopyMapToVector ( const std::map< A, B > &  m,
std::vector< std::pair< A, B > > *  v 
)

Copies the (key, value) pairs in a map to a vector of pairs.

Definition at line 112 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by GenRandStats(), TestCopyMapToVector(), TestFindAllKeys(), and TestPossibleValues().

113  {
114  KALDI_ASSERT(v != NULL);
115  v->resize(m.size());
116  typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
117  typename std::vector<std::pair<A, B> >::iterator viter = v->begin();
118  for (; miter != mend; ++miter, ++viter) {
119  *viter = std::make_pair(miter->first, miter->second);
120  // do it like this because of const casting.
121  }
122 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyMapValuesToSet()

void kaldi::CopyMapValuesToSet ( const std::map< A, B > &  m,
std::set< B > *  s 
)

Copies the values in a map to a set.

Definition at line 161 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by TestCopyMapValuesToSet().

161  {
162  KALDI_ASSERT(s != NULL);
163  s->clear();
164  typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
165  for (; miter != mend; ++miter)
166  s->insert(s->end(), miter->second);
167 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyMapValuesToVector()

void kaldi::CopyMapValuesToVector ( const std::map< A, B > &  m,
std::vector< B > *  v 
)

Copies the values in a map to a vector.

Definition at line 138 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by TestCopyMapValuesToSet(), and TestCopyMapValuesToVector().

138  {
139  KALDI_ASSERT(v != NULL);
140  v->resize(m.size());
141  typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
142  typename std::vector<B>::iterator viter = v->begin();
143  for (; miter != mend; ++miter, ++viter) {
144  *viter = miter->second;
145  }
146 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopySetToVector() [1/2]

void kaldi::CopySetToVector ( const std::set< T > &  s,
std::vector< T > *  v 
)

Copies the elements of a set to a vector.

Definition at line 86 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by ConstIntegerSet< EventValueType >::ConstIntegerSet(), fst::GetInputSymbols(), kaldi::nnet3::GetIoNames(), fst::GetOutputSymbols(), GetSeenPhones(), ConstIntegerSet< EventValueType >::Init(), PossibleValues(), RandomEventMap(), TestClusterEventMapRestricted(), fst::TestContextFst(), TestCopySetToVector(), TestEventMapIo(), TestFindAllKeys(), TestGenRandContextDependency(), TestMonophoneContextDependency(), TestPossibleValues(), TestQuestionsInitRand(), TestShareEventMapLeaves(), and TestSplitDecisionTree().

86  {
87  // copies members of s into v, in sorted order from lowest to highest
88  // (because the set was in sorted order).
89  KALDI_ASSERT(v != NULL);
90  v->resize(s.size());
91  typename std::set<T>::const_iterator siter = s.begin(), send = s.end();
92  typename std::vector<T>::iterator viter = v->begin();
93  for (; siter != send; ++siter, ++viter) {
94  *viter = *siter;
95  }
96 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopySetToVector() [2/2]

void kaldi::CopySetToVector ( const unordered_set< T > &  s,
std::vector< T > *  v 
)

Definition at line 99 of file stl-utils.h.

References KALDI_ASSERT.

99  {
100  KALDI_ASSERT(v != NULL);
101  v->resize(s.size());
102  typename unordered_set<T>::const_iterator siter = s.begin(), send = s.end();
103  typename std::vector<T>::iterator viter = v->begin();
104  for (; siter != send; ++siter, ++viter) {
105  *viter = *siter;
106  }
107 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopySubsetLattices() [1/2]

int32 kaldi::CopySubsetLattices ( std::string  filename,
SequentialLatticeReader lattice_reader,
LatticeWriter lattice_writer,
bool  include = true,
bool  ignore_missing = false,
bool  sorted = false 
)

Definition at line 28 of file lattice-copy.cc.

References SequentialTableReader< Holder >::Done(), KALDI_ASSERT, KALDI_ERR, KALDI_LOG, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), SplitStringToVector(), Input::Stream(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

32  {
33  unordered_set<std::string, StringHasher> subset;
34  std::set<std::string> subset_list;
35 
36  bool binary;
37  Input ki(filename, &binary);
38  KALDI_ASSERT(!binary);
39  std::string line;
40  while (std::getline(ki.Stream(), line)) {
41  std::vector<std::string> split_line;
42  SplitStringToVector(line, " \t\r", true, &split_line);
43  if(split_line.empty()) {
44  KALDI_ERR << "Unable to parse line \"" << line << "\" encountered in input in " << filename;
45  }
46  subset.insert(split_line[0]);
47  subset_list.insert(split_line[0]);
48  }
49 
50  int32 num_total = 0;
51  size_t num_success = 0;
52  for (; !lattice_reader->Done(); lattice_reader->Next(), num_total++) {
53  if (include && sorted && subset_list.size() > 0
54  && lattice_reader->Key() > *(subset_list.rbegin())) {
55  KALDI_LOG << "The utterance " << lattice_reader->Key()
56  << " is larger than "
57  << "the last key in the include list. Not reading further.";
58  KALDI_LOG << "Wrote " << num_success << " utterances";
59  return 0;
60  }
61 
62  if (include && subset.count(lattice_reader->Key()) > 0) {
63  lattice_writer->Write(lattice_reader->Key(), lattice_reader->Value());
64  num_success++;
65  } else if (!include && subset.count(lattice_reader->Key()) == 0) {
66  lattice_writer->Write(lattice_reader->Key(), lattice_reader->Value());
67  num_success++;
68  }
69  }
70 
71  KALDI_LOG << "Wrote " << num_success << " out of " << num_total
72  << " utterances.";
73 
74  if (ignore_missing) return 0;
75 
76  return (num_success != 0 ? 0 : 1);
77  }
kaldi::int32 int32
void Write(const std::string &key, const T &value) const
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ CopySubsetLattices() [2/2]

int32 kaldi::CopySubsetLattices ( std::string  filename,
SequentialCompactLatticeReader lattice_reader,
CompactLatticeWriter lattice_writer,
bool  include = true,
bool  ignore_missing = false,
bool  sorted = false 
)

Definition at line 79 of file lattice-copy.cc.

References SequentialTableReader< Holder >::Done(), KALDI_ASSERT, KALDI_ERR, KALDI_LOG, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), SplitStringToVector(), Input::Stream(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

83  {
84  unordered_set<std::string, StringHasher> subset;
85  std::set<std::string> subset_list;
86 
87  bool binary;
88  Input ki(filename, &binary);
89  KALDI_ASSERT(!binary);
90  std::string line;
91  while (std::getline(ki.Stream(), line)) {
92  std::vector<std::string> split_line;
93  SplitStringToVector(line, " \t\r", true, &split_line);
94  if(split_line.empty()) {
95  KALDI_ERR << "Unable to parse line \"" << line << "\" encountered in input in " << filename;
96  }
97  subset.insert(split_line[0]);
98  subset_list.insert(split_line[0]);
99  }
100 
101  int32 num_total = 0;
102  size_t num_success = 0;
103  for (; !lattice_reader->Done(); lattice_reader->Next(), num_total++) {
104  if (include && sorted && subset_list.size() > 0
105  && lattice_reader->Key() > *(subset_list.rbegin())) {
106  KALDI_LOG << "The utterance " << lattice_reader->Key()
107  << " is larger than "
108  << "the last key in the include list. Not reading further.";
109  KALDI_LOG << "Wrote " << num_success << " utterances";
110  return 0;
111  }
112 
113  if (include && subset.count(lattice_reader->Key()) > 0) {
114  lattice_writer->Write(lattice_reader->Key(), lattice_reader->Value());
115  num_success++;
116  } else if (!include && subset.count(lattice_reader->Key()) == 0) {
117  lattice_writer->Write(lattice_reader->Key(), lattice_reader->Value());
118  num_success++;
119  }
120  }
121 
122  KALDI_LOG << " Wrote " << num_success << " out of " << num_total
123  << " utterances.";
124 
125  if (ignore_missing) return 0;
126 
127  return (num_success != 0 ? 0 : 1);
128  }
kaldi::int32 int32
void Write(const std::string &key, const T &value) const
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ CopyVectorToSet()

void kaldi::CopyVectorToSet ( const std::vector< A > &  v,
std::set< A > *  s 
)

Copies the contents of a vector to a set.

Definition at line 172 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by kaldi::nnet3::ComputeCommandPairs(), TestCopyMapKeysToSet(), and TestCopyMapValuesToSet().

172  {
173  KALDI_ASSERT(s != NULL);
174  s->clear();
175  typename std::vector<A>::const_iterator iter = v.begin(), end = v.end();
176  for (; iter != end; ++iter)
177  s->insert(s->end(), *iter);
178  // s->end() is a hint in case v was sorted. will work regardless.
179 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CopyVectorToVector()

void kaldi::CopyVectorToVector ( const std::vector< A > &  vec_in,
std::vector< B > *  vec_out 
)

Copies the contents a vector of one type to a vector of another type.

Definition at line 207 of file stl-utils.h.

References rnnlm::i, and KALDI_ASSERT.

207  {
208  KALDI_ASSERT(vec_out != NULL);
209  vec_out->resize(vec_in.size());
210  for (size_t i = 0; i < vec_in.size(); i++)
211  (*vec_out)[i] = static_cast<B> (vec_in[i]);
212 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CountErrors()

void kaldi::CountErrors ( const fst::StdVectorFst fst,
int32 correct,
int32 substitutions,
int32 insertions,
int32 deletions,
int32 num_words 
)

Definition at line 114 of file lattice-oracle.cc.

References KALDI_ASSERT.

Referenced by main().

119  {
121  typedef fst::StdArc::Weight Weight;
122  *correct = *substitutions = *insertions = *deletions = *num_words = 0;
123 
124  // go through the first complete path in fst (there should be only one)
125  StateId src = fst.Start();
126  while (fst.Final(src)== Weight::Zero()) { // while not final
127  for (fst::ArcIterator<fst::StdVectorFst> aiter(fst, src);
128  !aiter.Done(); aiter.Next()) {
129  fst::StdArc arc = aiter.Value();
130  if (arc.ilabel == arc.olabel && arc.ilabel != 0) {
131  (*correct)++;
132  (*num_words)++;
133  } else if (arc.ilabel == 0 && arc.olabel != 0) {
134  (*deletions)++;
135  (*num_words)++;
136  } else if (arc.ilabel != 0 && arc.olabel == 0) {
137  (*insertions)++;
138  } else if (arc.ilabel != 0 && arc.olabel != 0) {
139  (*substitutions)++;
140  (*num_words)++;
141  } else {
142  KALDI_ASSERT(arc.ilabel == 0 && arc.olabel == 0);
143  }
144  src = arc.nextstate;
145  continue; // jump to next state
146  }
147  }
148 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::StdArc StdArc
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CoverageTest()

bool kaldi::CoverageTest ( bool  seps,
const std::string &  infile 
)

Definition at line 119 of file arpa-lm-compiler-test.cc.

References AddSelfLoops(), Compile(), CreateGenFst(), ArpaLmCompiler::Fst(), rnnlm::i, KALDI_WARN, kRandomSentences, and ArpaLmCompiler::MutableFst().

Referenced by RunAllTests().

119  {
120  // Compile ARPA model.
121  ArpaLmCompiler* lm_compiler = Compile(seps, infile);
122 
123  // Create an FST that generates any sequence of symbols taken from the model
124  // output.
125  fst::StdVectorFst* genFst =
126  CreateGenFst(seps, lm_compiler->Fst().OutputSymbols());
127 
128  int num_successes = 0;
129  for (int32 i = 0; i < kRandomSentences; ++i) {
130  // Generate a random sentence FST.
131  fst::StdVectorFst sentence;
132  RandGen(*genFst, &sentence);
133  if (seps)
134  AddSelfLoops(&sentence);
135 
136  fst::ArcSort(lm_compiler->MutableFst(), fst::StdOLabelCompare());
137 
138  // The past must successfully compose with the LM FST.
139  fst::StdVectorFst composition;
140  Compose(sentence, lm_compiler->Fst(), &composition);
141  if (composition.Start() != fst::kNoStateId)
142  ++num_successes;
143  }
144 
145  delete genFst;
146  delete lm_compiler;
147 
148  bool ok = num_successes == kRandomSentences;
149  if (!ok) {
150  KALDI_WARN << "Coverage test failed on " << infile << ": composed "
151  << num_successes << "/" << kRandomSentences;
152  }
153  return ok;
154 }
void AddSelfLoops(fst::StdMutableFst *fst)
ArpaLmCompiler * Compile(bool seps, const std::string &infile)
static fst::StdVectorFst * CreateGenFst(bool seps, const fst::SymbolTable *pst)
kaldi::int32 int32
fst::StdVectorFst StdVectorFst
#define KALDI_WARN
Definition: kaldi-error.h:150
static const int kRandomSentences

◆ CreateEditDistance()

void kaldi::CreateEditDistance ( const fst::StdVectorFst fst1,
const fst::StdVectorFst fst2,
fst::StdVectorFst pfst 
)

Definition at line 77 of file lattice-oracle.cc.

References fst::GetInputSymbols(), fst::GetOutputSymbols(), rnnlm::i, and rnnlm::j.

Referenced by main().

79  {
80  typedef fst::StdArc StdArc;
82  typedef fst::StdArc::Label Label;
83  Weight correct_cost(0.0);
84  Weight substitution_cost(1.0);
85  Weight insertion_cost(1.0);
86  Weight deletion_cost(1.0);
87 
88  // create set of output symbols in fst1
89  std::vector<Label> fst1syms, fst2syms;
90  GetOutputSymbols(fst1, false /*no epsilons*/, &fst1syms);
91  GetInputSymbols(fst2, false /*no epsilons*/, &fst2syms);
92 
93  pfst->AddState();
94  pfst->SetStart(0);
95  for (size_t i = 0; i < fst1syms.size(); i++)
96  pfst->AddArc(0, StdArc(fst1syms[i], 0, deletion_cost, 0)); // deletions
97 
98  for (size_t i = 0; i < fst2syms.size(); i++)
99  pfst->AddArc(0, StdArc(0, fst2syms[i], insertion_cost, 0)); // insertions
100 
101  // stupid implementation O(N^2)
102  for (size_t i = 0; i < fst1syms.size(); i++) {
103  Label label1 = fst1syms[i];
104  for (size_t j = 0; j < fst2syms.size(); j++) {
105  Label label2 = fst2syms[j];
106  Weight cost(label1 == label2 ? correct_cost : substitution_cost);
107  pfst->AddArc(0, StdArc(label1, label2, cost, 0)); // substitutions
108  }
109  }
110  pfst->SetFinal(0, Weight::One());
111  ArcSort(pfst, fst::StdOLabelCompare());
112 }
fst::StdArc::Label Label
fst::StdArc StdArc
void GetInputSymbols(const Fst< Arc > &fst, bool include_eps, std::vector< I > *symbols)
GetInputSymbols gets the list of symbols on the input of fst (including epsilon, if include_eps == tr...
fst::StdArc::Weight Weight
void GetOutputSymbols(const Fst< Arc > &fst, bool include_eps, std::vector< I > *symbols)
GetOutputSymbols gets the list of symbols on the output of fst (including epsilon, if include_eps == true)

◆ CreateEigenvalueMatrix() [1/2]

template void kaldi::CreateEigenvalueMatrix ( const VectorBase< float > &  re,
const VectorBase< float > &  im,
MatrixBase< float > *  D 
)

◆ CreateEigenvalueMatrix() [2/2]

template void kaldi::CreateEigenvalueMatrix ( const VectorBase< double > &  re,
const VectorBase< double > &  im,
MatrixBase< double > *  D 
)

◆ CreateFactorTransducer()

bool CreateFactorTransducer ( const CompactLattice clat,
const std::vector< int32 > &  state_times,
int32  utterance_id,
KwsProductFst factor_transducer 
)

Definition at line 160 of file kws-functions.cc.

References ComputeCompactLatticeAlphas(), ComputeCompactLatticeBetas(), fst::ComputeStateInfo(), rnnlm::i, KALDI_WARN, fst::kStateHasEpsilonArcsEntering, fst::kStateHasEpsilonArcsLeaving, fst::kStateHasNonEpsilonArcsEntering, fst::kStateHasNonEpsilonArcsLeaving, and ArcticWeightTpl< T >::One().

Referenced by main().

163  {
164  using namespace fst;
166 
167  // We first compute the alphas and betas
168  bool success = false;
169  std::vector<double> alpha;
170  std::vector<double> beta;
171  success = ComputeCompactLatticeAlphas(clat, &alpha);
172  success = success && ComputeCompactLatticeBetas(clat, &beta);
173  if (!success)
174  return false;
175 
176  // Now we map the CompactLattice to VectorFst<KwsProductArc>. We drop the
177  // alignment information and only keep the negated log-probs
178  Map(clat, factor_transducer, CompactLatticeToKwsProductFstMapper());
179 
180  // Now do the weight pushing manually on the CompactLattice format. Note that
181  // the alphas and betas in Kaldi are stored as the log-probs, not the negated
182  // log-probs, so the equation for weight pushing is a little different from
183  // the original algorithm (pay attention to the sign). We push the weight to
184  // initial and remove the total weight, i.e., the sum of all the outgoing
185  // transitions and final weight at any state is equal to One() (push only the
186  // negated log-prob, not the alignments)
187  for (StateIterator<KwsProductFst>
188  siter(*factor_transducer); !siter.Done(); siter.Next()) {
189  KwsProductArc::StateId state_id = siter.Value();
190  for (MutableArcIterator<KwsProductFst>
191  aiter(factor_transducer, state_id); !aiter.Done(); aiter.Next()) {
192  KwsProductArc arc = aiter.Value();
193  BaseFloat w = arc.weight.Value1().Value();
194  w += beta[state_id] - beta[arc.nextstate];
195  KwsProductWeight weight(w, arc.weight.Value2());
196  arc.weight = weight;
197  aiter.SetValue(arc);
198  }
199  // Weight of final state
200  if (factor_transducer->Final(state_id) != KwsProductWeight::Zero()) {
201  BaseFloat w = factor_transducer->Final(state_id).Value1().Value();
202  w += beta[state_id];
203  KwsProductWeight weight(w, factor_transducer->Final(state_id).Value2());
204  factor_transducer->SetFinal(state_id, weight);
205  }
206  }
207 
208  // Modify the alphas and set betas to zero. After that, we get the alphas and
209  // betas for the pushed FST. Since I will not use beta anymore, here I don't
210  // set them to zero. This can be derived from the weight pushing formula.
211  for (int32 s = 0; s < alpha.size(); s++) {
212  alpha[s] += beta[s] - beta[0];
213 
214  if (alpha[s] > 0.1) {
215  KALDI_WARN << "Positive alpha " << alpha[s];
216  }
217  }
218 
219  // to understand the next part, look at the comment in
220  // ../kwsbin/lattice-to-kws-index.cc just above the call to
221  // EnsureEpsilonProperty(). We use the bool has_epsilon_property mainly to
222  // handle the case when someone comments out that call. It should always be
223  // true in the normal case.
224  std::vector<char> state_properties;
225  ComputeStateInfo(*factor_transducer, &state_properties);
226  bool has_epsilon_property = true;
227  for (size_t i = 0; i < state_properties.size(); i++) {
228  char c = state_properties[i];
229  if ((c & kStateHasEpsilonArcsEntering) != 0 &&
231  has_epsilon_property = false;
232  if ((c & kStateHasEpsilonArcsLeaving) != 0 &&
234  has_epsilon_property = false;
235  }
236  if (!has_epsilon_property) {
237  KALDI_WARN << "Epsilon property does not hold, reverting to old behavior.";
238  }
239 
240  // OK, after the above preparation, we finally come to the factor generation
241  // step.
242  StateId ns = factor_transducer->NumStates();
243  StateId ss = factor_transducer->AddState();
244  StateId fs = factor_transducer->AddState();
245  factor_transducer->SetStart(ss);
246  factor_transducer->SetFinal(fs, KwsProductWeight::One());
247 
248  for (StateId s = 0; s < ns; s++) {
249  // Add arcs from initial state to current state
250  if (!has_epsilon_property ||
251  (state_properties[s] & kStateHasNonEpsilonArcsLeaving))
252  factor_transducer->AddArc(ss, KwsProductArc(0, 0, KwsProductWeight(-alpha[s], StdXStdprimeWeight(state_times[s], ArcticWeight::One())), s));
253  // Add arcs from current state to final state
254  if (!has_epsilon_property ||
255  (state_properties[s] & kStateHasNonEpsilonArcsEntering))
256  factor_transducer->AddArc(s, KwsProductArc(0, utterance_id, KwsProductWeight(0, StdXStdprimeWeight(TropicalWeight::One(), state_times[s])), fs));
257  // The old final state is not final any more
258  if (factor_transducer->Final(s) != KwsProductWeight::Zero())
259  factor_transducer->SetFinal(s, KwsProductWeight::Zero());
260  }
261 
262  return true;
263 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
LogXStdXStdprimeWeight KwsProductWeight
Definition: kaldi-kws.h:47
void ComputeStateInfo(const VectorFst< Arc > &fst, std::vector< char > *epsilon_info)
This function will set epsilon_info to have size equal to the NumStates() of the FST, containing a logical-or of the enum values kStateHasEpsilonArcsEntering, kStateHasNonEpsilonArcsEntering, kStateHasEpsilonArcsLeaving, and kStateHasNonEpsilonArcsLeaving.
fst::ProductWeight< TropicalWeight, ArcticWeight > StdXStdprimeWeight
Definition: kaldi-kws.h:39
static const ArcticWeightTpl< T > One()
Definition: arctic-weight.h:48
bool ComputeCompactLatticeBetas(const CompactLattice &clat, vector< double > *beta)
#define KALDI_WARN
Definition: kaldi-error.h:150
float BaseFloat
LogXStdXStdprimeArc KwsProductArc
Definition: kaldi-kws.h:48
bool ComputeCompactLatticeAlphas(const CompactLattice &clat, vector< double > *alpha)

◆ CreateGenFst()

static fst::StdVectorFst* kaldi::CreateGenFst ( bool  seps,
const fst::SymbolTable *  pst 
)
static

Definition at line 44 of file arpa-lm-compiler-test.cc.

References kBos, kDisambig, kEos, and kEps.

Referenced by CoverageTest().

44  {
46  genFst->SetInputSymbols(pst);
47  genFst->SetOutputSymbols(pst);
48 
49  fst::StdArc::StateId midId = genFst->AddState();
50  if (!seps) {
51  fst::StdArc::StateId initId = genFst->AddState();
52  fst::StdArc::StateId finalId = genFst->AddState();
53  genFst->SetStart(initId);
54  genFst->SetFinal(finalId, fst::StdArc::Weight::One());
55  genFst->AddArc(initId, fst::StdArc(kBos, kBos, 0, midId));
56  genFst->AddArc(midId, fst::StdArc(kEos, kEos, 0, finalId));
57  } else {
58  genFst->SetStart(midId);
59  genFst->SetFinal(midId, fst::StdArc::Weight::One());
60  }
61 
62  // Add a loop for each symbol in the table except the four special ones.
63  fst::SymbolTableIterator si(*pst);
64  for (si.Reset(); !si.Done(); si.Next()) {
65  if (si.Value() == kBos || si.Value() == kEos ||
66  si.Value() == kEps || si.Value() == kDisambig)
67  continue;
68  genFst->AddArc(midId, fst::StdArc(si.Value(), si.Value(),
69  fst::StdArc::Weight::One(), midId));
70  }
71  return genFst;
72 }
fst::StdArc::StateId StateId
fst::StdArc StdArc
fst::StdVectorFst StdVectorFst

◆ CsvResult()

static void kaldi::CsvResult ( std::string  test,
int  dim,
BaseFloat  measure,
std::string  units 
)
static

Definition at line 34 of file matrix-lib-speed-test.cc.

34  {
35  std::cout << test << "," << (sizeof(Real) == 8 ? "double" : "float") << "," << dim << "," << measure << "," << units << "\n";
36 }

◆ CuBlockMatrixUnitTest()

void kaldi::CuBlockMatrixUnitTest ( )

Definition at line 173 of file cu-block-matrix-test.cc.

173  {
174  UnitTestCuBlockMatrixIO<Real>();
175  UnitTestCuBlockMatrixAddMatBlock<Real>();
176  UnitTestCuBlockMatrixAddMatMat<Real>();
177 }

◆ CuCompressedMatrixTestNonnegative()

void kaldi::CuCompressedMatrixTestNonnegative ( )

Definition at line 54 of file cu-compressed-matrix-test.cc.

References CuMatrixBase< Real >::Add(), CuMatrixBase< Real >::AddMat(), CuCompressedMatrixBase::CopyFromMat(), CuCompressedMatrixBase::CopyToMat(), KALDI_ASSERT, kCompressedMatrixUint16, kCompressedMatrixUint8, kUndefined, CuMatrixBase< Real >::Max(), CuMatrixBase< Real >::Min(), NewCuCompressedMatrix(), RandInt(), CuMatrixBase< Real >::Scale(), and CuMatrixBase< Real >::SetRandUniform().

Referenced by main().

54  {
55  int32 num_rows = RandInt(80, 100),
56  num_cols = RandInt(80, 100);
57  CuMatrix<BaseFloat> M(num_rows, num_cols);
58  M.SetRandUniform();
59 
60  BaseFloat range = 0.5 * RandInt(1, 5);
61  M.Scale(range);
62 
63  CuCompressedMatrixType t = (RandInt(0, 1) == 0 ?
66 
67  // since the input is in the correct range, truncating or not should make no
68  // difference.
69  bool truncate = (RandInt(0, 1) == 0);
70 
71  BaseFloat extra_error = 0.0;
72  if (truncate && (RandInt(0, 1) == 0)) {
73  // this tests that with truncate == true, adding a small offset, which would
74  // take us outside the representable range, will not add too much extra
75  // error. (with truncate == false this would not be true because we wouldn't
76  // round to the edges of the range, it would wrap around).
77  extra_error = -0.01 * (RandInt(0, 1) == 0 ? 1.0 : -1.0);
78  M.Add(extra_error);
79  }
80 
81  CuCompressedMatrixBase *cm = NewCuCompressedMatrix(t, range, truncate);
82 
83  CuMatrix<BaseFloat> M2(num_rows, num_cols, kUndefined);
84 
85  cm->CopyFromMat(M);
86  cm->CopyToMat(&M2);
87 
88 
89  M2.AddMat(-1.0, M);
90 
91  BaseFloat diff_max = M2.Max(),
92  diff_min = M2.Min();
93 
94  BaseFloat
95  headroom = 1.1,
96  max_expected_error = fabs(extra_error) + headroom * 0.5 *
97  range / (t == kCompressedMatrixUint8 ? 255 : 65535);
98 
99  KALDI_ASSERT(diff_max < max_expected_error &&
100  diff_min > -1.0 * max_expected_error);
101 
102  delete cm;
103 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
virtual void CopyFromMat(const CuMatrixBase< BaseFloat > &mat)=0
Sets *this to an appropriately compressed copy of &#39;mat&#39;, which includes resizing *this.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Class CuCompressedMatrixBase is an abstract base class that allows you to compress a matrix of type C...
CuCompressedMatrixBase * NewCuCompressedMatrix(CuCompressedMatrixType t, BaseFloat range, bool truncat)
This function allocates a new CuCompressedMatrix with type determined by t, and with the &#39;range&#39; and ...
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95
virtual void CopyToMat(CuMatrixBase< BaseFloat > *mat) const =0
Copies the contents of *this to &#39;mat&#39;, which should be correctly sized beforehand.

◆ CuCompressedMatrixTestSign()

void kaldi::CuCompressedMatrixTestSign ( )

Definition at line 34 of file cu-compressed-matrix-test.cc.

References AssertEqual(), CuCompressedMatrixBase::CopyFromMat(), CuCompressedMatrixBase::CopyToMat(), CuMatrixBase< Real >::Heaviside(), kCompressedMatrixUint8, kUndefined, NewCuCompressedMatrix(), RandInt(), and CuMatrixBase< Real >::SetRandn().

Referenced by main().

34  {
35  int32 num_rows = RandInt(80, 100),
36  num_cols = RandInt(80, 100);
37  CuMatrix<BaseFloat> M(num_rows, num_cols);
38  M.SetRandn();
39 
40  CuMatrix<BaseFloat> M2(num_rows, num_cols, kUndefined);
41 
43 
44  // this just stores (M(i, j) > 0 ? 1 : 0).
45  cm->CopyFromMat(M);
46  cm->CopyToMat(&M2);
47 
48  M.Heaviside(M);
49 
50  AssertEqual(M, M2);
51  delete cm;
52 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
virtual void CopyFromMat(const CuMatrixBase< BaseFloat > &mat)=0
Sets *this to an appropriately compressed copy of &#39;mat&#39;, which includes resizing *this.
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Class CuCompressedMatrixBase is an abstract base class that allows you to compress a matrix of type C...
CuCompressedMatrixBase * NewCuCompressedMatrix(CuCompressedMatrixType t, BaseFloat range, bool truncat)
This function allocates a new CuCompressedMatrix with type determined by t, and with the &#39;range&#39; and ...
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95
virtual void CopyToMat(CuMatrixBase< BaseFloat > *mat) const =0
Copies the contents of *this to &#39;mat&#39;, which should be correctly sized beforehand.

◆ CuCompressedMatrixTestSymmetric()

void kaldi::CuCompressedMatrixTestSymmetric ( )

Definition at line 107 of file cu-compressed-matrix-test.cc.

References CuMatrixBase< Real >::Add(), CuMatrixBase< Real >::AddMat(), CuCompressedMatrixBase::CopyFromMat(), CuCompressedMatrixBase::CopyToMat(), KALDI_ASSERT, kCompressedMatrixInt16, kCompressedMatrixInt8, kUndefined, CuMatrixBase< Real >::Max(), CuMatrixBase< Real >::Min(), NewCuCompressedMatrix(), RandInt(), CuMatrixBase< Real >::Scale(), and CuMatrixBase< Real >::SetRandUniform().

Referenced by main().

107  {
108  int32 num_rows = RandInt(80, 100),
109  num_cols = RandInt(80, 100);
110  CuMatrix<BaseFloat> M(num_rows, num_cols);
111  M.SetRandUniform();
112  M.Scale(2.0);
113  M.Add(-1.0);
114 
115  BaseFloat range = 0.5 * RandInt(1, 5);
116  M.Scale(range);
117 
118  CuCompressedMatrixType t = (RandInt(0, 1) == 0 ?
121 
122  // since the input is in the correct range, truncating or not should make no
123  // difference.
124  bool truncate = (RandInt(0, 1) == 0);
125 
126  BaseFloat extra_error = 0.0;
127  if (truncate && (RandInt(0, 1) == 0)) {
128  // this tests that with truncate == true, adding a small offset, which would
129  // take us outside the representable range, will not add too much extra
130  // error. (with truncate == false this would not be true because we wouldn't
131  // round to the edges of the range, it would wrap around).
132  extra_error = -0.01 * (RandInt(0, 1) == 0 ? 1.0 : -1.0);
133  M.Add(extra_error);
134  }
135 
136  CuCompressedMatrixBase *cm = NewCuCompressedMatrix(t, range, truncate);
137 
138  CuMatrix<BaseFloat> M2(num_rows, num_cols, kUndefined);
139 
140  cm->CopyFromMat(M);
141  cm->CopyToMat(&M2);
142 
143 
144  M2.AddMat(-1.0, M);
145 
146  BaseFloat diff_max = M2.Max(),
147  diff_min = M2.Min();
148 
149  BaseFloat
150  headroom = 1.1,
151  max_expected_error = fabs(extra_error) + headroom * 0.5 *
152  range / (t == kCompressedMatrixInt8 ? 127 : 32767);
153 
154  KALDI_ASSERT(diff_max < max_expected_error &&
155  diff_min > -1.0 * max_expected_error);
156 
157  delete cm;
158 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
virtual void CopyFromMat(const CuMatrixBase< BaseFloat > &mat)=0
Sets *this to an appropriately compressed copy of &#39;mat&#39;, which includes resizing *this.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Class CuCompressedMatrixBase is an abstract base class that allows you to compress a matrix of type C...
CuCompressedMatrixBase * NewCuCompressedMatrix(CuCompressedMatrixType t, BaseFloat range, bool truncat)
This function allocates a new CuCompressedMatrix with type determined by t, and with the &#39;range&#39; and ...
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95
virtual void CopyToMat(CuMatrixBase< BaseFloat > *mat) const =0
Copies the contents of *this to &#39;mat&#39;, which should be correctly sized beforehand.

◆ CudaMathUnitTest()

void kaldi::CudaMathUnitTest ( )

Definition at line 694 of file cu-math-test.cc.

References UnitTestLstmNonlinearity().

694  {
695 #if HAVE_CUDA == 1
696  if (CuDevice::Instantiate().DoublePrecisionSupported())
697 #endif
698 
699  UnitTestCuMathComputeLstmNonlinearity<Real>();
700  UnitTestCuMathRandomize<Real>();
701  UnitTestCuMathSplice<Real>();
702  UnitTestCuMathCopy<Real>();
704  UnitTestEnsureNonzero<Real>();
705  UnitTestBackpropLstmNonlinearity<Real>();
706  UnitTestCuMathNormalizePerRow<Real>();
707  UnitTestCuMathNormalizePerRow_v2<Real>();
708  UnitTestCuDiffNormalizePerRow<Real>();
709 }
void UnitTestLstmNonlinearity()

◆ CudaMatrixResizeTest()

void kaldi::CudaMatrixResizeTest ( )

Definition at line 81 of file cu-device-test.cc.

81  {
82  std::vector<int32> sizes;
83  sizes.push_back(1);
84  sizes.push_back(2);
85  sizes.push_back(4);
86  sizes.push_back(8);
87  sizes.push_back(16);
88  //sizes.push_back(24);
89  //sizes.push_back(32);
90  //sizes.push_back(40);
91 
92  int32 ns = sizes.size();
93  for (int32 s = 0; s < ns; s++)
94  TestCuMatrixResize<Real>(sizes[s]);
95 }
kaldi::int32 int32

◆ CudaMatrixSpeedTest()

void kaldi::CudaMatrixSpeedTest ( )

Definition at line 1012 of file cu-matrix-speed-test.cc.

References kNoTrans, and kTrans.

1012  {
1013  std::vector<int32> sizes;
1014  sizes.push_back(16);
1015  sizes.push_back(32);
1016  sizes.push_back(64);
1017  sizes.push_back(128);
1018  sizes.push_back(256);
1019  sizes.push_back(512);
1020  sizes.push_back(1024);
1021  int32 ns = sizes.size();
1022  for (int32 s = 0; s < ns; s++)
1023  TestCuMatrixDivRowsVec<Real>(sizes[s]);
1024  for (int32 s = 0; s < ns; s++)
1025  TestCuMatrixResize<Real>(sizes[s]);
1026  for (int32 s = 0; s < ns; s++)
1027  TestCuMatrixAddMat<Real>(sizes[s], 3, 3);
1028  for (int32 s = 0; s < ns; s++)
1029  TestCuMatrixAddMatBlocks<Real>(sizes[s], 3, 3);
1030  for (int32 s = 0; s < ns; s++)
1031  TestCuMatrixMatMat<Real>(sizes[s]);
1032  for (int32 s = 0; s + 1 < ns; s++)
1033  TestCuMatrixMatMatBatched<Real>(sizes[s], 10);
1034  for (int32 s = 0; s < ns; s++) {
1035  TestCuMatrixAddDiagVecMat<Real>(sizes[s], kNoTrans);
1036  TestCuMatrixAddDiagVecMat<Real>(sizes[s], kTrans);
1037  }
1038  for (int32 s = 0; s < ns; s++)
1039  TestSymInvertPosDef<Real>(sizes[s]);
1040  for (int32 s = 0; s < ns; s++)
1041  TestCuMatrixCholesky<Real>(sizes[s]);
1042  for (int32 s = 0; s < ns; s++)
1043  TestCuMatrixSigmoid<Real>(sizes[s]);
1044  for (int32 s = 0; s < ns; s++)
1045  TestCuMatrixHeaviside<Real>(sizes[s]);
1046  for (int32 s = 0; s < ns; s++)
1047  TestCuFindRowMaxId<Real>(sizes[s]);
1048  for (int32 s = 0; s < ns; s++)
1049  TestCuMatrixCompObjfAndDeriv<Real>(sizes[s]);
1050  for (int32 s = 0; s < ns; s++)
1051  TestCuMatrixMulRowsGroupMat<Real>(sizes[s]);
1052  for (int32 s = 0; s < ns; s++)
1053  TestCuMatrixSoftmax<Real>(sizes[s]);
1054  for (int32 s = 0; s < ns; s++)
1055  TestCuMatrixDiffSoftmax<Real>(sizes[s]);
1056  for (int32 s = 0; s < ns; s++)
1057  TestCuMatrixDiffLogSoftmax<Real>(sizes[s]);
1058  for (int32 s = 0; s < ns; s++)
1059  TestCuMatrixLogSoftmax<Real>(sizes[s]);
1060  for (int32 s = 0; s < ns; s++)
1061  TestCuMatrixGroupPnorm<Real>(sizes[s]);
1062  for (int32 s = 0; s < ns; s++)
1063  TestCuMatrixDiffGroupPnorm<Real>(sizes[s]);
1064  for (int32 s = 0; s < ns; s++)
1065  TestCuMatrixGroupMax<Real>(sizes[s]);
1066  for (int32 s = 0; s < ns; s++)
1067  TestCuMatrixGroupMaxAllGroupSizes<Real>(sizes[s]);
1068  for (int32 s = 0; s < ns; s++)
1069  TestCuMatrixGroupMaxDeriv<Real>(sizes[s]);
1070  for (int32 s = 0; s < ns; s++)
1071  TestCuMatrixTraceMatMat<Real>(sizes[s]);
1072  for (int32 s = 0; s < ns; s++)
1073  TestCuSparseMatrixTraceMatSmat<Real>(sizes[s]);
1074  for (int32 s = 0; s < ns; s++)
1075  TestCuMatrixCopyLowerToUpper<Real>(sizes[s]);
1076  for (int32 s = 0; s < ns; s++)
1077  TestCuMatrixCopyFromTp<Real>(sizes[s], kNoTrans);
1078  for (int32 s = 0; s < ns; s++)
1079  TestCuMatrixCopyFromTp<Real>(sizes[s], kTrans);
1080  for (int32 s = 0; s < ns; s++)
1081  TestCuMatrixCopyFromSp<Real>(sizes[s]);
1082  for (int32 s = 0; s < ns; s++)
1083  TestCuMatrixCopyUpperToLower<Real>(sizes[s]);
1084  for (int32 s = 0; s < ns; s++)
1085  TestCuMatrixSetZeroAboveDiag<Real>(sizes[s]);
1086  for (int32 s = 0; s + 2 < ns; s++)
1087  TestCuMatrixLookup<Real>(sizes[s]);
1088  for (int32 s = 0; s < ns; s++)
1089  TestCuMatrixCopyRows1<Real>(sizes[s]);
1090  for (int32 s = 0; s < ns; s++)
1091  TestCuMatrixCopyRows2<Real>(sizes[s]);
1092  for (int32 s = 0; s < ns; s++)
1093  TestCuMatrixCopyToRows<Real>(sizes[s]);
1094  for (int32 s = 0; s < ns; s++)
1095  TestCuMatrixAddRows1<Real>(sizes[s]);
1096  for (int32 s = 0; s < ns; s++)
1097  TestCuMatrixAddRows2<Real>(sizes[s]);
1098  for (int32 s = 0; s < ns; s++)
1099  TestCuMatrixAddToRows<Real>(sizes[s]);
1100  for (int32 s = 0; s < ns; s++)
1101  TestCuMatrixAddRowRanges<Real>(sizes[s]);
1102  for (int32 s = 0; s < ns; s++)
1103  TestCuMatrixTransposeCross<Real>(sizes[s]);
1104  for (int32 s = 0; s < ns; s++)
1105  TestCuMatrixTransposeS<Real>(sizes[s]);
1106  for (int32 s = 0; s < ns; s++)
1107  TestCuMatrixTransposeNS<Real>(sizes[s]);
1108  for (int32 s = 0; s < ns; s++)
1109  TestCuMatrixSum<Real>(sizes[s]);
1110  for (int32 s = 0; s < ns; s++)
1111  TestCuMatrixMax<Real>(sizes[s]);
1112  for (int32 s = 0; s < ns; s++)
1113  TestCuMatrixMin<Real>(sizes[s]);
1114 }
kaldi::int32 int32

◆ CudaMatrixUnitTest()

void kaldi::CudaMatrixUnitTest ( )

Definition at line 2941 of file cu-matrix-test.cc.

2941  {
2942  UnitTestCuMatrixApplyExpSpecial<Real>();
2943  UnitTestCuMatrixApplyExpLimited<Real>();
2944  UnitTextCuMatrixAddSmatMat<Real>();
2945  UnitTextCuMatrixAddMatSmat<Real>();
2946  UnitTextCuMatrixAddSmat<Real>();
2947  UnitTestCuMatrixTraceMatMat<Real>();
2948  UnitTestCuMatrixObjfDeriv<Real>();
2949  //test CuMatrix<Real> methods by cross-check with Matrix
2950  UnitTestCuMatrixCopyCross<Real>();
2951  UnitTestCuMatrixCopyCross2<Real>();
2952  UnitTestCuMatrixApplyLog<Real>();
2953  UnitTestCuMatrixApplyExp<Real>();
2954  UnitTestCuMatrixSetRandn<Real>();
2955  UnitTestCuMatrixSetRandUniform<Real>();
2956  UnitTestCuMatrixScale<Real>();
2957  UnitTestCuMatrixSigmoid<Real>();
2958  UnitTestCuMatrixSoftHinge<Real>();
2959  UnitTestCuMatrixApplyPow<Real>();
2960  UnitTestCuMatrixApplyPowAbs<Real>();
2961  UnitTestCuMatrixSet<Real>();
2962  UnitTestCuMatrixAdd<Real>();
2963  UnitTestCuMatrixApplyFloor<Real>();
2964  UnitTestCuMatrixApplyCeiling<Real>();
2965  UnitTestCuMatrixApplyHeaviside<Real>();
2966  UnitTestCuMatrixHeaviside<Real>();
2967  UnitTestCuMatrixMulElements<Real>();
2968  UnitTestCuMatrixDivElements<Real>();
2969  UnitTestCuMatrixMax<Real>();
2970  UnitTestCuMatrixMin<Real>();
2971  UnitTestCuMatrixMulColsVec<Real>();
2972  UnitTestCuMatrixMulRowsVec<Real>();
2973  UnitTestCuMatrixDivRowsVec<Real>();
2974  UnitTestCuMatrixAddMat<Real>();
2975  UnitTestCuMatrixAddMatBlocks1<Real>();
2976  UnitTestCuMatrixAddMatBlocks1Trans<Real>();
2977  UnitTestCuMatrixAddMatBlocks2<Real>();
2978  UnitTestCuMatrixReduceSum<Real>();
2979  UnitTestCuMatrixReduceMax<Real>();
2980  UnitTestCuMatrixReduceMin<Real>();
2981  UnitTestCuMatrixAddVecToCols<Real>();
2982  UnitTestCuMatrixAddVecToRows<Real>();
2983  UnitTestCuMatrixAddMatMat<Real>();
2984  UnitTestCuMatrixAddVecVec<Real>();
2985  UnitTestCuMatrixSymAddMat2<Real>();
2986  UnitTestCuMatrixAddMatMatBatched<Real>();
2987  UnitTestCuMatrixSymInvertPosDef<Real>();
2988  UnitTestCuMatrixCopyFromMat<Real>();
2989  UnitTestCuMatrixCopyFromTp<Real>();
2990  UnitTestCuMatrixAddMatTp<Real>();
2991  UnitTestCuMatrixCopyCols<Real>();
2992  UnitTestCuMatrixAddCols<Real>();
2993  UnitTestCuMatrixSumColumnRanges<Real>();
2994  UnitTestCuMatrixCopyRows<Real>();
2995  UnitTestCuMatrixCopyRowsFromVec<Real>();
2996  UnitTestCuMatrixCopyColsFromVec<Real>();
2997  UnitTestCuMatrixCopyToRows<Real>();
2998  UnitTestCuMatrixAddRows<Real>();
2999  UnitTestCuMatrixMulRows<Real>();
3000  UnitTestCuMatrixAddToRows<Real>();
3001  UnitTestCuMatrixAddRowRanges<Real>();
3002  UnitTestCuMatrixAddTpMat<Real>();
3003  UnitTestCuMatrixTranspose<Real>();
3004  UnitTestCuMatrixCopyUpperToLower<Real>();
3005  UnitTestCuMatrixCopyLowerToUpper<Real>();
3006  UnitTestCuMatrixSetZeroAboveDiag<Real>();
3007  UnitTestCuMatrixAddElements<Real>();
3008  UnitTestCuMatrixAddToElements<Real>();
3009  UnitTestCuMatrixLookup<Real>();
3010  UnitTestCuMatrixEqualElementMask<Real>();
3011  // test CuVector<Real> methods
3012  UnitTestCuVectorAddVec<Real>();
3013  UnitTestCuVectorAddRowSumMat<Real>();
3014  UnitTestCuVectorAddRowSumMatLarge<Real>();
3015  UnitTestCuVectorAddColSumMat<Real>();
3016  UnitTestCuVectorAddColSumMatLarge<Real>();
3017  UnitTestCuSubMatrix<Real>();
3018  UnitTestCuMatrixInvertElements<Real>();
3019  UnitTestCuVectorInvertElements<Real>();
3020  UnitTestCuMatrixIO<Real>();
3021  UnitTestCuSigmoid<Real>();
3022  UnitTestCuApproxEqual<Real>();
3023  UnitTestCuCopy<Real, float>();
3024 #if HAVE_CUDA == 1
3025  if (CuDevice::Instantiate().DoublePrecisionSupported())
3026 #endif
3027  UnitTestCuCopy<Real, double>();
3028  UnitTestCuMatrixAddToDiag<Real>();
3029  UnitTestCuMatrixAdd2<Real>();
3030  UnitTestCuDiffSigmoid<Real>();
3031  UnitTestCuDiffSoftmax<Real>();
3032  UnitTestCuDiffLogSoftmax<Real>();
3033  UnitTestCuMatrixGroupPnorm<Real>();
3034  UnitTestCuMatrixDiffGroupPnorm<Real>();
3035  UnitTestCuMatrixGroupMax<Real>();
3036  UnitTestCuMatrixGroupMaxDeriv<Real>();
3037  UnitTestCuMatrixMulRowsVec<Real>();
3038  UnitTestCuMatrixMulRowsGroupMat<Real>();
3039  UnitTestCuFindRowMaxId<Real>();
3040  UnitTestCuSoftmax<Real>();
3041  UnitTestCuLogSoftmax<Real>();
3042  UnitTestCuDiffXent<Real>();
3043  UnitTestCheck<Real>();
3044  UnitTestSwapCu2Cu<Real>();
3045  UnitTestSwapCu2M<Real>();
3046  UnitTestCuMatrixAddDiagVecMat<Real>();
3047  UnitTestCuMatrixAddMatDiagVec<Real>();
3048  UnitTestCuMatrixAddMatMatElements<Real>();
3049  UnitTestCuMatrixSetMatMatDivMat<Real>();
3050  UnitTestCuTanh<Real>();
3051  UnitTestCuCholesky<Real>();
3052  UnitTestCuDiffTanh<Real>();
3053  UnitTestCuVectorAddTpVec<Real>();
3054  UnitTestCuVectorMulTp<Real>();
3055 }

◆ CudaPackedMatrixUnitTest()

void kaldi::CudaPackedMatrixUnitTest ( )

Definition at line 231 of file cu-packed-matrix-test.cc.

231  {
232  UnitTestCuPackedMatrixConstructor<Real>();
233  //UnitTestCuPackedMatrixCopy<Real>();
234  UnitTestCuPackedMatrixTrace<Real>();
235  UnitTestCuPackedMatrixScale<Real>();
236  UnitTestCuPackedMatrixAddToDiag<Real>();
237  UnitTestCuPackedMatrixSetUnit<Real>();
238 }

◆ CudaSparseMatrixUnitTest()

void kaldi::CudaSparseMatrixUnitTest ( )

Definition at line 271 of file cu-sparse-matrix-test.cc.

271  {
272  UnitTestCuSparseMatrixConstructFromIndexes<Real>();
273  UnitTestCuSparseMatrixSelectRowsAndTranspose<Real>();
274  UnitTestCuSparseMatrixTraceMatSmat<Real>();
275  UnitTestCuSparseMatrixSum<Real>();
276  UnitTestCuSparseMatrixFrobeniusNorm<Real>();
277  UnitTestCuSparseMatrixCopyToSmat<Real>();
278  UnitTestCuSparseMatrixSwap<Real>();
279 }

◆ CudaSpMatrixUnitTest() [1/2]

void kaldi::CudaSpMatrixUnitTest ( )

Definition at line 342 of file cu-sp-matrix-test.cc.

342  {
343  UnitTestCuSpMatrixIO<Real>();
344  UnitTestCuSpMatrixConstructor<Real>();
345  UnitTestCuSpMatrixOperator<Real>();
346  UnitTestCuSpMatrixApproxEqual<Real>();
347  UnitTestCuSpMatrixInvert<Real>();
348  UnitTestCuSpMatrixCopyFromMat<Real>();
349  UnitTestCuSpMatrixAddVec2<Real>();
350  UnitTestCuSpMatrixAddMat2<Real>();
351  UnitTestCuSpMatrixAddSp<Real>();
352  UnitTestCuSpMatrixAddToDiag<Real>();
353  UnitTestCuSpMatrixSetUnit<Real>();
354 }

◆ CudaSpMatrixUnitTest() [2/2]

void kaldi::CudaSpMatrixUnitTest ( )

Definition at line 356 of file cu-sp-matrix-test.cc.

356  {
357  UnitTestCuSpMatrixTraceSpSp<Real, OtherReal>();
358 
359 }

◆ CudaTpMatrixUnitTest()

void kaldi::CudaTpMatrixUnitTest ( )

Definition at line 176 of file cu-tp-matrix-test.cc.

176  {
177  UnitTestCuTpMatrixIO<Real>();
178  UnitTestCuTpMatrixInvert<Real>();
179  UnitTestCuTpMatrixCopyFromTp<Real>();
180  UnitTestCuTpMatrixCholesky<Real>();
181  UnitTestCuTpMatrixCopyFromMat<Real>();
182 }

◆ CudaVectorSpeedTest()

void kaldi::CudaVectorSpeedTest ( )

Definition at line 402 of file cu-vector-speed-test.cc.

References rnnlm::i, rnnlm::j, kNoTrans, and kTrans.

402  {
403  const size_t a = 1 << 5;
404  const size_t b = 1 << 8;
405  for (size_t i = a; i <= b; i *= 2) {
406  for (size_t j = a; j <= b; j *= 2) {
407  if (i * j <= a * b) {
408  TestCuVectorAddDiagMatMatShape<Real>(i, j, kNoTrans, kNoTrans);
409  TestCuVectorAddDiagMatMatShape<Real>(i, j, kNoTrans, kTrans);
410  TestCuVectorAddDiagMatMatShape<Real>(i, j, kTrans, kNoTrans);
411  TestCuVectorAddDiagMatMatShape<Real>(i, j, kTrans, kTrans);
412  }
413  }
414  }
415 
416  std::vector<int32> sizes;
417  for (int i = 32; i <= 1024; i *= 2) {
418  sizes.push_back(i);
419  }
420  int32 ns = sizes.size();
421  for (int32 s = 0; s < ns; s++)
422  TestCuVectorSoftmax<Real>(sizes[s]);
423 #if HAVE_CUDA == 1
424  TestCuVectorSumChooseMinLength<Real>();
425 #endif
426  for (int32 s = 0; s < ns; s++)
427  TestCuVectorSum<Real>(sizes[s]);
428  for (int32 s = 0; s < ns; s++)
429  TestCuVectorVecVecOne<Real>(sizes[s]);
430  for (int32 s = 0; s < ns; s++)
431  TestCuVectorCopyFromVec<Real, float>(sizes[s]);
432  for (int32 s = 0; s < ns; s++)
433  TestCuVectorCopyFromVec<Real, double>(sizes[s]);
434  for (int32 s = 0; s < ns; s++) {
435  TestCuVectorAddDiagMatMat<Real>(sizes[s], kNoTrans, kNoTrans);
436  TestCuVectorAddDiagMatMat<Real>(sizes[s], kNoTrans, kTrans);
437  TestCuVectorAddDiagMatMat<Real>(sizes[s], kTrans, kNoTrans);
438  TestCuVectorAddDiagMatMat<Real>(sizes[s], kTrans, kTrans);
439  }
440  for (int32 s = 0; s < ns; s++) {
441  TestCuVectorAddDiagMat2OnVariousShapes<Real>(sizes[s], kNoTrans);
442  TestCuVectorAddDiagMat2OnVariousShapes<Real>(sizes[s], kTrans);
443  }
444  for (int32 s = 0; s < ns; s++) {
445  TestCuVectorAddDiagMat2<Real>(sizes[s], kNoTrans);
446  TestCuVectorAddDiagMat2<Real>(sizes[s], kTrans);
447  }
448  for (int32 s = 0; s < ns; s++) {
449  TestCuVectorAddRowSumMat<Real>(sizes[s], kNoTrans);
450  TestCuVectorAddRowSumMat<Real>(sizes[s], kTrans);
451  }
452  for (int32 s = 0; s < ns; s++) {
453  TestCuVectorAddColSumMat<Real>(sizes[s], kNoTrans);
454  TestCuVectorAddColSumMat<Real>(sizes[s], kTrans);
455  }
456  for (int32 s = 0; s < ns; s++) {
457  TestCuVectorApplyFloor<Real>(sizes[s]);
458  TestCuVectorApplyFloorNoCount<Real>(sizes[s]);
459  }
460  for (int32 s = 0; s < ns; s++) {
461  TestCuVectorApplyCeiling<Real>(sizes[s]);
462  TestCuVectorApplyCeilingNoCount<Real>(sizes[s]);
463  }
464 
465 }
kaldi::int32 int32

◆ CuMatrixUnitTest()

static void kaldi::CuMatrixUnitTest ( )
static

Definition at line 561 of file cu-test.cc.

561  {
562  UnitTestTrace<Real>();
563  UnitTestCholesky<Real>();
564  UnitTestInvert<Real>();
565  UnitInvert<Real>();
566  UnitTestCopyFromMat<Real>();
567  UnitTestCopySp<Real>();
568  UnitTestConstructor<Real>();
569  UnitTestVector<Real>();
570  UnitTestMulTp<Real>();
571  UnitTestMatrix<Real>();
572  UnitTestSetZeroAboveDiag<Real>();
573 }

◆ CuRandGaussianMatrixBaseSpeedTest()

void kaldi::CuRandGaussianMatrixBaseSpeedTest ( const int32  iter)

Definition at line 129 of file cu-rand-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, kUndefined, MeanVariance(), CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), and CuRand< Real >::RandGaussian().

129  {
130  Timer t;
131  CuRand<Real> rand;
132  CuMatrix<Real> m(249,1001, kUndefined);
133  for (int32 i = 0; i < iter; i++) {
134  rand.RandGaussian(dynamic_cast<CuMatrixBase<Real>*>(&m));
135  }
136  CuMatrix<Real> m2(256,1024, kUndefined);
137  for (int32 i = 0; i < iter; i++) {
138  rand.RandGaussian(dynamic_cast<CuMatrixBase<Real>*>(&m2));
139  }
140  // flops = number of generated random numbers per second,
141  Real flops = iter * (m.NumRows() * m.NumCols() + m2.NumRows() * m2.NumCols()) / t.Elapsed();
142  KALDI_LOG << __func__ << NameOf<Real>()
143  << " Speed was " << flops << " rand_elems/s. "
144  << "(debug " << MeanVariance(m) << ")";
145 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
std::string MeanVariance(const CuVectorBase< Real > &v)
void RandGaussian(CuMatrixBase< Real > *tgt)
Fill with Normal random numbers,.
Definition: cu-rand.cc:116
Matrix for CUDA computing.
Definition: matrix-common.h:69
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ CuRandGaussianMatrixSpeedTest()

void kaldi::CuRandGaussianMatrixSpeedTest ( const int32  iter)

Definition at line 110 of file cu-rand-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, kUndefined, MeanVariance(), CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), and CuRand< Real >::RandGaussian().

110  {
111  Timer t;
112  CuRand<Real> rand;
113  CuMatrix<Real> m(249,1001, kUndefined);
114  for (int32 i = 0; i < iter; i++) {
115  rand.RandGaussian(&m);
116  }
117  CuMatrix<Real> m2(256,1024, kUndefined);
118  for (int32 i = 0; i < iter; i++) {
119  rand.RandGaussian(&m2);
120  }
121  // flops = number of generated random numbers per second,
122  Real flops = iter * (m.NumRows() * m.NumCols() + m2.NumRows() * m2.NumCols()) / t.Elapsed();
123  KALDI_LOG << __func__ << NameOf<Real>()
124  << " Speed was " << flops << " rand_elems/s. "
125  << "(debug " << MeanVariance(m) << ")";
126 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
std::string MeanVariance(const CuVectorBase< Real > &v)
void RandGaussian(CuMatrixBase< Real > *tgt)
Fill with Normal random numbers,.
Definition: cu-rand.cc:116
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ CuRandGaussianVectorSpeedTest()

void kaldi::CuRandGaussianVectorSpeedTest ( const int32  iter)

Definition at line 167 of file cu-rand-speed-test.cc.

References CuVectorBase< Real >::Dim(), Timer::Elapsed(), rnnlm::i, kUndefined, MeanVariance(), and CuRand< Real >::RandGaussian().

167  {
168  Timer t;
169  CuRand<Real> rand;
170  CuVector<Real> v(2011, kUndefined);
171  for (int32 i = 0; i < iter; i++) {
172  rand.RandGaussian(&v);
173  }
174  CuVector<Real> v2(2048, kUndefined);
175  for (int32 i = 0; i < iter; i++) {
176  rand.RandGaussian(&v2);
177  }
178  // flops = number of generated random numbers per second,
179  Real flops = iter * (v.Dim() + v2.Dim()) / t.Elapsed();
180  KALDI_LOG << __func__ << NameOf<Real>()
181  << " Speed was " << flops << " rand_elems/s. "
182  << "(debug " << MeanVariance(v) << ")";
183 }
kaldi::int32 int32
std::string MeanVariance(const CuVectorBase< Real > &v)
void RandGaussian(CuMatrixBase< Real > *tgt)
Fill with Normal random numbers,.
Definition: cu-rand.cc:116
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ CuRandUniformMatrixBaseSpeedTest()

void kaldi::CuRandUniformMatrixBaseSpeedTest ( const int32  iter)

Definition at line 91 of file cu-rand-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, kUndefined, MeanVariance(), CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), and CuRand< Real >::RandUniform().

91  {
92  Timer t;
93  CuRand<Real> rand;
94  CuMatrix<Real> m(249,1001, kUndefined);
95  for (int32 i = 0; i < iter; i++) {
96  rand.RandUniform(dynamic_cast<CuMatrixBase<Real>*>(&m));
97  }
98  CuMatrix<Real> m2(256,1024, kUndefined);
99  for (int32 i = 0; i < iter; i++) {
100  rand.RandUniform(dynamic_cast<CuMatrixBase<Real>*>(&m2));
101  }
102  // flops = number of generated random numbers per second,
103  Real flops = iter * (m.NumRows() * m.NumCols() + m2.NumRows() * m2.NumCols()) / t.Elapsed();
104  KALDI_LOG << __func__ << NameOf<Real>()
105  << " Speed was " << flops << " rand_elems/s. "
106  << "(debug " << MeanVariance(m) << ")";
107 }
void RandUniform(CuMatrixBase< Real > *tgt)
Fill with uniform [0..1] floats,.
Definition: cu-rand.cc:60
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
std::string MeanVariance(const CuVectorBase< Real > &v)
Matrix for CUDA computing.
Definition: matrix-common.h:69
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ CuRandUniformMatrixSpeedTest()

void kaldi::CuRandUniformMatrixSpeedTest ( const int32  iter)

Definition at line 72 of file cu-rand-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, kUndefined, MeanVariance(), CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), and CuRand< Real >::RandUniform().

72  {
73  Timer t;
74  CuRand<Real> rand;
75  CuMatrix<Real> m(249,1001, kUndefined);
76  for (int32 i = 0; i < iter; i++) {
77  rand.RandUniform(&m);
78  }
79  CuMatrix<Real> m2(256,1024, kUndefined);
80  for (int32 i = 0; i < iter; i++) {
81  rand.RandUniform(&m2);
82  }
83  // flops = number of generated random numbers per second,
84  Real flops = iter * (m.NumRows() * m.NumCols() + m2.NumRows() * m2.NumCols()) / t.Elapsed();
85  KALDI_LOG << __func__ << NameOf<Real>()
86  << " Speed was " << flops << " rand_elems/s. "
87  << "(debug " << MeanVariance(m) << ")";
88 }
void RandUniform(CuMatrixBase< Real > *tgt)
Fill with uniform [0..1] floats,.
Definition: cu-rand.cc:60
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
std::string MeanVariance(const CuVectorBase< Real > &v)
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ CuRandUniformVectorSpeedTest()

void kaldi::CuRandUniformVectorSpeedTest ( const int32  iter)

Definition at line 148 of file cu-rand-speed-test.cc.

References CuVectorBase< Real >::Dim(), Timer::Elapsed(), rnnlm::i, kUndefined, MeanVariance(), and CuRand< Real >::RandUniform().

148  {
149  Timer t;
150  CuRand<Real> rand;
151  CuVector<Real> v(2011, kUndefined);
152  for (int32 i = 0; i < iter; i++) {
153  rand.RandUniform(&v);
154  }
155  CuVector<Real> v2(2048, kUndefined);
156  for (int32 i = 0; i < iter; i++) {
157  rand.RandUniform(&v2);
158  }
159  // flops = number of generated random numbers per second,
160  Real flops = iter * (v.Dim() + v2.Dim()) / t.Elapsed();
161  KALDI_LOG << __func__ << NameOf<Real>()
162  << " Speed was " << flops << " rand_elems/s. "
163  << "(debug " << MeanVariance(v) << ")";
164 }
void RandUniform(CuMatrixBase< Real > *tgt)
Fill with uniform [0..1] floats,.
Definition: cu-rand.cc:60
kaldi::int32 int32
std::string MeanVariance(const CuVectorBase< Real > &v)
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ CuSpMatrixSpeedTest()

void kaldi::CuSpMatrixSpeedTest ( )

Definition at line 107 of file cu-sp-matrix-speed-test.cc.

References kTakeLower, kTakeMean, and kTakeUpper.

107  {
108  std::vector<int32> sizes;
109  sizes.push_back(16);
110  sizes.push_back(32);
111  sizes.push_back(64);
112  sizes.push_back(128);
113  sizes.push_back(256);
114  sizes.push_back(512);
115  sizes.push_back(1024);
116  int32 ns = sizes.size();
117 
118  for (int32 s = 0; s < ns; s++) {
119  UnitTestCuSpMatrixInvert<Real>(sizes[s]);
120  UnitTestCuSpMatrixCopyFromMat<Real>(sizes[s], kTakeLower);
121  UnitTestCuSpMatrixCopyFromMat<Real>(sizes[s], kTakeUpper);
122  UnitTestCuSpMatrixCopyFromMat<Real>(sizes[s], kTakeMean);
123  }
124 }
kaldi::int32 int32

◆ CuVectorUnitTest()

void kaldi::CuVectorUnitTest ( )

Definition at line 780 of file cu-vector-test.cc.

780  {
781  UnitTestCuVectorCopyFromVec<Real, float>();
782 #if HAVE_CUDA == 1
783  if (CuDevice::Instantiate().DoublePrecisionSupported())
784 #endif
785  UnitTestCuVectorCopyFromVec<Real, double>();
786  UnitTestCuVectorIO<Real>();
787  CuVectorUnitTestVecVec<Real>();
788  CuVectorUnitTestAddVec<Real>();
789  CuVectorUnitTestAddVecCross<Real>();
790  CuVectorUnitTestAddVecExtra<Real>();
791  CuVectorUnitTestApproxEqual<Real>();
792  CuVectorUnitTestScale<Real>();
793  CuVectorUnitTestSum<Real>();
794  CuVectorUnitTestInvertElements<Real>();
795  UnitTestCuVectorSum<Real>();
796  CuVectorUnitTestAddRowSumMat<Real>();
797  CuVectorUnitTestAddColSumMat<Real>();
798  UnitTestCuVectorReplaceValue<Real>();
799  UnitTestCuVectorAddTp<Real>();
800  UnitTestCuVectorMulTp<Real>();
801  UnitTestCuSubVector<Real>();
802  CuVectorUnitTestCopyFromMat<Real>();
803  CuVectorUnitTestMin<Real>();
804  CuVectorUnitTestMax<Real>();
805  CuVectorUnitTestApplySoftMax<Real>();
806  CuVectorUnitTestCopyDiagFromPacked<Real>();
807  CuVectorUnitTestCopyDiagFromMat<Real>();
808  CuVectorUnitTestCopyCross<Real>();
809  CuVectorUnitTestCopyCross2<Real>();
810  CuVectorUnitTestNorm<Real>();
811  CuVectorUnitTestApplyExp<Real>();
812  CuVectorUnitTestApplyLog<Real>();
813  CuVectorUnitTestApplyFloor<Real>();
814  CuVectorUnitTestApplyFloorNoCount<Real>();
815  CuVectorUnitTestApplyCeilingNoCount<Real>();
816  CuVectorUnitTestApplyCeiling<Real>();
817  CuVectorUnitTestApplyPow<Real>();
818  CuVectorUnitTestAddMatVec<Real>();
819  CuVectorUnitTestAddSpVec<Real>();
820  CuVectorUnitTestAddVecVec<Real>();
821  CuVectorUnitTestAddDiagMat2<Real>();
822  CuVectorUnitTestAddDiagMatMat<Real>();
823  CuVectorUnitTestCopyElements<Real>();
824  UnitTestVecMatVec<Real>();
825 }

◆ CuVectorUnitTestAddColSumMat()

void kaldi::CuVectorUnitTestAddColSumMat ( )

Definition at line 264 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddColSumMat(), VectorBase< Real >::AddColSumMat(), AssertEqual(), Rand(), and CuMatrixBase< Real >::SetRandn().

264  {
265  int32 M = 10 + Rand() % 280, N = 10 + Rand() % 20;
266  BaseFloat alpha = 10.0143432, beta = 43.4321;
267  CuMatrix<Real> mat(M, N);
268  mat.SetRandn();
269  CuVector<Real> vec(M);
270  mat.SetRandn();
271  Matrix<Real> mat2(mat);
272  Vector<Real> vec2(M);
273  vec.AddColSumMat(alpha, mat, beta);
274  vec2.AddColSumMat(alpha, mat2, beta);
275  Vector<Real> vec3(vec);
276  AssertEqual(vec2, vec3);
277 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddDiagMat2()

void kaldi::CuVectorUnitTestAddDiagMat2 ( )

Definition at line 668 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddDiagMat2(), VectorBase< Real >::AddDiagMat2(), AssertEqual(), kNoTrans, kTrans, Rand(), CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

668  {
669  for (int p = 0; p < 4; p++) {
670  int32 M = 230 + Rand() % 100, N = 230 + Rand() % 100;
671  BaseFloat alpha = 0.2 + Rand() % 3, beta = 0.3 + Rand() % 2;
672  CuVector<Real> cu_vector(M);
673  cu_vector.SetRandn();
674 
675  CuMatrix<Real> cu_mat_orig(M, N);
676  cu_mat_orig.SetRandn();
677  MatrixTransposeType trans = (p % 2 == 0 ? kNoTrans : kTrans);
678  CuMatrix<Real> cu_mat(cu_mat_orig, trans);
679 
680  Vector<Real> vector(cu_vector);
681  Matrix<Real> mat(cu_mat);
682 
683  vector.AddDiagMat2(alpha, mat, trans, beta);
684  cu_vector.AddDiagMat2(alpha, cu_mat, trans, beta);
685 
686  Vector<Real> vector2(cu_vector);
687  AssertEqual(vector, vector2);
688  }
689 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddDiagMatMat()

static void kaldi::CuVectorUnitTestAddDiagMatMat ( )
static

Definition at line 692 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddDiagMatMat(), CuMatrixBase< Real >::AddMatMat(), CuVectorBase< Real >::AddVec(), AssertEqual(), CuVectorBase< Real >::CopyDiagFromMat(), rnnlm::d, kNoTrans, kTrans, Rand(), CuVectorBase< Real >::Scale(), CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

692  {
693  for (MatrixIndexT iter = 0; iter < 4; iter++) {
694  BaseFloat alpha = 0.432 + Rand() % 5, beta = 0.043 + Rand() % 2;
695  MatrixIndexT dimM = 10 + Rand() % 300,
696  dimN = 5 + Rand() % 300;
697  CuVector<Real> v(dimM);
698  CuMatrix<Real> M_orig(dimM, dimN), N_orig(dimN, dimM);
699  M_orig.SetRandn();
700  N_orig.SetRandn();
701  MatrixTransposeType transM = (iter % 2 == 0 ? kNoTrans : kTrans);
702  MatrixTransposeType transN = ((iter/2) % 2 == 0 ? kNoTrans : kTrans);
703  CuMatrix<Real> M(M_orig, transM), N(N_orig, transN);
704 
705  v.SetRandn();
706  CuVector<Real> w(v);
707 
708  w.AddDiagMatMat(alpha, M, transM, N, transN, beta);
709 
710  {
711  CuVector<Real> w2(v);
712  CuMatrix<Real> MN(dimM, dimM);
713  MN.AddMatMat(1.0, M, transM, N, transN, 0.0);
714  CuVector<Real> d(dimM);
715  d.CopyDiagFromMat(MN);
716  w2.Scale(beta);
717  w2.AddVec(alpha, d);
718  AssertEqual(w, w2);
719  }
720  }
721 }
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddMatVec()

void kaldi::CuVectorUnitTestAddMatVec ( )

Definition at line 725 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddMatVec(), VectorBase< Real >::AddMatVec(), AssertEqual(), rnnlm::i, kNoTrans, kTrans, Rand(), CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

725  {
726  for (int32 i = 0; i < 10; i++) {
727  int32 M = 10 + Rand() % 500, N = 10 + Rand() % 400;
728 
729  bool transpose = (i % 2 == 0);
730 
731  CuVector<Real> src_cu(M);
732  src_cu.SetRandn();
733  Vector<Real> src(src_cu);
734 
735  CuVector<Real> dst_cu(N);
736  dst_cu.SetRandn();
737  Vector<Real> dst(dst_cu);
738 
739  CuMatrix<Real> mat_cu(transpose ? M : N, transpose ? N : M);
740  mat_cu.SetRandn();
741  Matrix<Real> mat(mat_cu);
742 
743  BaseFloat alpha = 0.5 * (Rand() % 10), beta = 0.5 * (Rand() % 10);
744  dst_cu.AddMatVec(alpha, mat_cu, transpose ? kTrans : kNoTrans,
745  src_cu, beta);
746  dst.AddMatVec(alpha, mat, transpose ? kTrans : kNoTrans,
747  src, beta);
748  Vector<Real> dst2(dst_cu);
749  AssertEqual(dst, dst2);
750  }
751 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddRowSumMat()

void kaldi::CuVectorUnitTestAddRowSumMat ( )

Definition at line 249 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddRowSumMat(), VectorBase< Real >::AddRowSumMat(), AssertEqual(), Rand(), and CuMatrixBase< Real >::SetRandn().

249  {
250  int32 M = 10 + Rand() % 280, N = 10 + Rand() % 20;
251  BaseFloat alpha = 10.0143432, beta = 43.4321;
252  CuMatrix<Real> mat(N, M);
253  mat.SetRandn();
254  CuVector<Real> vec(M);
255  mat.SetRandn();
256  Matrix<Real> mat2(mat);
257  Vector<Real> vec2(M);
258  vec.AddRowSumMat(alpha, mat, beta);
259  vec2.AddRowSumMat(alpha, mat2, beta);
260  Vector<Real> vec3(vec);
261  AssertEqual(vec2, vec3);
262 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddSpVec()

void kaldi::CuVectorUnitTestAddSpVec ( )

Definition at line 754 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddSpVec(), VectorBase< Real >::AddSpVec(), AssertEqual(), rnnlm::i, Rand(), CuPackedMatrix< Real >::SetRandn(), and CuVectorBase< Real >::SetRandn().

754  {
755  for (int32 i = 0; i < 5; i++) {
756  int32 M = 100 + Rand() % 256;
757 
758  CuVector<Real> src_cu(M);
759  src_cu.SetRandn();
760  Vector<Real> src(src_cu);
761 
762  CuVector<Real> dst_cu(M);
763  dst_cu.SetRandn();
764  Vector<Real> dst(dst_cu);
765 
766  CuSpMatrix<Real> mat_cu(M);
767  mat_cu.SetRandn();
768  SpMatrix<Real> mat(mat_cu);
769 
770  BaseFloat alpha = 0.5 * (Rand() % 5), beta = 0.5 * (Rand() % 5);
771  dst_cu.AddSpVec(alpha, mat_cu, src_cu, beta);
772  dst.AddSpVec(alpha, mat, src, beta);
773  Vector<Real> dst2(dst_cu);
774  AssertEqual(dst, dst2);
775  }
776 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddVec()

void kaldi::CuVectorUnitTestAddVec ( )

Definition at line 155 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddVec(), AssertEqual(), rnnlm::i, Rand(), and CuVectorBase< Real >::SetRandn().

155  {
156  int32 M = 10 + Rand() % 100;
157  CuVector<Real> vec1(M);
158  CuVector<Real> vec2(M);
159  vec1.SetRandn();
160  vec2.SetRandn();
161  CuVector<Real> vec1_orig(vec1);
162  BaseFloat alpha = 0.43243;
163  vec1.AddVec(alpha, vec2);
164 
165  for (int32 i = 0; i < M; i++)
166  AssertEqual(vec1_orig(i) + alpha * vec2(i), vec1(i));
167 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddVecCross()

void kaldi::CuVectorUnitTestAddVecCross ( )

Definition at line 169 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddVec(), AssertEqual(), rnnlm::i, Rand(), and CuVectorBase< Real >::SetRandn().

169  {
170  for (int32 i = 0; i < 4; i++) {
171  int32 M = 10 + Rand() % 100;
172  CuVector<float> vec1(M);
173  CuVector<Real> vec2(M);
174  vec1.SetRandn();
175  vec2.SetRandn();
176 
177  if (i == 0) {
178  CuVector<Real> vec1_orig(vec1);
179  Real alpha = 0.43243;
180  vec1.AddVec(alpha, vec2);
181 
182  for (int32 i = 0; i < M; i++)
183  AssertEqual(vec1_orig(i) + alpha * vec2(i), vec1(i));
184  } else {
185  CuVector<Real> vec2_orig(vec2);
186  Real alpha = 0.43243;
187  vec2.AddVec(alpha, vec1);
188  for (int32 i = 0; i < M; i++)
189  AssertEqual(vec2_orig(i) + alpha * vec1(i), vec2(i));
190  }
191  }
192 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddVecExtra()

void kaldi::CuVectorUnitTestAddVecExtra ( )

Definition at line 194 of file cu-vector-test.cc.

References AssertEqual(), rnnlm::i, Rand(), and CuVectorBase< Real >::SetRandn().

194  {
195  int32 M = 10 + Rand() % 100;
196  CuVector<Real> vec1(M), vec2(M);
197  vec1.SetRandn();
198  vec2.SetRandn();
199  CuVector<Real> vec1_orig(vec1);
200  BaseFloat alpha = 0.43243, beta = 1.4321;
201  vec1.AddVec(alpha, vec2, beta);
202 
203  for (int32 i = 0; i < M; i++)
204  AssertEqual(beta * vec1_orig(i) + alpha * vec2(i), vec1(i));
205 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestAddVecVec()

void kaldi::CuVectorUnitTestAddVecVec ( )

Definition at line 647 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddVecVec(), VectorBase< Real >::AddVecVec(), AssertEqual(), Rand(), VectorBase< Real >::SetRandn(), and CuVectorBase< Real >::SetRandn().

647  {
648  int32 dim = 100;
649  CuVector<Real> cu_vector(dim);
650  cu_vector.SetRandn();
651  Vector<Real> vector(cu_vector);
652 
653  Real beta = Rand();
654  Real alpha = Rand();
655  Vector<Real> v(dim), r(dim);
656  v.SetRandn(); r.SetRandn();
657  CuVector<Real> cuV(v), cuR(r);
658 
659 
660  cu_vector.AddVecVec(alpha, cuR, cuV, beta);
661  vector.AddVecVec(alpha, r, v, beta);
662 
663  CuVector<Real> cu2(vector);
664  std::cout<<cu2(0)<<' '<<cu_vector(0)<<std::endl;
665  AssertEqual(cu2, cu_vector);
666 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestApplyCeiling()

void kaldi::CuVectorUnitTestApplyCeiling ( )

Definition at line 591 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplyCeiling(), VectorBase< Real >::ApplyCeiling(), AssertEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_WARN, Rand(), and CuVectorBase< Real >::SetRandn().

591  {
592  for (int32 l = 0; l < 10; l++) {
593  int32 dim = 100 + Rand() % 700;
594  CuVector<Real> cu_vector(dim);
595  cu_vector.SetRandn();
596 
597  Vector<Real> vector(cu_vector);
598  BaseFloat floor = 0.33 * (-5 + Rand() % 10);
599  MatrixIndexT i, j;
600  cu_vector.ApplyCeiling(floor, &i);
601  vector.ApplyCeiling(floor, &j);
602 
603  CuVector<Real> cu2(vector);
604 
605  AssertEqual(cu2, cu_vector);
606  if (i != j) {
607  KALDI_WARN << "ApplyCeiling return code broken...";
608  }
609  KALDI_ASSERT(i==j);
610  }
611 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestApplyCeilingNoCount()

void kaldi::CuVectorUnitTestApplyCeilingNoCount ( )

Definition at line 613 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplyCeiling(), AssertEqual(), Rand(), and CuVectorBase< Real >::SetRandn().

613  {
614  for (int32 l = 0; l < 10; l++) {
615  int32 dim = 100 + Rand() % 700;
616  CuVector<Real> cu_vector1(dim);
617  cu_vector1.SetRandn();
618  CuVector<Real> cu_vector2(cu_vector1);
619 
620  BaseFloat floor = 0.33 * (-5 + Rand() % 10);
621  MatrixIndexT dummy_count;
622  cu_vector1.ApplyCeiling(floor, &dummy_count);
623  cu_vector2.ApplyCeiling(floor, nullptr);
624  AssertEqual(cu_vector1, cu_vector2);
625  }
626 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestApplyExp()

void kaldi::CuVectorUnitTestApplyExp ( )

Definition at line 522 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplyExp(), Exp(), rnnlm::j, KALDI_ASSERT, and CuVectorBase< Real >::SetRandn().

522  {
523  int32 dim = 100;
524  CuVector<Real> vector(dim);
525  vector.SetRandn();
526  CuVector<Real> vector2(vector);
527 
528  vector.ApplyExp();
529  for(int32 j = 0; j < dim; j++) {
530  //std::cout<<"diff is "<<exp(vector2(j))-vector(j)<<std::endl;;
531  KALDI_ASSERT(std::abs(Exp(vector2(j))-vector(j)) < 0.00001);
532  }
533 
534 }
double Exp(double x)
Definition: kaldi-math.h:83
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CuVectorUnitTestApplyFloor()

void kaldi::CuVectorUnitTestApplyFloor ( )

Definition at line 554 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplyFloor(), VectorBase< Real >::ApplyFloor(), AssertEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_WARN, Rand(), and CuVectorBase< Real >::SetRandn().

554  {
555  for (int32 l = 0; l < 10; l++) {
556  int32 dim = 100 + Rand() % 700;
557  CuVector<Real> cu_vector(dim);
558  cu_vector.SetRandn();
559 
560  Vector<Real> vector(cu_vector);
561  BaseFloat floor = 0.33 * (-5 + Rand() % 10);
562  MatrixIndexT i, j;
563  cu_vector.ApplyFloor(floor, &i);
564  vector.ApplyFloor(floor, &j);
565 
566  CuVector<Real> cu2(vector);
567 
568  AssertEqual(cu2, cu_vector);
569  if (i != j) {
570  KALDI_WARN << "ApplyFloor return code broken...";
571  }
572  KALDI_ASSERT(i==j);
573  }
574 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestApplyFloorNoCount()

void kaldi::CuVectorUnitTestApplyFloorNoCount ( )

Definition at line 576 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplyFloor(), AssertEqual(), Rand(), and CuVectorBase< Real >::SetRandn().

576  {
577  for (int32 l = 0; l < 10; l++) {
578  int32 dim = 100 + Rand() % 700;
579  CuVector<Real> cu_vector1(dim);
580  cu_vector1.SetRandn();
581  CuVector<Real> cu_vector2(cu_vector1);
582 
583  BaseFloat floor = 0.33 * (-5 + Rand() % 10);
584  MatrixIndexT dummy_count;
585  cu_vector1.ApplyFloor(floor, &dummy_count);
586  cu_vector2.ApplyFloor(floor, nullptr);
587  AssertEqual(cu_vector1, cu_vector2);
588  }
589 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestApplyLog()

void kaldi::CuVectorUnitTestApplyLog ( )

Definition at line 536 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplyLog(), rnnlm::j, KALDI_ASSERT, Log(), and CuVectorBase< Real >::SetRandn().

536  {
537  int32 dim = 100;
538  CuVector<Real> vector(dim);
539  vector.SetRandn();
540  for(int32 j = 0; j < dim; j++) {
541  if(vector(j) <= 0.0)
542  vector(j) = 1.0 - vector(j);
543  }
544 
545  CuVector<Real> vector2(vector);
546 
547  vector.ApplyLog();
548  for(int32 j = 0; j < dim; j++) {
549  //std::cout<<"diff is "<<exp(vector2(j))-vector(j)<<std::endl;;
550  KALDI_ASSERT(std::abs(Log(vector2(j))-vector(j)) < 0.000001 );
551  }
552 }
kaldi::int32 int32
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CuVectorUnitTestApplyPow()

void kaldi::CuVectorUnitTestApplyPow ( )

Definition at line 628 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplyPow(), VectorBase< Real >::ApplyPow(), AssertEqual(), Rand(), and CuVectorBase< Real >::SetRandn().

628  {
629  for (int32 l = 0; l < 10; l++) {
630  int32 dim = 100 + Rand() % 700;
631 
632  CuVector<Real> cu_vector(dim);
633  cu_vector.SetRandn();
634 
635  Vector<Real> vector(cu_vector);
636 
637  BaseFloat pow = -2 + (Rand() % 5);
638  cu_vector.ApplyPow(pow);
639  vector.ApplyPow(pow);
640 
641  CuVector<Real> cu2(vector);
642 
643  AssertEqual(cu2, cu_vector);
644  }
645 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestApplySoftMax()

void kaldi::CuVectorUnitTestApplySoftMax ( )

Definition at line 506 of file cu-vector-test.cc.

References CuVectorBase< Real >::ApplySoftMax(), VectorBase< Real >::ApplySoftMax(), AssertEqual(), rnnlm::i, Rand(), and CuVectorBase< Real >::SetRandn().

506  {
507  for (int32 i = 0; i < 10; i++) {
508  int32 dim = 100 + Rand() % 300;
509  //int32 dim = 1024;
510  CuVector<Real> cu_vector(dim);
511  cu_vector.SetRandn();
512  Vector<Real> vector(cu_vector);
513 
514  cu_vector.ApplySoftMax();
515  vector.ApplySoftMax();
516  CuVector<Real> cu_vector2(vector);
517  //std::cout<<cu_vector <<"\n"<<cu_vector2<<std::endl;
518  AssertEqual(cu_vector, cu_vector2);
519  }
520 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestApproxEqual()

void kaldi::CuVectorUnitTestApproxEqual ( )

Definition at line 280 of file cu-vector-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and CuVectorBase< Real >::SetRandn().

280  {
281  int32 M = 10 + Rand() % 100;
282  CuVector<Real> vec1(M), vec2(M);
283  vec1.SetRandn();
284  vec2.SetRandn();
285  Real tol = 0.5;
286  for (int32 i = 0; i < 10; i++) {
287  Real sumsq = 0.0, sumsq_orig = 0.0;
288  for (int32 j = 0; j < M; j++) {
289  sumsq += (vec1(j) - vec2(j)) * (vec1(j) - vec2(j));
290  sumsq_orig += vec1(j) * vec1(j);
291  }
292  Real rms = sqrt(sumsq), rms_orig = sqrt(sumsq_orig);
293  KALDI_ASSERT(vec1.ApproxEqual(vec2, tol) == (rms <= tol * rms_orig));
294  tol *= 2.0;
295  }
296 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CuVectorUnitTestCopyCross()

void kaldi::CuVectorUnitTestCopyCross ( )

Definition at line 424 of file cu-vector-test.cc.

References AssertEqual(), CuVectorBase< Real >::CopyFromVec(), rnnlm::i, Rand(), and CuVectorBase< Real >::SetRandn().

424  {
425  for (int32 i = 0; i < 10; i++) {
426  int32 M = 100 + Rand() % 255;
427  if (Rand() % 3 == 0) M = 0;
428  CuVector<Real> v1(M);
429  v1.SetRandn();
430  CuVector<float> v2(M);
431  v2.CopyFromVec(v1);
432  CuVector<Real> v3(M);
433  v3.CopyFromVec(v2);
434  AssertEqual(v1, v3);
435  }
436 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestCopyCross2()

void kaldi::CuVectorUnitTestCopyCross2 ( )

Definition at line 438 of file cu-vector-test.cc.

References AssertEqual(), CuVectorBase< Real >::CopyFromVec(), VectorBase< Real >::CopyFromVec(), rnnlm::i, Rand(), and CuVectorBase< Real >::SetRandn().

438  {
439  for (int32 i = 0; i < 10; i++) {
440  int32 M = 100 + Rand() % 255;
441  if (Rand() % 3 == 0) M = 0;
442  CuVector<Real> v1(M);
443  v1.SetRandn();
444  Vector<float> v2(M);
445  v2.CopyFromVec(v1);
446  CuVector<Real> v3(M);
447  v3.CopyFromVec(v2);
448  AssertEqual(v1, v3);
449  }
450 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestCopyDiagFromMat()

void kaldi::CuVectorUnitTestCopyDiagFromMat ( )

Definition at line 452 of file cu-vector-test.cc.

References AssertEqual(), CuVectorBase< Real >::CopyDiagFromMat(), VectorBase< Real >::CopyDiagFromMat(), rnnlm::i, kUndefined, Rand(), MatrixBase< Real >::SetRandn(), CuVectorBase< Real >::Sum(), VectorBase< Real >::Sum(), MatrixBase< Real >::Trace(), CuMatrixBase< Real >::Trace(), and Matrix< Real >::Transpose().

452  {
453  for (int32 i = 0; i < 5; i++) {
454  int32 M = 100 + Rand() % 255, N = M + Rand() % 2;
455  Matrix<Real> matrix(M, N);
456  if (i % 2 == 0) matrix.Transpose();
457  matrix.SetRandn();
458  Vector<Real> vector(M, kUndefined);
459  vector.CopyDiagFromMat(matrix);
460 
461  CuMatrix<Real> cuda_matrix(matrix);
462  CuVector<Real> cuda_vector(M, kUndefined);
463  cuda_vector.CopyDiagFromMat(cuda_matrix);
464  Vector<Real> vector2(cuda_vector);
465  AssertEqual(vector, vector2);
466  AssertEqual(vector.Sum(), cuda_matrix.Trace(false));
467  AssertEqual(cuda_vector.Sum(), matrix.Trace(false));
468  }
469 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ CuVectorUnitTestCopyDiagFromPacked()

void kaldi::CuVectorUnitTestCopyDiagFromPacked ( )

Definition at line 409 of file cu-vector-test.cc.

References VectorBase< Real >::ApproxEqual(), CuVectorBase< Real >::CopyDiagFromPacked(), VectorBase< Real >::CopyDiagFromPacked(), rnnlm::i, KALDI_ASSERT, kUndefined, Rand(), and CuPackedMatrix< Real >::SetRandn().

409  {
410  for (int32 i = 0; i < 5; i++) {
411  int32 N = 100 + Rand() % 255;
412  CuSpMatrix<Real> S(N);
413  S.SetRandn();
415  V.CopyDiagFromPacked(S);
416  SpMatrix<Real> cpu_S(S);
417  Vector<Real> cpu_V(N);
418  cpu_V.CopyDiagFromPacked(cpu_S);
419  Vector<Real> cpu_V2(V);
420  KALDI_ASSERT(cpu_V.ApproxEqual(cpu_V2));
421  }
422 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CuVectorUnitTestCopyElements()

void kaldi::CuVectorUnitTestCopyElements ( )

Definition at line 207 of file cu-vector-test.cc.

References AssertEqual(), CuVectorBase< Real >::CopyElements(), rnnlm::i, rnnlm::j, kNoTrans, kTrans, kUndefined, rnnlm::n, Rand(), CuMatrix< Real >::Resize(), CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

207  {
208  int32 dim = 10 + Rand() % 100, N = 20 + Rand() % 50;
209  CuVector<Real> V(dim);
210  V.SetRandn();
211  CuVector<Real> V_copy(V);
212  for (int n = 0; n < 2; n++) {
213  bool transpose = (n == 0);
214  CuMatrix<Real> M;
215  if (!transpose)
216  M.Resize(dim, N, kUndefined);
217  else
218  M.Resize(N, dim, kUndefined);
219  M.SetRandn();
220  std::vector<int32> elements(dim);
221  for (int32 i = 0; i < dim; i++) {
222  int32 j = elements[i] = Rand() % N;
223  if (!transpose)
224  V_copy(i) = M(i, j);
225  else
226  V_copy(i) = M(j, i);
227  }
228  CuArray<int32> cu_elements(elements);
229  V.CopyElements(M, transpose ? kTrans : kNoTrans, cu_elements);
230  AssertEqual(V, V_copy);
231  }
232 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void Resize(MatrixIndexT rows, MatrixIndexT cols, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Allocate the memory.
Definition: cu-matrix.cc:50

◆ CuVectorUnitTestCopyFromMat()

void kaldi::CuVectorUnitTestCopyFromMat ( )

Definition at line 375 of file cu-vector-test.cc.

References CuVectorBase< Real >::CopyColFromMat(), CuVectorBase< Real >::CopyRowsFromMat(), VectorBase< Real >::CopyRowsFromMat(), MatrixBase< Real >::CopyRowsFromVec(), CuMatrixBase< Real >::CopyRowsFromVec(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and CuMatrixBase< Real >::SetRandn().

375  {
376  int32 M = 100 + Rand() % 255, N = 100 + Rand() % 255;
377  CuMatrix<Real> cu_matrix(M, N);
378  cu_matrix.SetRandn();
379  for(int32 i = 0; i < N; i++) {
380  CuVector<Real> vector(M);
381  vector.CopyColFromMat(cu_matrix, i);
382  for(int32 j = 0; j < M; j++) {
383  KALDI_ASSERT(vector(j)==cu_matrix(j, i));
384  }
385  }
386  Matrix<Real> matrix(cu_matrix), matrix2(M, N);
387  CuMatrix<Real> matrix3(M, N);
388 
389  CuVector<Real> vector(M * N), vector2(M * N);
390  vector.CopyRowsFromMat(cu_matrix);
391  vector2.CopyRowsFromMat(matrix);
392  matrix2.CopyRowsFromVec(vector2);
393  matrix3.CopyRowsFromVec(Vector<Real>(vector2));
394  Vector<Real> vector3(M * N);
395  vector3.CopyRowsFromMat(cu_matrix);
396 
397 
398  for(int32 j = 0; j < M*N; j++) {
399  if (Rand() % 500 == 0) { // random small subset (it was slow)
400  KALDI_ASSERT(vector(j) == cu_matrix(j/N, j%N));
401  KALDI_ASSERT(vector2(j) == cu_matrix(j/N, j%N));
402  KALDI_ASSERT(vector2(j) == matrix2(j/N, j%N));
403  KALDI_ASSERT(vector3(j) == matrix2(j/N, j%N));
404  KALDI_ASSERT(vector3(j) == matrix3(j/N, j%N));
405  }
406  }
407 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CuVectorUnitTestInvertElements()

void kaldi::CuVectorUnitTestInvertElements ( )

Definition at line 327 of file cu-vector-test.cc.

References AssertEqual(), CuVectorBase< Real >::InvertElements(), CuVectorBase< Real >::MulElements(), Rand(), CuVectorBase< Real >::SetRandn(), and VecVec().

327  {
328  // Also tests MulElements();
329  int32 M = 256 + Rand() % 100;
330  CuVector<Real> vec1(M);
331  vec1.SetRandn();
332  CuVector<Real> vec2(vec1);
333  vec2.InvertElements();
334  CuVector<Real> vec3(vec1);
335  vec3.MulElements(vec2);
336  // vec3 should be all ones.
337  Real prod = VecVec(vec3, vec3);
338  AssertEqual(prod, static_cast<Real>(M));
339 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ CuVectorUnitTestMax()

void kaldi::CuVectorUnitTestMax ( )

Definition at line 494 of file cu-vector-test.cc.

References KALDI_ASSERT, CuVectorBase< Real >::Max(), VectorBase< Real >::Max(), Rand(), and CuVectorBase< Real >::SetRandn().

494  {
495  for (int32 p = 1; p <= 1000000; p *= 2) {
496  int32 dim = p + Rand() % 500;
497  CuVector<Real> cu_vector(dim);
498  cu_vector.SetRandn();
499  Vector<Real> vector(cu_vector);
500  Real max1 = cu_vector.Max(), max2 = vector.Max();
501  KALDI_ASSERT(max1 == max2);
502  }
503 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CuVectorUnitTestMin()

void kaldi::CuVectorUnitTestMin ( )

Definition at line 482 of file cu-vector-test.cc.

References KALDI_ASSERT, CuVectorBase< Real >::Min(), VectorBase< Real >::Min(), Rand(), and CuVectorBase< Real >::SetRandn().

482  {
483  for (int32 p = 1; p <= 1000000; p *= 2) {
484  int32 dim = p + Rand() % 500;
485  CuVector<Real> cu_vector(dim);
486  cu_vector.SetRandn();
487  Vector<Real> vector(cu_vector);
488  Real min1 = cu_vector.Min(), min2 = vector.Min();
489  KALDI_ASSERT(min1 == min2);
490  }
491 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ CuVectorUnitTestNorm()

void kaldi::CuVectorUnitTestNorm ( )

Definition at line 472 of file cu-vector-test.cc.

References ApproxEqual(), KALDI_ASSERT, and CuVectorBase< Real >::Norm().

472  {
473  int32 dim = 2;
474  CuVector<Real> cu_vector(dim);
475  cu_vector(0) = 1.0;
476  cu_vector(1) = -2.0;
477  KALDI_ASSERT(ApproxEqual(cu_vector.Norm(1.0), 3.0));
478  KALDI_ASSERT(ApproxEqual(cu_vector.Norm(2.0), sqrt(5.0)));
479 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ CuVectorUnitTestScale()

void kaldi::CuVectorUnitTestScale ( )

Definition at line 361 of file cu-vector-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, Rand(), CuVectorBase< Real >::Scale(), VectorBase< Real >::Scale(), and CuVectorBase< Real >::SetRandn().

361  {
362  for (int32 i = 0; i < 4; i++) {
363  int32 dim = 100 + Rand() % 400;
364  CuVector<Real> cu_vec(dim);
365  cu_vec.SetRandn();
366  Vector<Real> vec(cu_vec);
367  BaseFloat scale = 0.333;
368  cu_vec.Scale(scale);
369  vec.Scale(scale);
370  Vector<Real> vec2(cu_vec);
371  KALDI_ASSERT(ApproxEqual(vec, vec2));
372  }
373 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ CuVectorUnitTestSum()

void kaldi::CuVectorUnitTestSum ( )

Definition at line 341 of file cu-vector-test.cc.

References VectorBase< Real >::ApplyAbs(), KALDI_ASSERT, Rand(), CuVectorBase< Real >::Set(), VectorBase< Real >::Sum(), and VecVec().

341  {
342  for (int32 p = 1; p <= 1000000; p *= 2) {
343  MatrixIndexT dim = p + Rand() % 500;
344  CuVector<Real> A(dim), ones(dim);
345  A.SetRandn();
346  ones.Set(1.0);
347 
348  Real x = VecVec(A, ones);
349  Real y = A.Sum();
350  Real diff = std::abs(x - y);
351  // Note: CuVectorBase<> does not have an ApplyAbs() member
352  // function, so we copy back to a host vector for simplicity in
353  // this test case.
354  Vector<Real> A_host(A);
355  A_host.ApplyAbs();
356  Real s = A_host.Sum();
357  KALDI_ASSERT ( diff <= 1.0e-04 * s);
358  }
359 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ CuVectorUnitTestVecVec()

void kaldi::CuVectorUnitTestVecVec ( )

Definition at line 144 of file cu-vector-test.cc.

References AssertEqual(), rnnlm::i, Rand(), CuVectorBase< Real >::SetRandn(), and VecVec().

144  {
145  int32 M = 10 + Rand() % 100;
146  CuVector<Real> vec1(M), vec2(M);
147  vec1.SetRandn();
148  vec2.SetRandn();
149  Real prod = 0.0;
150  for (int32 i = 0; i < M; i++)
151  prod += vec1(i) * vec2(i);
152  AssertEqual(prod, VecVec(vec1, vec2));
153 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ cygprefix()

static std::string kaldi::cygprefix ( "/cygdrive/"  )
static

Referenced by prefixp().

◆ CygwinCompatPopen()

static FILE* kaldi::CygwinCompatPopen ( const char *  command,
const char *  mode 
)
static

Definition at line 110 of file kaldi-cygwin-io-inl.h.

110  {
111  // To speed up command launch marginally, optionally accept full path
112  // to bash.exe. This will not work if the path contains spaces, but
113  // no sane person would install cygwin into a space-ridden path.
114  const char* bash_exe = std::getenv("BASH_EXE");
115  std::string qcmd(bash_exe != nullptr ? bash_exe : "bash.exe");
116  qcmd += " -c \"";
117  for (; *command; ++command) {
118  if (*command == '\"')
119  qcmd += '\"';
120  qcmd += *command;
121  }
122  qcmd += '\"';
123 
124  return _popen(qcmd.c_str(), mode);
125 }

◆ DecodeLabelUid()

StateId kaldi::DecodeLabelUid ( uint64  osymbol)

Definition at line 42 of file kws-search.cc.

Referenced by main(), and OutputDetailedStatistics().

42  {
43  return static_cast<StateId>(osymbol >> 32);
44 }
fst::StdArc::StateId StateId

◆ DecodeUtterance()

bool kaldi::DecodeUtterance ( LatticeBiglmFasterDecoder decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignment_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

Definition at line 36 of file gmm-latgen-biglm-faster.cc.

References fst::AcousticLatticeScale(), LatticeBiglmFasterDecoder::Decode(), LatticeFasterDecoderConfig::det_opts, fst::DeterminizeLatticePhonePrunedWrapper(), LatticeBiglmFasterDecoder::GetBestPath(), fst::GetLinearSymbolSequence(), LatticeBiglmFasterDecoder::GetOptions(), LatticeBiglmFasterDecoder::GetRawLattice(), rnnlm::i, TableWriter< Holder >::IsOpen(), KALDI_ERR, KALDI_LOG, KALDI_VLOG, KALDI_WARN, LatticeFasterDecoderConfig::lattice_beam, LatticeBiglmFasterDecoder::ReachedFinal(), fst::ScaleLattice(), LatticeWeightTpl< FloatType >::Value1(), LatticeWeightTpl< FloatType >::Value2(), words, and TableWriter< Holder >::Write().

Referenced by main().

48  { // puts utterance's like in like_ptr on success.
49  using fst::VectorFst;
50 
51  if (!decoder.Decode(&decodable)) {
52  KALDI_WARN << "Failed to decode file " << utt;
53  return false;
54  }
55  if (!decoder.ReachedFinal()) {
56  if (allow_partial) {
57  KALDI_WARN << "Outputting partial output for utterance " << utt
58  << " since no final-state reached\n";
59  } else {
60  KALDI_WARN << "Not producing output for utterance " << utt
61  << " since no final-state reached and "
62  << "--allow-partial=false.\n";
63  return false;
64  }
65  }
66 
67  double likelihood;
68  LatticeWeight weight;
69  int32 num_frames;
70  { // First do some stuff with word-level traceback...
71  VectorFst<LatticeArc> decoded;
72  decoder.GetBestPath(&decoded);
73  if (decoded.NumStates() == 0)
74  // Shouldn't really reach this point as already checked success.
75  KALDI_ERR << "Failed to get traceback for utterance " << utt;
76 
77  std::vector<int32> alignment;
78  std::vector<int32> words;
79  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
80  num_frames = alignment.size();
81  if (words_writer->IsOpen())
82  words_writer->Write(utt, words);
83  if (alignment_writer->IsOpen())
84  alignment_writer->Write(utt, alignment);
85  if (word_syms != NULL) {
86  std::cerr << utt << ' ';
87  for (size_t i = 0; i < words.size(); i++) {
88  std::string s = word_syms->Find(words[i]);
89  if (s == "")
90  KALDI_ERR << "Word-id " << words[i] <<" not in symbol table.";
91  std::cerr << s << ' ';
92  }
93  std::cerr << '\n';
94  }
95  likelihood = -(weight.Value1() + weight.Value2());
96  }
97 
98  // Get lattice, and do determinization if requested.
99  Lattice lat;
100  decoder.GetRawLattice(&lat);
101  if (lat.NumStates() == 0)
102  KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
103  fst::Connect(&lat);
104  if (determinize) {
105  CompactLattice clat;
107  trans_model,
108  &lat,
109  decoder.GetOptions().lattice_beam,
110  &clat,
111  decoder.GetOptions().det_opts))
112  KALDI_WARN << "Determinization finished earlier than the beam for "
113  << "utterance " << utt;
114  // We'll write the lattice without acoustic scaling.
115  if (acoustic_scale != 0.0)
116  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
117  compact_lattice_writer->Write(utt, clat);
118  } else {
119  Lattice fst;
120  decoder.GetRawLattice(&fst);
121  if (fst.NumStates() == 0)
122  KALDI_ERR << "Unexpected problem getting lattice for utterance "
123  << utt;
124  fst::Connect(&fst); // Will get rid of this later... shouldn't have any
125  // disconnected states there, but we seem to.
126  if (acoustic_scale != 0.0) // We'll write the lattice without acoustic scaling
127  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &fst);
128  lattice_writer->Write(utt, fst);
129  }
130  KALDI_LOG << "Log-like per frame for utterance " << utt << " is "
131  << (likelihood / num_frames) << " over "
132  << num_frames << " frames.";
133  KALDI_VLOG(2) << "Cost for utterance " << utt << " is "
134  << weight.Value1() << " + " << weight.Value2();
135  *like_ptr = likelihood;
136  return true;
137 }
int32 words[kMaxOrder]
bool GetBestPath(fst::MutableFst< LatticeArc > *ofst, bool use_final_probs=true) const
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
bool Decode(DecodableInterface *decodable)
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
void Write(const std::string &key, const T &value) const
std::vector< std::vector< double > > AcousticLatticeScale(double acwt)
LatticeBiglmFasterDecoderConfig GetOptions()
void ScaleLattice(const std::vector< std::vector< ScaleFloat > > &scale, MutableFst< ArcTpl< Weight > > *fst)
Scales the pairs of weights in LatticeWeight or CompactLatticeWeight by viewing the pair (a...
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
bool ReachedFinal() const
says whether a final-state was active on the last frame.
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
bool GetRawLattice(fst::MutableFst< LatticeArc > *ofst, bool use_final_probs=true) const
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
fst::DeterminizeLatticePhonePrunedOptions det_opts
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
#define KALDI_LOG
Definition: kaldi-error.h:153
bool DeterminizeLatticePhonePrunedWrapper(const kaldi::TransitionModel &trans_model, MutableFst< kaldi::LatticeArc > *ifst, double beam, MutableFst< kaldi::CompactLatticeArc > *ofst, DeterminizeLatticePhonePrunedOptions opts)
This function is a wrapper of DeterminizeLatticePhonePruned() that works for Lattice type FSTs...

◆ DecodeUtteranceLatticeFaster() [1/3]

bool DecodeUtteranceLatticeFaster ( LatticeFasterDecoderTpl< FST > &  decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignments_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

This function DecodeUtteranceLatticeFaster is used in several decoders, and we have moved it here.

Note: this is really "binary-level" code as it involves table readers and writers; we've just put it here as there is no other obvious place to put it. If determinize == false, it writes to lattice_writer, else to compact_lattice_writer. The writers for alignments and words will only be written to if they are open.

Caution: this will only link correctly if FST is either fst::Fst<fst::StdArc>, or fst::GrammarFst, as the template function is defined in the .cc file and only instantiated for those two types.

Definition at line 287 of file decoder-wrappers.cc.

References fst::AcousticLatticeScale(), LatticeFasterDecoderTpl< FST, Token >::Decode(), DecodeUtteranceLatticeIncremental(), fst::DeterminizeLatticePhonePrunedWrapper(), LatticeFasterDecoderTpl< FST, Token >::GetBestPath(), fst::GetLinearSymbolSequence(), LatticeFasterDecoderTpl< FST, Token >::GetOptions(), LatticeFasterDecoderTpl< FST, Token >::GetRawLattice(), rnnlm::i, TableWriter< Holder >::IsOpen(), KALDI_ERR, KALDI_LOG, KALDI_VLOG, KALDI_WARN, LatticeFasterDecoderTpl< FST, Token >::ReachedFinal(), fst::ScaleLattice(), LatticeWeightTpl< FloatType >::Value1(), LatticeWeightTpl< FloatType >::Value2(), words, and TableWriter< Holder >::Write().

Referenced by main(), ProcessUtterance(), and AlignConfig::Register().

300  { // puts utterance's like in like_ptr on success.
301  using fst::VectorFst;
302 
303  if (!decoder.Decode(&decodable)) {
304  KALDI_WARN << "Failed to decode utterance with id " << utt;
305  return false;
306  }
307  if (!decoder.ReachedFinal()) {
308  if (allow_partial) {
309  KALDI_WARN << "Outputting partial output for utterance " << utt
310  << " since no final-state reached\n";
311  } else {
312  KALDI_WARN << "Not producing output for utterance " << utt
313  << " since no final-state reached and "
314  << "--allow-partial=false.\n";
315  return false;
316  }
317  }
318 
319  double likelihood;
320  LatticeWeight weight;
321  int32 num_frames;
322  { // First do some stuff with word-level traceback...
323  VectorFst<LatticeArc> decoded;
324  if (!decoder.GetBestPath(&decoded))
325  // Shouldn't really reach this point as already checked success.
326  KALDI_ERR << "Failed to get traceback for utterance " << utt;
327 
328  std::vector<int32> alignment;
329  std::vector<int32> words;
330  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
331  num_frames = alignment.size();
332  if (words_writer->IsOpen())
333  words_writer->Write(utt, words);
334  if (alignment_writer->IsOpen())
335  alignment_writer->Write(utt, alignment);
336  if (word_syms != NULL) {
337  std::cerr << utt << ' ';
338  for (size_t i = 0; i < words.size(); i++) {
339  std::string s = word_syms->Find(words[i]);
340  if (s == "")
341  KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
342  std::cerr << s << ' ';
343  }
344  std::cerr << '\n';
345  }
346  likelihood = -(weight.Value1() + weight.Value2());
347  }
348 
349  // Get lattice, and do determinization if requested.
350  Lattice lat;
351  decoder.GetRawLattice(&lat);
352  if (lat.NumStates() == 0)
353  KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
354  fst::Connect(&lat);
355  if (determinize) {
356  CompactLattice clat;
358  trans_model,
359  &lat,
360  decoder.GetOptions().lattice_beam,
361  &clat,
362  decoder.GetOptions().det_opts))
363  KALDI_WARN << "Determinization finished earlier than the beam for "
364  << "utterance " << utt;
365  // We'll write the lattice without acoustic scaling.
366  if (acoustic_scale != 0.0)
367  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
368  compact_lattice_writer->Write(utt, clat);
369  } else {
370  // We'll write the lattice without acoustic scaling.
371  if (acoustic_scale != 0.0)
372  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &lat);
373  lattice_writer->Write(utt, lat);
374  }
375  KALDI_LOG << "Log-like per frame for utterance " << utt << " is "
376  << (likelihood / num_frames) << " over "
377  << num_frames << " frames.";
378  KALDI_VLOG(2) << "Cost for utterance " << utt << " is "
379  << weight.Value1() << " + " << weight.Value2();
380  *like_ptr = likelihood;
381  return true;
382 }
int32 words[kMaxOrder]
kaldi::int32 int32
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
std::vector< std::vector< double > > AcousticLatticeScale(double acwt)
void ScaleLattice(const std::vector< std::vector< ScaleFloat > > &scale, MutableFst< ArcTpl< Weight > > *fst)
Scales the pairs of weights in LatticeWeight or CompactLatticeWeight by viewing the pair (a...
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
LatticeWeightTpl< BaseFloat > LatticeWeight
#define KALDI_LOG
Definition: kaldi-error.h:153
bool DeterminizeLatticePhonePrunedWrapper(const kaldi::TransitionModel &trans_model, MutableFst< kaldi::LatticeArc > *ifst, double beam, MutableFst< kaldi::CompactLatticeArc > *ofst, DeterminizeLatticePhonePrunedOptions opts)
This function is a wrapper of DeterminizeLatticePhonePruned() that works for Lattice type FSTs...

◆ DecodeUtteranceLatticeFaster() [2/3]

template bool kaldi::DecodeUtteranceLatticeFaster ( LatticeFasterDecoderTpl< fst::Fst< fst::StdArc > > &  decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignment_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

◆ DecodeUtteranceLatticeFaster() [3/3]

template bool kaldi::DecodeUtteranceLatticeFaster ( LatticeFasterDecoderTpl< fst::GrammarFst > &  decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignment_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

◆ DecodeUtteranceLatticeIncremental() [1/3]

bool DecodeUtteranceLatticeIncremental ( LatticeIncrementalDecoderTpl< FST > &  decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignment_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

TODO.

Definition at line 199 of file decoder-wrappers.cc.

References fst::AcousticLatticeScale(), CompactLatticeShortestPath(), fst::ConvertLattice(), LatticeIncrementalDecoderTpl< FST, Token >::Decode(), LatticeIncrementalDecoderTpl< FST, Token >::GetLattice(), fst::GetLinearSymbolSequence(), rnnlm::i, TableWriter< Holder >::IsOpen(), KALDI_ASSERT, KALDI_ERR, KALDI_LOG, KALDI_VLOG, KALDI_WARN, LatticeIncrementalDecoderTpl< FST, Token >::NumFramesDecoded(), LatticeIncrementalDecoderTpl< FST, Token >::ReachedFinal(), fst::ScaleLattice(), LatticeWeightTpl< FloatType >::Value1(), LatticeWeightTpl< FloatType >::Value2(), words, and TableWriter< Holder >::Write().

Referenced by DecodeUtteranceLatticeFaster(), main(), and AlignConfig::Register().

212  { // puts utterance's like in like_ptr on success.
213  using fst::VectorFst;
214  if (!decoder.Decode(&decodable)) {
215  KALDI_WARN << "Failed to decode utterance with id " << utt;
216  return false;
217  }
218  if (!decoder.ReachedFinal()) {
219  if (allow_partial) {
220  KALDI_WARN << "Outputting partial output for utterance " << utt
221  << " since no final-state reached\n";
222  } else {
223  KALDI_WARN << "Not producing output for utterance " << utt
224  << " since no final-state reached and "
225  << "--allow-partial=false.\n";
226  return false;
227  }
228  }
229 
230  // Get lattice
231  CompactLattice clat = decoder.GetLattice(decoder.NumFramesDecoded(), true);
232  if (clat.NumStates() == 0)
233  KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
234 
235  double likelihood;
236  LatticeWeight weight;
237  int32 num_frames;
238  { // First do some stuff with word-level traceback...
239  CompactLattice decoded_clat;
240  CompactLatticeShortestPath(clat, &decoded_clat);
241  Lattice decoded;
242  fst::ConvertLattice(decoded_clat, &decoded);
243 
244  if (decoded.Start() == fst::kNoStateId)
245  // Shouldn't really reach this point as already checked success.
246  KALDI_ERR << "Failed to get traceback for utterance " << utt;
247 
248  std::vector<int32> alignment;
249  std::vector<int32> words;
250  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
251  num_frames = alignment.size();
252  KALDI_ASSERT(num_frames == decoder.NumFramesDecoded());
253  if (words_writer->IsOpen())
254  words_writer->Write(utt, words);
255  if (alignment_writer->IsOpen())
256  alignment_writer->Write(utt, alignment);
257  if (word_syms != NULL) {
258  std::cerr << utt << ' ';
259  for (size_t i = 0; i < words.size(); i++) {
260  std::string s = word_syms->Find(words[i]);
261  if (s == "")
262  KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
263  std::cerr << s << ' ';
264  }
265  std::cerr << '\n';
266  }
267  likelihood = -(weight.Value1() + weight.Value2());
268  }
269 
270  // We'll write the lattice without acoustic scaling.
271  if (acoustic_scale != 0.0)
272  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
273  Connect(&clat);
274  compact_lattice_writer->Write(utt, clat);
275  KALDI_LOG << "Log-like per frame for utterance " << utt << " is "
276  << (likelihood / num_frames) << " over "
277  << num_frames << " frames.";
278  KALDI_VLOG(2) << "Cost for utterance " << utt << " is "
279  << weight.Value1() << " + " << weight.Value2();
280  *like_ptr = likelihood;
281  return true;
282 }
int32 words[kMaxOrder]
kaldi::int32 int32
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
void CompactLatticeShortestPath(const CompactLattice &clat, CompactLattice *shortest_path)
A form of the shortest-path/best-path algorithm that&#39;s specially coded for CompactLattice.
std::vector< std::vector< double > > AcousticLatticeScale(double acwt)
void ScaleLattice(const std::vector< std::vector< ScaleFloat > > &scale, MutableFst< ArcTpl< Weight > > *fst)
Scales the pairs of weights in LatticeWeight or CompactLatticeWeight by viewing the pair (a...
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
LatticeWeightTpl< BaseFloat > LatticeWeight
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ DecodeUtteranceLatticeIncremental() [2/3]

template bool kaldi::DecodeUtteranceLatticeIncremental ( LatticeIncrementalDecoderTpl< fst::Fst< fst::StdArc > > &  decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignment_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

◆ DecodeUtteranceLatticeIncremental() [3/3]

template bool kaldi::DecodeUtteranceLatticeIncremental ( LatticeIncrementalDecoderTpl< fst::GrammarFst > &  decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignment_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

◆ DecodeUtteranceLatticeSimple()

bool DecodeUtteranceLatticeSimple ( LatticeSimpleDecoder decoder,
DecodableInterface decodable,
const TransitionModel trans_model,
const fst::SymbolTable *  word_syms,
std::string  utt,
double  acoustic_scale,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignment_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

Definition at line 448 of file decoder-wrappers.cc.

References fst::AcousticLatticeScale(), LatticeSimpleDecoder::Decode(), LatticeSimpleDecoderConfig::det_opts, fst::DeterminizeLatticePhonePrunedWrapper(), LatticeSimpleDecoder::GetBestPath(), fst::GetLinearSymbolSequence(), LatticeSimpleDecoder::GetOptions(), LatticeSimpleDecoder::GetRawLattice(), rnnlm::i, TableWriter< Holder >::IsOpen(), KALDI_ERR, KALDI_LOG, KALDI_VLOG, KALDI_WARN, LatticeSimpleDecoderConfig::lattice_beam, LatticeSimpleDecoder::ReachedFinal(), fst::ScaleLattice(), LatticeWeightTpl< FloatType >::Value1(), LatticeWeightTpl< FloatType >::Value2(), words, TableWriter< Holder >::Write(), and LatticeWeightTpl< BaseFloat >::Zero().

Referenced by main().

461  { // puts utterance's like in like_ptr on success.
462  using fst::VectorFst;
463 
464  if (!decoder.Decode(&decodable)) {
465  KALDI_WARN << "Failed to decode utterance with id " << utt;
466  return false;
467  }
468  if (!decoder.ReachedFinal()) {
469  if (allow_partial) {
470  KALDI_WARN << "Outputting partial output for utterance " << utt
471  << " since no final-state reached\n";
472  } else {
473  KALDI_WARN << "Not producing output for utterance " << utt
474  << " since no final-state reached and "
475  << "--allow-partial=false.\n";
476  return false;
477  }
478  }
479 
480  double likelihood;
481  LatticeWeight weight = LatticeWeight::Zero();
482  int32 num_frames;
483  { // First do some stuff with word-level traceback...
484  VectorFst<LatticeArc> decoded;
485  if (!decoder.GetBestPath(&decoded))
486  // Shouldn't really reach this point as already checked success.
487  KALDI_ERR << "Failed to get traceback for utterance " << utt;
488 
489  std::vector<int32> alignment;
490  std::vector<int32> words;
491  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
492  num_frames = alignment.size();
493  if (words_writer->IsOpen())
494  words_writer->Write(utt, words);
495  if (alignment_writer->IsOpen())
496  alignment_writer->Write(utt, alignment);
497  if (word_syms != NULL) {
498  std::cerr << utt << ' ';
499  for (size_t i = 0; i < words.size(); i++) {
500  std::string s = word_syms->Find(words[i]);
501  if (s == "")
502  KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
503  std::cerr << s << ' ';
504  }
505  std::cerr << '\n';
506  }
507  likelihood = -(weight.Value1() + weight.Value2());
508  }
509 
510  // Get lattice, and do determinization if requested.
511  Lattice lat;
512  if (!decoder.GetRawLattice(&lat))
513  KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
514  fst::Connect(&lat);
515  if (determinize) {
516  CompactLattice clat;
518  trans_model,
519  &lat,
520  decoder.GetOptions().lattice_beam,
521  &clat,
522  decoder.GetOptions().det_opts))
523  KALDI_WARN << "Determinization finished earlier than the beam for "
524  << "utterance " << utt;
525  // We'll write the lattice without acoustic scaling.
526  if (acoustic_scale != 0.0)
527  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
528  compact_lattice_writer->Write(utt, clat);
529  } else {
530  // We'll write the lattice without acoustic scaling.
531  if (acoustic_scale != 0.0)
532  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &lat);
533  lattice_writer->Write(utt, lat);
534  }
535  KALDI_LOG << "Log-like per frame for utterance " << utt << " is "
536  << (likelihood / num_frames) << " over "
537  << num_frames << " frames.";
538  KALDI_VLOG(2) << "Cost for utterance " << utt << " is "
539  << weight.Value1() << " + " << weight.Value2();
540  *like_ptr = likelihood;
541  return true;
542 }
int32 words[kMaxOrder]
kaldi::int32 int32
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
std::vector< std::vector< double > > AcousticLatticeScale(double acwt)
void ScaleLattice(const std::vector< std::vector< ScaleFloat > > &scale, MutableFst< ArcTpl< Weight > > *fst)
Scales the pairs of weights in LatticeWeight or CompactLatticeWeight by viewing the pair (a...
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
LatticeWeightTpl< BaseFloat > LatticeWeight
#define KALDI_LOG
Definition: kaldi-error.h:153
bool DeterminizeLatticePhonePrunedWrapper(const kaldi::TransitionModel &trans_model, MutableFst< kaldi::LatticeArc > *ifst, double beam, MutableFst< kaldi::CompactLatticeArc > *ofst, DeterminizeLatticePhonePrunedOptions opts)
This function is a wrapper of DeterminizeLatticePhonePruned() that works for Lattice type FSTs...

◆ DeletePointers()

void kaldi::DeletePointers ( std::vector< A *> *  v)

Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL.

Definition at line 184 of file stl-utils.h.

References KALDI_ASSERT.

Referenced by AutomaticallyObtainQuestions(), BlockAffineComponent::Backprop(), RegressionTree::BuildTree(), ClusterEventMap(), ClusterEventMapGetMapping(), ClusterEventMapRestrictedByKeys(), ClusterEventMapRestrictedByMap(), ClusterEventMapToNClustersRestrictedByMap(), ClusterGaussiansToUbm(), ClusterKMeans(), ComputeInitialSplit(), AmDiagGmm::CopyFromAmDiagGmm(), DoTableSplit(), FindBestSplitForKey(), RegressionTree::GatherStats(), GetHTransducer(), AmDiagGmm::Init(), AccumAmDiagGmm::Init(), RegtreeMllrDiagGmmAccs::Init(), RegtreeFmllrDiagGmmAccs::Init(), CompositeComponent::Init(), InitAmGmm(), DecodableAmDiagGmmRegtreeMllr::InitCache(), CompositeComponent::InitFromConfig(), KMeansClusterPhones(), main(), MapEventMapLeaves(), DiagGmm::MergeKmeans(), ObjfGivenMap(), BlockAffineComponent::Propagate(), Questions::Read(), RenumberEventMap(), ShareEventMapLeaves(), TestAddToClusters(), TestAddToClustersOptimized(), TestClusterBottomUp(), TestClusterEventMapGetMappingAndRenumberEventMap(), TestClusterEventMapGetMappingAndRenumberEventMap2(), TestClusterKMeans(), TestClusterKMeansVector(), TestClusterTopDown(), TestEnsureClusterableVectorNotNull(), TestRefineClusters(), TestTreeCluster(), TypeOneUsage(), TypeOneUsageAverage(), UnitTestRegtreeFmllrDiagGmm(), RegtreeMllrDiagGmmAccs::Update(), RegtreeFmllrDiagGmmAccs::Update(), AccumAmDiagGmm::~AccumAmDiagGmm(), AmDiagGmm::~AmDiagGmm(), BottomUpClusterer::~BottomUpClusterer(), CompartmentalizedBottomUpClusterer::~CompartmentalizedBottomUpClusterer(), CompositeComponent::~CompositeComponent(), DecodableAmDiagGmmRegtreeMllr::~DecodableAmDiagGmmRegtreeMllr(), DecodableAmNnetSimpleParallel::~DecodableAmNnetSimpleParallel(), GeneralDescriptor::~GeneralDescriptor(), Questions::~Questions(), RegtreeFmllrDiagGmmAccs::~RegtreeFmllrDiagGmmAccs(), RegtreeMllrDiagGmmAccs::~RegtreeMllrDiagGmmAccs(), SwitchingForwardingDescriptor::~SwitchingForwardingDescriptor(), TableEventMap::~TableEventMap(), and TreeClusterer::~TreeClusterer().

184  {
185  KALDI_ASSERT(v != NULL);
186  typename std::vector<A*>::iterator iter = v->begin(), end = v->end();
187  for (; iter != end; ++iter) {
188  if (*iter != NULL) {
189  delete *iter;
190  *iter = NULL; // set to NULL for extra safety.
191  }
192  }
193 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ DeterminizeLatticeWrapper()

bool DeterminizeLatticeWrapper ( const Lattice lat,
const std::string &  key,
bool  prune,
BaseFloat  beam,
BaseFloat  beam_ratio,
int32  max_mem,
int32  max_loop,
BaseFloat  delta,
int32  num_loops,
CompactLattice clat 
)

Definition at line 38 of file lattice-determinize-non-compact.cc.

References DeterminizeLatticeOptions::delta, fst::DeterminizeLattice(), rnnlm::i, KALDI_WARN, DeterminizeLatticeOptions::max_loop, DeterminizeLatticeOptions::max_mem, fst::NumArcs(), and PruneLattice().

Referenced by main().

47  {
49  lat_opts.max_mem = max_mem;
50  lat_opts.max_loop = max_loop;
51  lat_opts.delta = delta;
52  BaseFloat cur_beam = beam;
53  for (int32 i = 0; i < num_loops;) { // we increment i below.
54 
55  if (lat.Start() == fst::kNoStateId) {
56  KALDI_WARN << "Detected empty lattice, skipping " << key;
57  return false;
58  }
59 
60  // The work gets done in the next line.
61  if (DeterminizeLattice(lat, clat, lat_opts, NULL)) {
62  if (prune) PruneLattice(cur_beam, clat);
63  return true;
64  } else { // failed to determinize..
65  KALDI_WARN << "Failed to determinize lattice (presumably max-states "
66  << "reached), reducing lattice-beam to "
67  << (cur_beam*beam_ratio) << " and re-trying.";
68  for (; i < num_loops; i++) {
69  cur_beam *= beam_ratio;
70  Lattice pruned_lat(lat);
71  PruneLattice(cur_beam, &pruned_lat);
72  if (NumArcs(lat) == NumArcs(pruned_lat)) {
73  cur_beam *= beam_ratio;
74  KALDI_WARN << "Pruning did not have an effect on the original "
75  << "lattice size; reducing beam to "
76  << cur_beam << " and re-trying.";
77  } else if (DeterminizeLattice(pruned_lat, clat, lat_opts, NULL)) {
78  if (prune) PruneLattice(cur_beam, clat);
79  return true;
80  } else {
81  KALDI_WARN << "Determinization failed again; reducing beam again to "
82  << (cur_beam*beam_ratio) << " and re-trying.";
83  }
84  }
85  }
86  }
87  KALDI_WARN << "Decreased pruning beam --num-loops=" << num_loops
88  << " times and was not able to determinize: failed for "
89  << key;
90  return false;
91 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_WARN
Definition: kaldi-error.h:150
bool PruneLattice(BaseFloat beam, LatType *lat)
bool DeterminizeLattice(const Fst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< Weight > > *ofst, DeterminizeLatticeOptions opts, bool *debug_ptr)
This function implements the normal version of DeterminizeLattice, in which the output strings are re...
Arc::StateId NumArcs(const ExpandedFst< Arc > &fst)
Returns the total number of arcs in an FST.

◆ DiagGmmToStats()

void DiagGmmToStats ( const DiagGmm gmm,
GmmFlagsType  flags,
double  state_occ,
AccumDiagGmm dst_stats 
)

Creates stats from the GMM. Resizes them as needed.

Definition at line 339 of file ebw-diag-gmm.cc.

References AccumDiagGmm::AddStatsForComponent(), VectorBase< Real >::AddVec(), VectorBase< Real >::AddVec2(), AugmentGmmFlags(), DiagGmm::Dim(), DiagGmmNormal::means_, DiagGmm::NumGauss(), AccumDiagGmm::Resize(), MatrixBase< Real >::Row(), VectorBase< Real >::SetZero(), DiagGmmNormal::vars_, and DiagGmmNormal::weights_.

Referenced by IsmoothStatsAmDiagGmmFromModel(), and EbwWeightOptions::Register().

342  {
343  dst_stats->Resize(gmm, AugmentGmmFlags(flags));
344  int32 num_gauss = gmm.NumGauss(), dim = gmm.Dim();
345  DiagGmmNormal gmmnormal(gmm);
346  Vector<double> x_stats(dim), x2_stats(dim);
347  for (int32 g = 0; g < num_gauss; g++) {
348  double occ = state_occ * gmmnormal.weights_(g);
349  x_stats.SetZero();
350  x_stats.AddVec(occ, gmmnormal.means_.Row(g));
351  x2_stats.SetZero();
352  x2_stats.AddVec2(occ, gmmnormal.means_.Row(g));
353  x2_stats.AddVec(occ, gmmnormal.vars_.Row(g));
354  dst_stats->AddStatsForComponent(g, occ, x_stats, x2_stats);
355  }
356 }
GmmFlagsType AugmentGmmFlags(GmmFlagsType f)
Returns "augmented" version of flags: e.g.
Definition: model-common.cc:52
kaldi::int32 int32

◆ DifferenceWrapper()

static void kaldi::DifferenceWrapper ( const fst::VectorFst< Arc > &  fst1,
const fst::VectorFst< Arc > &  fst2,
fst::VectorFst< Arc > *  difference 
)
static

Definition at line 303 of file kws-functions.cc.

References fst::RemoveWeights().

Referenced by MaybeDoSanityCheck().

305  {
306  using namespace fst;
307  if (!fst2.Properties(kAcceptor, true)) {
308  // make it an acceptor by encoding the weights.
309  EncodeMapper<Arc> encoder(kEncodeLabels, ENCODE);
310  VectorFst<Arc> fst1_copy(fst1);
311  VectorFst<Arc> fst2_copy(fst2);
312  Encode(&fst1_copy, &encoder);
313  Encode(&fst2_copy, &encoder);
314  DifferenceWrapper(fst1_copy, fst2_copy, difference);
315  Decode(difference, encoder);
316  } else {
317  VectorFst<Arc> fst2_copy(fst2);
318  RmEpsilon(&fst2_copy); // or Difference will crash.
319  RemoveWeights(&fst2_copy); // or Difference will crash.
320  Difference(fst1, fst2_copy, difference);
321  }
322 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
static void DifferenceWrapper(const fst::VectorFst< Arc > &fst1, const fst::VectorFst< Arc > &fst2, fst::VectorFst< Arc > *difference)
void RemoveWeights(MutableFst< Arc > *ifst)

◆ DirExist()

bool kaldi::DirExist ( const std::string &  dirname)

Definition at line 43 of file pitch-functions-test.cc.

References KALDI_LOG.

Referenced by main().

43  {
44  struct stat st;
45  if (stat(dirname.c_str(), &st) != 0) {
46  KALDI_LOG << " directory " << dirname << " does not exist!";
47  return false;
48  }
49  return true;
50 }
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ DivideRoundingDown()

static int32 kaldi::DivideRoundingDown ( int32  a,
int32  b 
)
inlinestatic

Returns a / b, rounding towards negative infinity in all cases.

Definition at line 287 of file kaldi-math.h.

References KALDI_ASSERT.

Referenced by BackpropTruncationComponent::PrecomputeIndexes(), GeneralDropoutComponent::PrecomputeIndexes(), kaldi::nnet3::time_height_convolution::RoundDownToMultipleOf(), and UnitTestDivideRoundingDown().

287  {
288  KALDI_ASSERT(b != 0);
289  if (a * b >= 0)
290  return a / b;
291  else if (a < 0)
292  return (a - b + 1) / b;
293  else
294  return (a - b - 1) / b;
295 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ DoFactorDisambiguation()

void DoFactorDisambiguation ( KwsLexicographicFst index_transducer)

Definition at line 98 of file kws-functions2.cc.

Referenced by main().

98  {
99  using namespace fst;
101 
102  StateId ns = index_transducer->NumStates();
103  for (StateId s = 0; s < ns; s++) {
104  for (MutableArcIterator<KwsLexicographicFst>
105  aiter(index_transducer, s); !aiter.Done(); aiter.Next()) {
106  KwsLexicographicArc arc = aiter.Value();
107  if (index_transducer->Final(arc.nextstate) != KwsLexicographicWeight::Zero())
108  arc.ilabel = s;
109  else
110  arc.olabel = 0;
111  aiter.SetValue(arc);
112  }
113  }
114 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
StdLStdLStdArc KwsLexicographicArc
Definition: kaldi-kws.h:45

◆ DoFactorMerging()

void DoFactorMerging ( KwsProductFst factor_transducer,
KwsLexicographicFst index_transducer 
)

Definition at line 53 of file kws-functions2.cc.

References fst::DeterminizeStar(), KALDI_VLOG, MaybeDoSanityCheck(), and ReplaceSymbolWithEpsilon().

Referenced by main().

54  {
55  using namespace fst;
57 
58  // Encode the transducer first
59  EncodeMapper<KwsProductArc> encoder(kEncodeLabels, ENCODE);
60  Encode(factor_transducer, &encoder);
61 
62 
63  // We want DeterminizeStar to remove epsilon arcs, so turn whatever it encoded
64  // epsilons as, into actual epsilons.
65  {
66  KwsProductArc epsilon_arc(0, 0, KwsProductWeight::One(), 0);
67  Label epsilon_label = encoder(epsilon_arc).ilabel;
68  ReplaceSymbolWithEpsilon(epsilon_label, factor_transducer);
69  }
70 
71 
72  MaybeDoSanityCheck(*factor_transducer);
73 
74  // Use DeterminizeStar
75  KALDI_VLOG(2) << "DoFactorMerging: determinization...";
76  KwsProductFst dest_transducer;
77  DeterminizeStar(*factor_transducer, &dest_transducer);
78 
79  MaybeDoSanityCheck(dest_transducer);
80 
81  // Commenting the minimization out, as it moves states/arcs in a way we don't
82  // want in some rare cases. For example, if we have two arcs from starting
83  // state, which have same words on the input side, but different cluster IDs
84  // on the output side, it may make the two arcs sharing a common final arc,
85  // which will cause problem in the factor disambiguation stage (we will not
86  // be able to add disambiguation symbols for both paths). We do a final step
87  // optimization anyway so commenting this out shouldn't matter too much.
88  // KALDI_VLOG(2) << "DoFactorMerging: minimization...";
89  // Minimize(&dest_transducer);
90 
91  MaybeDoSanityCheck(dest_transducer);
92 
93  Decode(&dest_transducer, encoder);
94 
95  Map(dest_transducer, index_transducer, KwsProductFstToKwsLexicographicFstMapper());
96 }
fst::VectorFst< KwsProductArc > KwsProductFst
Definition: kaldi-kws.h:49
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
static void ReplaceSymbolWithEpsilon(typename Arc::Label symbol, fst::VectorFst< Arc > *fst)
fst::StdArc::Label Label
void MaybeDoSanityCheck(const KwsLexicographicFst &index_transducer)
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
LogXStdXStdprimeArc KwsProductArc
Definition: kaldi-kws.h:48
bool DeterminizeStar(F &ifst, MutableFst< typename F::Arc > *ofst, float delta, bool *debug_ptr, int max_states, bool allow_partial)
This function implements the normal version of DeterminizeStar, in which the output strings are repre...

◆ DoRescalingUpdate() [1/2]

void kaldi::DoRescalingUpdate ( const AccumDiagGmm old_ml_acc,
const AccumDiagGmm new_ml_acc,
BaseFloat  min_variance,
BaseFloat  min_gaussian_occupancy,
DiagGmm gmm,
double *  tot_count,
double *  tot_divergence 
)

Definition at line 177 of file indirect-diff-diag-gmm.cc.

References DiagGmmNormal::CopyToDiagGmm(), rnnlm::d, DiagGmm::Dim(), AccumDiagGmm::Dim(), AccumDiagGmm::Flags(), KALDI_ASSERT, KALDI_WARN, kGmmMeans, kGmmVariances, Log(), AccumDiagGmm::mean_accumulator(), DiagGmmNormal::means_, DiagGmm::NumGauss(), AccumDiagGmm::NumGauss(), AccumDiagGmm::occupancy(), AccumDiagGmm::variance_accumulator(), and DiagGmmNormal::vars_.

Referenced by DoRescalingUpdate(), and main().

183  {
184  int32 num_gauss = gmm->NumGauss(), dim = gmm->Dim();
185  KALDI_ASSERT(old_ml_acc.NumGauss() == num_gauss &&
186  old_ml_acc.Dim() == dim);
187  KALDI_ASSERT(new_ml_acc.NumGauss() == num_gauss &&
188  new_ml_acc.Dim() == dim);
189  KALDI_ASSERT((old_ml_acc.Flags() & (kGmmMeans|kGmmVariances)) ==
191  KALDI_ASSERT((new_ml_acc.Flags() & (kGmmMeans|kGmmVariances)) ==
193 
194  DiagGmmNormal gmm_normal(*gmm);
195  for (int32 gauss = 0; gauss < num_gauss; gauss++) {
196  double old_ml_count = old_ml_acc.occupancy()(gauss),
197  new_ml_count = new_ml_acc.occupancy()(gauss);
198  if (old_ml_count <= min_gaussian_occupancy ||
199  new_ml_count <= min_gaussian_occupancy) {
200  KALDI_WARN << "Gaussian being skipped because it has small count: (old,new) = "
201  << old_ml_count << ", " << new_ml_count;
202  continue;
203  }
204  *tot_count += new_ml_count;
205  for (int32 d = 0; d < dim; d++) {
206  double old_model_mean = gmm_normal.means_(gauss, d),
207  old_model_var = gmm_normal.vars_(gauss, d),
208  old_ml_mean = old_ml_acc.mean_accumulator()(gauss, d) / old_ml_count,
209  old_ml_var = old_ml_acc.variance_accumulator()(gauss, d) / old_ml_count
210  - old_ml_mean*old_ml_mean,
211  new_ml_mean = new_ml_acc.mean_accumulator()(gauss, d) / new_ml_count,
212  new_ml_var = new_ml_acc.variance_accumulator()(gauss, d) / new_ml_count
213  - new_ml_mean*new_ml_mean,
214  new_model_mean = old_model_mean + new_ml_mean - old_ml_mean,
215  new_model_var = std::max(static_cast<double>(min_variance),
216  old_model_var * new_ml_var / old_ml_var);
217  double divergence =
218  0.5 *(((new_model_mean-old_model_mean)*(new_model_mean-old_model_mean) +
219  new_model_var - old_model_var)/old_model_var +
220  Log(old_model_var / new_model_var));
221  if (divergence < 0.0)
222  KALDI_WARN << "Negative divergence " << divergence;
223  *tot_divergence += divergence * new_ml_count;
224  gmm_normal.means_(gauss, d) = new_model_mean;
225  gmm_normal.vars_(gauss, d) = new_model_var;
226  }
227  }
228  gmm_normal.CopyToDiagGmm(gmm);
229 }
kaldi::int32 int32
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ DoRescalingUpdate() [2/2]

void DoRescalingUpdate ( const AccumAmDiagGmm old_ml_accs,
const AccumAmDiagGmm new_ml_accs,
BaseFloat  min_variance,
BaseFloat  min_gaussian_occupancy,
AmDiagGmm am_gmm 
)

Definition at line 232 of file indirect-diff-diag-gmm.cc.

References AmDiagGmm::ComputeGconsts(), DoRescalingUpdate(), AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), KALDI_ASSERT, KALDI_LOG, AccumAmDiagGmm::NumAccs(), and AmDiagGmm::NumPdfs().

236  {
237  int32 num_pdfs = am_gmm->NumPdfs();
238  KALDI_ASSERT(old_ml_accs.NumAccs() == num_pdfs);
239  KALDI_ASSERT(new_ml_accs.NumAccs() == num_pdfs);
240  double tot_count = 0.0, tot_divergence = 0.0;
241  for (int32 pdf = 0; pdf < num_pdfs; pdf++)
242  DoRescalingUpdate(old_ml_accs.GetAcc(pdf), new_ml_accs.GetAcc(pdf),
243  min_variance, min_gaussian_occupancy, &am_gmm->GetPdf(pdf),
244  &tot_count, &tot_divergence);
245  KALDI_LOG << "K-L divergence from old to new model is "
246  << (tot_divergence/tot_count) << " over "
247  << tot_count << " frames.";
248  am_gmm->ComputeGconsts();
249 }
kaldi::int32 int32
void DoRescalingUpdate(const AccumAmDiagGmm &old_ml_accs, const AccumAmDiagGmm &new_ml_accs, BaseFloat min_variance, BaseFloat min_gaussian_occupancy, AmDiagGmm *am_gmm)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ DoReverberation()

float kaldi::DoReverberation ( const Vector< BaseFloat > &  rir,
BaseFloat  samp_freq,
Vector< BaseFloat > *  signal 
)

Definition at line 93 of file wav-reverberate.cc.

References ComputeEarlyReverbEnergy(), and FFTbasedBlockConvolveSignals().

Referenced by main().

94  {
95  float signal_power = ComputeEarlyReverbEnergy(rir, *signal, samp_freq);
96  FFTbasedBlockConvolveSignals(rir, signal);
97  return signal_power;
98 }
BaseFloat ComputeEarlyReverbEnergy(const Vector< BaseFloat > &rir, const Vector< BaseFloat > &signal, BaseFloat samp_freq)
void FFTbasedBlockConvolveSignals(const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
Definition: signal.cc:77

◆ DoubleFactorial() [1/2]

static int32 kaldi::DoubleFactorial ( int32  i)
static

Definition at line 444 of file matrix-lib-test.cc.

Referenced by DoubleFactorial(), UnitTestCuMatrixSetRandn(), and UnitTestSetRandn().

444  {
445  if (i <= 0) { return 1; } else { return i * DoubleFactorial(i - 2); }
446 }
static int32 DoubleFactorial(int32 i)

◆ DoubleFactorial() [2/2]

static int32 kaldi::DoubleFactorial ( int32  i)
static

Definition at line 2622 of file cu-matrix-test.cc.

References DoubleFactorial().

2622  {
2623  if (i <= 0) { return 1; } else { return i * DoubleFactorial(i - 2); }
2624 }
static int32 DoubleFactorial(int32 i)

◆ EBWUpdateGaussian()

static bool kaldi::EBWUpdateGaussian ( BaseFloat  D,
GmmFlagsType  flags,
const VectorBase< double > &  orig_mean,
const VectorBase< double > &  orig_var,
const VectorBase< double > &  x_stats,
const VectorBase< double > &  x2_stats,
double  occ,
VectorBase< double > *  mean,
VectorBase< double > *  var,
double *  auxf_impr 
)
static

Definition at line 31 of file ebw-diag-gmm.cc.

References VectorBase< Real >::AddVec(), VectorBase< Real >::AddVec2(), VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Dim(), rnnlm::i, KALDI_ASSERT, kGmmMeans, kGmmVariances, Log(), VectorBase< Real >::Min(), VectorBase< Real >::Scale(), and VectorBase< Real >::SetZero().

Referenced by UpdateEbwDiagGmm().

41  {
42  if (! (flags&(kGmmMeans|kGmmVariances))) { // nothing to do.
43  if (auxf_impr) *auxf_impr = 0.0;
44  mean->CopyFromVec(orig_mean);
45  var->CopyFromVec(orig_var);
46  return true;
47  }
48  KALDI_ASSERT(!( (flags&kGmmVariances) && !(flags&kGmmMeans))
49  && "We didn't make the update cover this case sensibly (update vars not means)");
50 
51  mean->SetZero();
52  var->SetZero();
53  mean->AddVec(D, orig_mean);
54  var->AddVec2(D, orig_mean);
55  var->AddVec(D, orig_var);
56  mean->AddVec(1.0, x_stats);
57  var->AddVec(1.0, x2_stats);
58  BaseFloat scale = 1.0 / (occ + D);
59  mean->Scale(scale);
60  var->Scale(scale);
61  var->AddVec2(-1.0, *mean);
62 
63  if (!(flags&kGmmVariances)) var->CopyFromVec(orig_var);
64  if (!(flags&kGmmMeans)) mean->CopyFromVec(orig_mean);
65 
66  // Return false if any NaN's.
67  for (int32 i = 0; i < mean->Dim(); i++) {
68  double m = ((*mean)(i)), v = ((*var)(i));
69  if (m!=m || v!=v || m-m != 0 || v-v != 0) {
70  return false;
71  }
72  }
73 
74  if (var->Min() > 0.0) {
75  if (auxf_impr != NULL) {
76  // work out auxf improvement.
77  BaseFloat old_auxf = 0.0, new_auxf = 0.0;
78  int32 dim = orig_mean.Dim();
79  for (int32 i = 0; i < dim; i++) {
80  BaseFloat mean_diff = (*mean)(i) - orig_mean(i);
81  old_auxf += (occ+D) * -0.5 * (Log(orig_var(i)) +
82  ((*var)(i) + mean_diff*mean_diff)
83  / orig_var(i));
84  new_auxf += (occ+D) * -0.5 * (Log((*var)(i)) + 1.0);
85 
86  }
87  *auxf_impr = new_auxf - old_auxf;
88  }
89  return true;
90  } else return false;
91 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ElementwiseProductOfFft()

void kaldi::ElementwiseProductOfFft ( const Vector< BaseFloat > &  a,
Vector< BaseFloat > *  b 
)

Definition at line 26 of file signal.cc.

References ComplexMul(), VectorBase< Real >::Dim(), and rnnlm::i.

Referenced by FFTbasedBlockConvolveSignals(), and FFTbasedConvolveSignals().

26  {
27  int32 num_fft_bins = a.Dim() / 2;
28  for (int32 i = 0; i < num_fft_bins; i++) {
29  // do complex multiplication
30  ComplexMul(a(2*i), a(2*i + 1), &((*b)(2*i)), &((*b)(2*i + 1)));
31  }
32 }
kaldi::int32 int32
void ComplexMul(const Real &a_re, const Real &a_im, Real *b_re, Real *b_im)
ComplexMul implements, inline, the complex multiplication b *= a.

◆ EncodeLabel()

uint64 kaldi::EncodeLabel ( StateId  ilabel,
StateId  olabel 
)

Definition at line 35 of file kws-search.cc.

Referenced by main().

35  {
36  return (static_cast<int64>(olabel) << 32) + static_cast<int64>(ilabel);
37 }

◆ EndpointDetected< fst::Fst< fst::StdArc > >() [1/2]

template bool kaldi::EndpointDetected< fst::Fst< fst::StdArc > > ( const OnlineEndpointConfig config,
const TransitionModel tmodel,
BaseFloat  frame_shift_in_seconds,
const LatticeFasterOnlineDecoderTpl< fst::Fst< fst::StdArc > > &  decoder 
)

◆ EndpointDetected< fst::Fst< fst::StdArc > >() [2/2]

template bool kaldi::EndpointDetected< fst::Fst< fst::StdArc > > ( const OnlineEndpointConfig config,
const TransitionModel tmodel,
BaseFloat  frame_shift_in_seconds,
const LatticeIncrementalOnlineDecoderTpl< fst::Fst< fst::StdArc > > &  decoder 
)

◆ EndpointDetected< fst::GrammarFst >() [1/2]

template bool kaldi::EndpointDetected< fst::GrammarFst > ( const OnlineEndpointConfig config,
const TransitionModel tmodel,
BaseFloat  frame_shift_in_seconds,
const LatticeFasterOnlineDecoderTpl< fst::GrammarFst > &  decoder 
)

◆ EndpointDetected< fst::GrammarFst >() [2/2]

template bool kaldi::EndpointDetected< fst::GrammarFst > ( const OnlineEndpointConfig config,
const TransitionModel tmodel,
BaseFloat  frame_shift_in_seconds,
const LatticeIncrementalOnlineDecoderTpl< fst::GrammarFst > &  decoder 
)

◆ EstimateIvectorsOnline()

double EstimateIvectorsOnline ( const Matrix< BaseFloat > &  feats,
const Posterior post,
const IvectorExtractor extractor,
int32  ivector_period,
int32  num_cg_iters,
BaseFloat  max_count,
Matrix< BaseFloat > *  ivectors 
)

Definition at line 1778 of file ivector-extractor.cc.

References IvectorExtractor::IvectorDim(), KALDI_ASSERT, MatrixBase< Real >::NumRows(), IvectorExtractor::PriorOffset(), Matrix< Real >::Resize(), and MatrixBase< Real >::Row().

Referenced by main().

1785  {
1786 
1787  KALDI_ASSERT(ivector_period > 0);
1788  KALDI_ASSERT(static_cast<int32>(post.size()) == feats.NumRows());
1789  int32 num_frames = feats.NumRows(),
1790  num_ivectors = (num_frames + ivector_period - 1) / ivector_period;
1791 
1792  ivectors->Resize(num_ivectors, extractor.IvectorDim());
1793 
1794  OnlineIvectorEstimationStats online_stats(extractor.IvectorDim(),
1795  extractor.PriorOffset(),
1796  max_count);
1797 
1798  double ans = 0.0;
1799 
1800  Vector<double> cur_ivector(extractor.IvectorDim());
1801  cur_ivector(0) = extractor.PriorOffset();
1802  for (int32 frame = 0; frame < num_frames; frame++) {
1803  online_stats.AccStats(extractor,
1804  feats.Row(frame),
1805  post[frame]);
1806  if (frame % ivector_period == 0) {
1807  online_stats.GetIvector(num_cg_iters, &cur_ivector);
1808  int32 ivector_index = frame / ivector_period;
1809  ivectors->Row(ivector_index).CopyFromVec(cur_ivector);
1810  if (ivector_index == num_ivectors - 1) // last iVector
1811  ans = online_stats.ObjfChange(cur_ivector);
1812  }
1813  }
1814  return ans;
1815 }
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ EstimateSgmm2FmllrSubspace()

void EstimateSgmm2FmllrSubspace ( const SpMatrix< double > &  fmllr_grad_scatter,
int32  num_fmllr_bases,
int32  feat_dim,
Sgmm2FmllrGlobalParams fmllr_globals,
double  min_eig = 0.0 
)

Computes the fMLLR basis matrices given the scatter of the vectorized gradients (eq: B.10).

The result is stored in 'fmllr_globals'. The actual number of bases may be less than 'num_fmllr_bases' depending on the feature dimension and number of eigenvalues greater than 'min_eig'.

Definition at line 506 of file fmllr-sgmm2.cc.

References VectorBase< Real >::Dim(), SpMatrix< Real >::Eig(), Sgmm2FmllrGlobalParams::fmllr_bases_, KALDI_ASSERT, KALDI_LOG, KALDI_VLOG, KALDI_WARN, kSetZero, PackedMatrix< Real >::NumRows(), and SortSvd().

Referenced by TestSgmm2FmllrSubspace().

508  {
509  KALDI_ASSERT(num_fmllr_bases > 0 && feat_dim > 0);
510  if (num_fmllr_bases > feat_dim * (feat_dim + 1)) {
511  num_fmllr_bases = feat_dim * (feat_dim + 1);
512  KALDI_WARN << "Limiting number of fMLLR bases to be the same as transform "
513  << "dimension.";
514  }
515 
516  vector< Matrix<BaseFloat> > &fmllr_bases(globals->fmllr_bases_);
517 
518  Vector<double> s(fmllr_grad_scatter.NumRows());
519  Matrix<double> U(fmllr_grad_scatter.NumRows(),
520  fmllr_grad_scatter.NumRows());
521  try {
522  fmllr_grad_scatter.Eig(&s, &U);
523  SortSvd(&s, &U); // in case was not exactly sorted.
524  KALDI_VLOG(1) << "Eigenvalues (max 200) of CMLLR scatter are: "
525  << (SubVector<double>(s, 0,
526  std::min(static_cast<MatrixIndexT>(200),
527  s.Dim())));
528 
529 
530 // for (int32 b = 2; b < num_fmllr_bases; b++) {
531 // if (s(b) < min_eig) {
532 // num_fmllr_bases = b;
533 // KALDI_WARN << "Limiting number of fMLLR bases to " << num_fmllr_bases
534 // << " because of small eigenvalues.";
535 // break;
536 // }
537 // }
538 
539  U.Transpose(); // Now the rows of U correspond to the basis vectors.
540  fmllr_bases.resize(num_fmllr_bases);
541  for (int32 b = 0; b < num_fmllr_bases; b++) {
542  fmllr_bases[b].Resize(feat_dim, feat_dim + 1, kSetZero);
543  fmllr_bases[b].CopyRowsFromVec(U.Row(b));
544  }
545  KALDI_LOG << "Estimated " << num_fmllr_bases << " fMLLR basis matrices.";
546  } catch(const std::exception &e) {
547  KALDI_WARN << "Not estimating FMLLR bases because of a thrown exception:\n"
548  << e.what();
549  fmllr_bases.resize(0);
550  }
551 } // End of EstimateSgmm2FmllrSubspace
kaldi::int32 int32
void Eig(VectorBase< Real > *s, MatrixBase< Real > *P=NULL) const
Solves the symmetric eigenvalue problem: at end we should have (*this) = P * diag(s) * P^T...
Definition: qr.cc:433
MatrixIndexT NumRows() const
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
#define KALDI_LOG
Definition: kaldi-error.h:153
void SortSvd(VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt, bool sort_on_absolute_value)
Function to ensure that SVD is sorted.

◆ EstPca()

bool kaldi::EstPca ( const Matrix< BaseFloat > &  ivector_mat,
BaseFloat  target_energy,
const std::string &  reco,
Matrix< BaseFloat > *  mat 
)

Definition at line 29 of file ivector-plda-scoring-dense.cc.

References SpMatrix< Real >::AddMat2(), VectorBase< Real >::AddRowSumMat(), SpMatrix< Real >::AddVec2(), ApproxEqual(), MatrixBase< Real >::CopyFromMat(), VectorBase< Real >::Dim(), SpMatrix< Real >::Eig(), KALDI_WARN, kCopyData, kTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), SpMatrix< Real >::Resize(), Vector< Real >::Resize(), Matrix< Real >::Resize(), PackedMatrix< Real >::Scale(), VectorBase< Real >::Scale(), SortSvd(), and VectorBase< Real >::Sum().

Referenced by main().

30  {
31 
32  // If the target_energy is 1.0, it's equivalent to not applying the
33  // conversation-dependent PCA at all, so it's better to exit this
34  // function before doing any computation.
35  if (ApproxEqual(target_energy, 1.0, 0.001))
36  return false;
37 
38  int32 num_rows = ivector_mat.NumRows(),
39  num_cols = ivector_mat.NumCols();
41  SpMatrix<BaseFloat> sumsq;
42  sum.Resize(num_cols);
43  sumsq.Resize(num_cols);
44  sum.AddRowSumMat(1.0, ivector_mat);
45  sumsq.AddMat2(1.0, ivector_mat, kTrans, 1.0);
46  sum.Scale(1.0 / num_rows);
47  sumsq.Scale(1.0 / num_rows);
48  sumsq.AddVec2(-1.0, sum); // now sumsq is centered covariance.
49  int32 full_dim = sum.Dim();
50 
51  Matrix<BaseFloat> P(full_dim, full_dim);
52  Vector<BaseFloat> s(full_dim);
53 
54  try {
55  if (num_rows > num_cols)
56  sumsq.Eig(&s, &P);
57  else
58  Matrix<BaseFloat>(sumsq).Svd(&s, &P, NULL);
59  } catch (...) {
60  KALDI_WARN << "Unable to compute conversation dependent PCA for"
61  << " recording " << reco << ".";
62  return false;
63  }
64 
65  SortSvd(&s, &P);
66 
67  Matrix<BaseFloat> transform(P, kTrans); // Transpose of P. This is what
68  // appears in the transform.
69 
70  // We want the PCA transform to retain target_energy amount of the total
71  // energy.
72  BaseFloat total_energy = s.Sum();
73  BaseFloat energy = 0.0;
74  int32 dim = 1;
75  while (energy / total_energy <= target_energy) {
76  energy += s(dim-1);
77  dim++;
78  }
79  Matrix<BaseFloat> transform_float(transform);
80  mat->Resize(transform.NumCols(), transform.NumRows());
81  mat->CopyFromMat(transform);
82  mat->Resize(dim, transform_float.NumCols(), kCopyData);
83  return true;
84 }
void AddMat2(const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transM, const Real beta)
rank-N update: if (transM == kNoTrans) (*this) = beta*(*this) + alpha * M * M^T, or (if transM == kTr...
Definition: sp-matrix.cc:1110
Packed symetric matrix class.
Definition: matrix-common.h:62
void Scale(Real c)
void AddRowSumMat(Real alpha, const MatrixBase< Real > &M, Real beta=1.0)
Does *this = alpha * (sum of rows of M) + beta * *this.
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
void Eig(VectorBase< Real > *s, MatrixBase< Real > *P=NULL) const
Solves the symmetric eigenvalue problem: at end we should have (*this) = P * diag(s) * P^T...
Definition: qr.cc:433
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
void AddVec2(const Real alpha, const VectorBase< OtherReal > &v)
rank-one update, this <– this + alpha v v&#39;
Definition: sp-matrix.cc:946
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
void Scale(Real alpha)
Multiplies all elements by this constant.
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
void Resize(MatrixIndexT nRows, MatrixResizeType resize_type=kSetZero)
Definition: sp-matrix.h:81
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
void SortSvd(VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt, bool sort_on_absolute_value)
Function to ensure that SVD is sorted.

◆ EventTypeToString()

std::string EventTypeToString ( const EventType evec)

Definition at line 253 of file event-map.cc.

Referenced by FilterStatsByKey(), MakeEventPair(), SplitStatsByKey(), and SplitStatsByMap().

253  {
254  std::stringstream ss;
255  EventType::const_iterator iter = evec.begin(), end = evec.end();
256  std::string sep = "";
257  for (; iter != end; ++iter) {
258  ss << sep << iter->first <<":"<<iter->second;
259  sep = " ";
260  }
261  return ss.str();
262 }

◆ Exp() [1/2]

◆ Exp() [2/2]

float kaldi::Exp ( float  x)
inline

Definition at line 85 of file kaldi-math.h.

References Exp().

85 { return expf(x); }

◆ ExpectOneOrTwoTokens()

void ExpectOneOrTwoTokens ( std::istream &  is,
bool  binary,
const std::string &  token1,
const std::string &  token2 
)

This function is like ExpectToken but for two tokens, and it will either accept token1 and then token2, or just token2.

This is useful in Read functions where the first token may already have been consumed.

Definition at line 536 of file text-utils.cc.

References ExpectToken(), KALDI_ASSERT, KALDI_ERR, and ReadToken().

Referenced by PnormComponent::Read(), DistributeComponent::Read(), DistributeComponentPrecomputedIndexes::Read(), RestrictedAttentionComponent::Read(), ElementwiseProductComponent::Read(), RestrictedAttentionComponent::PrecomputedIndexes::Read(), BatchNormComponent::Read(), StatisticsExtractionComponent::Read(), ConvolutionModel::Read(), TimeHeightConvolutionComponent::PrecomputedIndexes::Read(), StatisticsExtractionComponentPrecomputedIndexes::Read(), ConvolutionComputation::Read(), StatisticsPoolingComponent::Read(), StatisticsPoolingComponentPrecomputedIndexes::Read(), BackpropTruncationComponent::Read(), MaxpoolingComponent::Read(), TdnnComponent::PrecomputedIndexes::Read(), BackpropTruncationComponentPrecomputedIndexes::Read(), NonlinearComponent::Read(), DropoutMaskComponent::Read(), GeneralDropoutComponent::Read(), GeneralDropoutComponentPrecomputedIndexes::Read(), FixedAffineComponent::Read(), SpecAugmentTimeMaskComponent::Read(), SumGroupComponent::Read(), SpecAugmentTimeMaskComponentPrecomputedIndexes::Read(), FixedScaleComponent::Read(), FixedBiasComponent::Read(), NoOpComponent::Read(), SumBlockComponent::Read(), ClipGradientComponent::Read(), and PermuteComponent::Read().

538  {
539  KALDI_ASSERT(token1 != token2);
540  std::string temp;
541  ReadToken(is, binary, &temp);
542  if (temp == token1) {
543  ExpectToken(is, binary, token2);
544  } else {
545  if (temp != token2) {
546  KALDI_ERR << "Expecting token " << token1 << " or " << token2
547  << " but got " << temp;
548  }
549  }
550 }
void ReadToken(std::istream &is, bool binary, std::string *str)
ReadToken gets the next token and puts it in str (exception on failure).
Definition: io-funcs.cc:154
void ExpectToken(std::istream &is, bool binary, const char *token)
ExpectToken tries to read in the given token, and throws an exception on failure. ...
Definition: io-funcs.cc:191
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ExtendWaveWithSilence()

void ExtendWaveWithSilence ( const Vector< BaseFloat > &  wav_in,
BaseFloat  samp_rate,
Vector< BaseFloat > *  wav_out,
BaseFloat  sil_search_len,
BaseFloat  sil_extract_len,
BaseFloat  sil_extract_shift 
)

Definition at line 152 of file extend-wav-with-silence.cc.

References VectorBase< Real >::AddVecVec(), VectorBase< Real >::Dim(), FindQuietestSegment(), rnnlm::i, KALDI_ASSERT, M_2PI, and VectorBase< Real >::Range().

Referenced by main().

157  {
158  Vector<BaseFloat> quietest_seg;
159  FindQuietestSegment(wav_in, samp_rate, &quietest_seg,
160  sil_search_len, sil_extract_len, sil_extract_shift);
161 
162  int32 window_size = quietest_seg.Dim(),
163  window_size_half = window_size / 2;
164  KALDI_ASSERT(window_size > 0);
165  Vector<BaseFloat> window(window_size);
166  Vector<BaseFloat> windowed_silence(window_size);
167  Vector<BaseFloat> half_window(window_size_half);
168  for(int32 i = 0; i < window.Dim(); i++){
169  BaseFloat i_fl = static_cast<BaseFloat>(i);
170  window(i) = 0.54 - 0.46*cos(M_2PI * i_fl / (window_size-1));
171  }
172  half_window = window.Range(window_size_half, window_size_half);
173  windowed_silence.AddVecVec(1.0, window, quietest_seg, 0.0);
174 
175  wav_out->Range(0, wav_in.Dim()).CopyFromVec(wav_in);
176  SubVector<BaseFloat> wav_ext(*wav_out, wav_in.Dim() - window_size_half,
177  wav_out->Dim() - wav_in.Dim() + window_size_half);
178  for(int32 i = 0; i < window_size_half; i++) // windowing the first half window
179  wav_ext(i) *= half_window(i);
180 
181  int32 tmp_offset = 0;
182  for(; tmp_offset + window_size < wav_ext.Dim();) {
183  wav_ext.Range(tmp_offset, window_size).AddVec(1.0, windowed_silence);
184  tmp_offset += window_size_half;
185  }
186 
187  for(int32 i = tmp_offset; i < wav_ext.Dim(); i++)
188  wav_ext(i) += windowed_silence(i-tmp_offset);
189 
190 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define M_2PI
Definition: kaldi-math.h:52
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
void FindQuietestSegment(const Vector< BaseFloat > &wav_in, BaseFloat samp_rate, Vector< BaseFloat > *wav_sil, BaseFloat search_dur=0.5, BaseFloat seg_dur=0.1, BaseFloat seg_shift_dur=0.05)

◆ ExtractObjectRange() [1/6]

template bool kaldi::ExtractObjectRange ( const CompressedMatrix ,
const std::string &  ,
Matrix< float > *   
)

◆ ExtractObjectRange() [2/6]

template bool kaldi::ExtractObjectRange ( const CompressedMatrix ,
const std::string &  ,
Matrix< double > *   
)

◆ ExtractObjectRange() [3/6]

template bool kaldi::ExtractObjectRange ( const Matrix< double > &  ,
const std::string &  ,
Matrix< double > *   
)

◆ ExtractObjectRange() [4/6]

template bool kaldi::ExtractObjectRange ( const Matrix< float > &  ,
const std::string &  ,
Matrix< float > *   
)

◆ ExtractObjectRange() [5/6]

template bool kaldi::ExtractObjectRange ( const Vector< double > &  ,
const std::string &  ,
Vector< double > *   
)

◆ ExtractObjectRange() [6/6]

template bool kaldi::ExtractObjectRange ( const Vector< float > &  ,
const std::string &  ,
Vector< float > *   
)

◆ Factorize()

void kaldi::Factorize ( m,
std::vector< I > *  factors 
)

Definition at line 325 of file kaldi-math.h.

References rnnlm::i, rnnlm::j, and KALDI_ASSERT.

Referenced by ComplexFft(), and UnitTestFactorizeTpl().

325  {
326  // Splits a number into its prime factors, in sorted order from
327  // least to greatest, with duplication. A very inefficient
328  // algorithm, which is mainly intended for use in the
329  // mixed-radix FFT computation (where we assume most factors
330  // are small).
331  KALDI_ASSERT(factors != NULL);
332  KALDI_ASSERT(m >= 1); // Doesn't work for zero or negative numbers.
333  factors->clear();
334  I small_factors[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
335 
336  // First try small factors.
337  for (I i = 0; i < 10; i++) {
338  if (m == 1) return; // We're done.
339  while (m % small_factors[i] == 0) {
340  m /= small_factors[i];
341  factors->push_back(small_factors[i]);
342  }
343  }
344  // Next try all odd numbers starting from 31.
345  for (I j = 31;; j += 2) {
346  if (m == 1) return;
347  while (m % j == 0) {
348  m /= j;
349  factors->push_back(j);
350  }
351  }
352 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ FakeStatsForSomeDims()

void FakeStatsForSomeDims ( const std::vector< int32 > &  dims,
MatrixBase< double > *  stats 
)

Modify the stats so that for some dimensions (specified in "dims"), we replace them with "fake" stats that have zero mean and unit variance; this is done to disable CMVN for those dimensions.

Definition at line 168 of file cmvn.cc.

References count, rnnlm::d, rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::NumRows().

Referenced by OnlineCmvn::GetFrame(), and main().

169  {
170  KALDI_ASSERT(stats->NumRows() == 2 && stats->NumCols() > 1);
171  int32 dim = stats->NumCols() - 1;
172  double count = (*stats)(0, dim);
173  for (size_t i = 0; i < dims.size(); i++) {
174  int32 d = dims[i];
175  KALDI_ASSERT(d >= 0 && d < dim);
176  (*stats)(0, d) = 0.0;
177  (*stats)(1, d) = count;
178  }
179 }
kaldi::int32 int32
const size_t count
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ FFTbasedBlockConvolveSignals()

void FFTbasedBlockConvolveSignals ( const Vector< BaseFloat > &  filter,
Vector< BaseFloat > *  signal 
)

Definition at line 77 of file signal.cc.

References SplitRadixRealFft< Real >::Compute(), VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Data(), VectorBase< Real >::Dim(), ElementwiseProductOfFft(), KALDI_VLOG, kCopyData, VectorBase< Real >::Range(), Vector< Real >::Resize(), RoundUpToNearestPowerOfTwo(), VectorBase< Real >::Scale(), and VectorBase< Real >::SetZero().

Referenced by ComputeEarlyReverbEnergy(), DoReverberation(), and UnitTestFFTbasedBlockConvolution().

77  {
78  int32 signal_length = signal->Dim();
79  int32 filter_length = filter.Dim();
80  int32 output_length = signal_length + filter_length - 1;
81  signal->Resize(output_length, kCopyData);
82 
83  KALDI_VLOG(1) << "Length of the filter is " << filter_length;
84 
85  int32 fft_length = RoundUpToNearestPowerOfTwo(4 * filter_length);
86  KALDI_VLOG(1) << "Best FFT length is " << fft_length;
87 
88  int32 block_length = fft_length - filter_length + 1;
89  KALDI_VLOG(1) << "Block size is " << block_length;
90  SplitRadixRealFft<BaseFloat> srfft(fft_length);
91 
92  Vector<BaseFloat> filter_padded(fft_length);
93  filter_padded.Range(0, filter_length).CopyFromVec(filter);
94  srfft.Compute(filter_padded.Data(), true);
95 
96  Vector<BaseFloat> temp_pad(filter_length - 1);
97  temp_pad.SetZero();
98  Vector<BaseFloat> signal_block_padded(fft_length);
99 
100  for (int32 po = 0; po < output_length; po += block_length) {
101  // get a block of the signal
102  int32 process_length = std::min(block_length, output_length - po);
103  signal_block_padded.SetZero();
104  signal_block_padded.Range(0, process_length).CopyFromVec(signal->Range(po, process_length));
105 
106  srfft.Compute(signal_block_padded.Data(), true);
107 
108  ElementwiseProductOfFft(filter_padded, &signal_block_padded);
109 
110  srfft.Compute(signal_block_padded.Data(), false);
111  signal_block_padded.Scale(1.0 / fft_length);
112 
113  // combine the block
114  if (po + block_length < output_length) { // current block is not the last block
115  signal->Range(po, block_length).CopyFromVec(signal_block_padded.Range(0, block_length));
116  signal->Range(po, filter_length - 1).AddVec(1.0, temp_pad);
117  temp_pad.CopyFromVec(signal_block_padded.Range(block_length, filter_length - 1));
118  } else {
119  signal->Range(po, output_length - po).CopyFromVec(
120  signal_block_padded.Range(0, output_length - po));
121  if (filter_length - 1 < output_length - po)
122  signal->Range(po, filter_length - 1).AddVec(1.0, temp_pad);
123  else
124  signal->Range(po, output_length - po).AddVec(1.0, temp_pad.Range(0, output_length - po));
125  }
126  }
127 }
kaldi::int32 int32
int32 RoundUpToNearestPowerOfTwo(int32 n)
Definition: kaldi-math.cc:32
void ElementwiseProductOfFft(const Vector< BaseFloat > &a, Vector< BaseFloat > *b)
Definition: signal.cc:26
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ FFTbasedConvolveSignals()

void FFTbasedConvolveSignals ( const Vector< BaseFloat > &  filter,
Vector< BaseFloat > *  signal 
)

Definition at line 50 of file signal.cc.

References SplitRadixRealFft< Real >::Compute(), VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Data(), VectorBase< Real >::Dim(), ElementwiseProductOfFft(), KALDI_VLOG, VectorBase< Real >::Range(), Vector< Real >::Resize(), RoundUpToNearestPowerOfTwo(), and VectorBase< Real >::Scale().

Referenced by UnitTestFFTbasedBlockConvolution(), and UnitTestFFTbasedConvolution().

50  {
51  int32 signal_length = signal->Dim();
52  int32 filter_length = filter.Dim();
53  int32 output_length = signal_length + filter_length - 1;
54 
55  int32 fft_length = RoundUpToNearestPowerOfTwo(output_length);
56  KALDI_VLOG(1) << "fft_length for full signal convolution is " << fft_length;
57 
58  SplitRadixRealFft<BaseFloat> srfft(fft_length);
59 
60  Vector<BaseFloat> filter_padded(fft_length);
61  filter_padded.Range(0, filter_length).CopyFromVec(filter);
62  srfft.Compute(filter_padded.Data(), true);
63 
64  Vector<BaseFloat> signal_padded(fft_length);
65  signal_padded.Range(0, signal_length).CopyFromVec(*signal);
66  srfft.Compute(signal_padded.Data(), true);
67 
68  ElementwiseProductOfFft(filter_padded, &signal_padded);
69 
70  srfft.Compute(signal_padded.Data(), false);
71  signal_padded.Scale(1.0 / fft_length);
72 
73  signal->Resize(output_length);
74  signal->CopyFromVec(signal_padded.Range(0, output_length));
75 }
kaldi::int32 int32
int32 RoundUpToNearestPowerOfTwo(int32 n)
Definition: kaldi-math.cc:32
void ElementwiseProductOfFft(const Vector< BaseFloat > &a, Vector< BaseFloat > *b)
Definition: signal.cc:26
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ FilterMatrixRows() [1/2]

template void kaldi::FilterMatrixRows ( const Matrix< float > &  in,
const std::vector< bool > &  keep_rows,
Matrix< float > *  out 
)

◆ FilterMatrixRows() [2/2]

template void kaldi::FilterMatrixRows ( const Matrix< double > &  in,
const std::vector< bool > &  keep_rows,
Matrix< double > *  out 
)

◆ FilterSparseMatrixRows() [1/2]

template void kaldi::FilterSparseMatrixRows ( const SparseMatrix< float > &  in,
const std::vector< bool > &  keep_rows,
SparseMatrix< float > *  out 
)

◆ FilterSparseMatrixRows() [2/2]

template void kaldi::FilterSparseMatrixRows ( const SparseMatrix< double > &  in,
const std::vector< bool > &  keep_rows,
SparseMatrix< double > *  out 
)

◆ FindQuietestSegment()

void FindQuietestSegment ( const Vector< BaseFloat > &  wav_in,
BaseFloat  samp_rate,
Vector< BaseFloat > *  wav_sil,
BaseFloat  search_dur = 0.5,
BaseFloat  seg_dur = 0.1,
BaseFloat  seg_shift_dur = 0.05 
)

Definition at line 195 of file extend-wav-with-silence.cc.

References VectorBase< Real >::Dim(), KALDI_ASSERT, KALDI_WARN, VectorBase< Real >::Range(), and VecVec().

Referenced by ExtendWaveWithSilence().

200  {
201  KALDI_ASSERT(seg_dur < search_dur);
202 
203  int32 search_len = (int32) (search_dur * samp_rate),
204  seg_len = (int32) (seg_dur * samp_rate),
205  seg_shift = (int32) (seg_shift_dur *samp_rate),
206  start = 0;
207  double min_energy;
208  Vector<BaseFloat> wav_min_energy;
209  Vector<BaseFloat> seg_tmp(wav_in.Range(0, seg_len));
210  wav_min_energy = seg_tmp;
211  min_energy = VecVec(seg_tmp, seg_tmp);
212  for(start = 0; start + seg_len < search_len; ){
213  SubVector<BaseFloat> seg_this(wav_in, start, seg_len);
214  seg_tmp = seg_this;
215  double energy_this = VecVec(seg_this, seg_this);
216  if(energy_this < min_energy && energy_this > 0.0){
217  min_energy = energy_this;
218  wav_min_energy = seg_tmp;
219  }
220  start += seg_shift;
221  }
222 
223  for(start = wav_in.Dim() - search_len; start + seg_len < wav_in.Dim(); ){
224  SubVector<BaseFloat> seg_this(wav_in, start, seg_len);
225  seg_tmp = seg_this;
226  double energy_this = VecVec(seg_this, seg_this);
227  if(energy_this < min_energy && energy_this > 0.0){
228  min_energy = energy_this;
229  wav_min_energy = seg_tmp;
230  }
231  start += seg_shift;
232  }
233 
234  if (min_energy == 0.0) {
235  KALDI_WARN << "Zero energy silence being used.";
236  }
237  *wav_sil = wav_min_energy;
238 }
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ FmllrAuxfGradient()

BaseFloat FmllrAuxfGradient ( const MatrixBase< BaseFloat > &  xform,
const AffineXformStats stats,
MatrixBase< BaseFloat > *  grad_out 
)

Returns the (diagonal-GMM) FMLLR auxiliary function value given the transform and the stats.

Definition at line 510 of file fmllr-diag-gmm.cc.

References MatrixBase< Real >::AddMat(), VectorBase< Real >::AddSpVec(), AffineXformStats::beta_, MatrixBase< Real >::CopyFromMat(), MatrixBase< Real >::CopyRowFromVec(), rnnlm::d, AffineXformStats::G_, AffineXformStats::K_, kNoTrans, kTrans, MatrixBase< Real >::LogDet(), MatrixBase< Real >::Range(), MatrixBase< Real >::Row(), MatrixBase< Real >::Scale(), TraceMatMat(), and VecVec().

Referenced by ComputeFmllrLogDet().

514  {
515  int32 dim = static_cast<int32>(stats.G_.size());
516  Matrix<double> xform_d(xform);
517  Vector<double> xform_row_g(dim + 1);
518  SubMatrix<double> A(xform_d, 0, dim, 0, dim);
519  double obj = stats.beta_ * A.LogDet() +
520  TraceMatMat(xform_d, stats.K_, kTrans);
521  Matrix<double> S(dim, dim + 1);
522  for (int32 d = 0; d < dim; d++) {
523  xform_row_g.AddSpVec(1.0, stats.G_[d], xform_d.Row(d), 0.0);
524  obj -= 0.5 * VecVec(xform_row_g, xform_d.Row(d));
525  S.CopyRowFromVec(xform_row_g, d);
526  }
527 
528  // Compute the gradient: P = \beta [(A^{-1})^{T} , 0] + K - S
529  // grad_out->Resize(dim, dim + 1);
530  Matrix<double> tmp_grad(dim, dim + 1);
531  tmp_grad.Range(0, dim, 0, dim).CopyFromMat(A);
532  tmp_grad.Range(0, dim, 0, dim).Invert();
533  tmp_grad.Range(0, dim, 0, dim).Transpose();
534  tmp_grad.Scale(stats.beta_);
535  tmp_grad.AddMat(-1.0, S, kNoTrans);
536  tmp_grad.AddMat(1.0, stats.K_, kNoTrans);
537  grad_out->CopyFromMat(tmp_grad, kNoTrans);
538 
539  return obj;
540 }
kaldi::int32 int32
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ FmllrAuxFuncDiagGmm() [1/2]

float FmllrAuxFuncDiagGmm ( const MatrixBase< float > &  xform,
const AffineXformStats stats 
)

Returns the (diagonal-GMM) FMLLR auxiliary function value given the transform and the stats.

Definition at line 481 of file fmllr-diag-gmm.cc.

References VectorBase< Real >::AddSpVec(), AffineXformStats::beta_, rnnlm::d, AffineXformStats::G_, AffineXformStats::K_, kTrans, MatrixBase< Real >::LogDet(), MatrixBase< Real >::Row(), TraceMatMat(), and VecVec().

Referenced by ComputeFmllrLogDet(), ComputeFmllrMatrixDiagGmmDiagonal(), ComputeFmllrMatrixDiagGmmFull(), LinearVtln::ComputeTransform(), and BasisFmllrEstimate::ComputeTransform().

482  {
483  int32 dim = static_cast<int32>(stats.G_.size());
484  Matrix<double> xform_d(xform);
485  Vector<double> xform_row_g(dim + 1);
486  SubMatrix<double> A(xform_d, 0, dim, 0, dim);
487  double obj = stats.beta_ * A.LogDet() +
488  TraceMatMat(xform_d, stats.K_, kTrans);
489  for (int32 d = 0; d < dim; d++) {
490  xform_row_g.AddSpVec(1.0, stats.G_[d], xform_d.Row(d), 0.0);
491  obj -= 0.5 * VecVec(xform_row_g, xform_d.Row(d));
492  }
493  return obj;
494 }
kaldi::int32 int32
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ FmllrAuxFuncDiagGmm() [2/2]

double FmllrAuxFuncDiagGmm ( const MatrixBase< double > &  xform,
const AffineXformStats stats 
)

Definition at line 496 of file fmllr-diag-gmm.cc.

References VectorBase< Real >::AddSpVec(), AffineXformStats::beta_, rnnlm::d, AffineXformStats::G_, AffineXformStats::K_, kTrans, MatrixBase< Real >::LogDet(), MatrixBase< Real >::Row(), TraceMatMat(), and VecVec().

497  {
498  int32 dim = static_cast<int32>(stats.G_.size());
499  Vector<double> xform_row_g(dim + 1);
500  SubMatrix<double> A(xform, 0, dim, 0, dim);
501  double obj = stats.beta_ * A.LogDet() +
502  TraceMatMat(xform, stats.K_, kTrans);
503  for (int32 d = 0; d < dim; d++) {
504  xform_row_g.AddSpVec(1.0, stats.G_[d], xform.Row(d), 0.0);
505  obj -= 0.5 * VecVec(xform_row_g, xform.Row(d));
506  }
507  return obj;
508 }
kaldi::int32 int32
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ FmllrInnerUpdate()

void FmllrInnerUpdate ( SpMatrix< double > &  inv_G,
VectorBase< double > &  k,
double  beta,
int32  row,
MatrixBase< double > *  transform 
)

This function does one row of the inner-loop fMLLR transform update.

We export it because it's needed in the RawFmllr code. Here, if inv_G is the inverse of the G matrix indexed by this row, and k is the corresponding row of the K matrix.

Definition at line 193 of file fmllr-diag-gmm.cc.

References VectorBase< Real >::AddSpVec(), VectorBase< Real >::AddVec(), MatrixBase< Real >::CopyFromMat(), MatrixBase< Real >::Invert(), KALDI_ASSERT, kTrans, Log(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), VectorBase< Real >::Range(), MatrixBase< Real >::Range(), MatrixBase< Real >::Row(), VectorBase< Real >::Scale(), and VecVec().

Referenced by ComputeFmllrLogDet(), ComputeFmllrMatrixDiagGmmFull(), and FmllrRawAccs::Update().

197  {
198  int32 dim = transform->NumRows();
199  KALDI_ASSERT(transform->NumCols() == dim + 1);
200  KALDI_ASSERT(row >= 0 && row < dim);
201 
202  double logdet;
203  // Calculating the matrix of cofactors (transpose of adjugate)
204  Matrix<double> cofact_mat(dim, dim);
205  cofact_mat.CopyFromMat(transform->Range(0, dim, 0, dim), kTrans);
206  cofact_mat.Invert(&logdet);
207  // Removed this step because it's not necessary and could lead to
208  // under/overflow [Dan]
209  // cofact_mat.Scale(exp(logdet));
210 
211  // The extended cofactor vector for the current row
212  Vector<double> cofact_row(dim + 1);
213  cofact_row.Range(0, dim).CopyRowFromMat(cofact_mat, row);
214  cofact_row(dim) = 0;
215  Vector<double> cofact_row_invg(dim + 1);
216  cofact_row_invg.AddSpVec(1.0, inv_G, cofact_row, 0.0);
217 
218  // Solve the quadratic equation for step size
219  double e1 = VecVec(cofact_row_invg, cofact_row);
220  double e2 = VecVec(cofact_row_invg, k);
221  double discr = std::sqrt(e2 * e2 + 4 * e1 * beta);
222  double alpha1 = (-e2 + discr) / (2 * e1);
223  double alpha2 = (-e2 - discr) / (2 * e1);
224  double auxf1 = beta * Log(std::abs(alpha1 * e1 + e2)) -
225  0.5 * alpha1 * alpha1 * e1;
226  double auxf2 = beta * Log(std::abs(alpha2 * e1 + e2)) -
227  0.5 * alpha2 * alpha2 * e1;
228  double alpha = (auxf1 > auxf2) ? alpha1 : alpha2;
229 
230  // Update transform row: w_d = (\alpha cofact_d + k_d) G_d^{-1}
231  cofact_row.Scale(alpha);
232  cofact_row.AddVec(1.0, k);
233  transform->Row(row).AddSpVec(1.0, inv_G, cofact_row, 0.0);
234 }
kaldi::int32 int32
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ FrameLevelLpp()

void kaldi::FrameLevelLpp ( const SubVector< BaseFloat > &  prob_row,
const std::vector< std::set< int32 > > &  pdf2phones,
const std::vector< int32 > *  phone_map,
Vector< BaseFloat > *  out_frame_level_lpp 
)

FrameLevelLpp compute a log posterior for pure-phones by sum the posterior of the states belonging to those triphones whose current phone is the canonical phone:

p(p|o_t) = {s p} p(s|o_t),

where s is the senone label, {s|s p} is the states belonging to those riphones whose current phone is the canonical phone p.

Definition at line 76 of file compute-gop.cc.

References VectorBase< Real >::ApplyLog(), VectorBase< Real >::Dim(), rnnlm::i, and KALDI_ASSERT.

Referenced by main().

79  {
80  for (int32 i = 0; i < prob_row.Dim(); i++) {
81  std::set<int32> dest_idxs;
82  for (int32 ph : pdf2phones.at(i)) {
83  dest_idxs.insert((phone_map != NULL) ? (*phone_map)[ph] - 1 : ph - 1);
84  }
85 
86  for (int32 idx : dest_idxs) {
87  KALDI_ASSERT(idx < out_frame_level_lpp->Dim());
88  (*out_frame_level_lpp)(idx) += prob_row(i);
89  }
90  }
91  out_frame_level_lpp->ApplyLog();
92 }
kaldi::int32 int32
void ApplyLog()
Apply natural log to all elements.
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Gcd()

I kaldi::Gcd ( m,
n 
)

Definition at line 297 of file kaldi-math.h.

References KALDI_ASSERT, KALDI_ERR, and rnnlm::n.

Referenced by ClusterKMeansOnce(), ConvolutionModel::ComputeDerived(), kaldi::nnet3::time_height_convolution::FindGcdOfDifferences(), RestrictedAttentionComponent::GetComputationStructure(), Lcm(), LinearResample::LinearResample(), kaldi::nnet3::time_height_convolution::PadComputationInputTime(), and UnitTestGcdLcmTpl().

297  {
298  if (m == 0 || n == 0) {
299  if (m == 0 && n == 0) { // gcd not defined, as all integers are divisors.
300  KALDI_ERR << "Undefined GCD since m = 0, n = 0.";
301  }
302  return (m == 0 ? (n > 0 ? n : -n) : ( m > 0 ? m : -m));
303  // return absolute value of whichever is nonzero
304  }
305  // could use compile-time assertion
306  // but involves messing with complex template stuff.
307  KALDI_ASSERT(std::numeric_limits<I>::is_integer);
308  while (1) {
309  m %= n;
310  if (m == 0) return (n > 0 ? n : -n);
311  n %= m;
312  if (n == 0) return (m > 0 ? m : -m);
313  }
314 }
struct rnnlm::@11::@12 n
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ generate_features()

static void kaldi::generate_features ( cova_type  covariance_type,
size_t  n_gaussians,
size_t  dim,
Matrix< BaseFloat > &  trans_mat,
size_t  frames_per_gaussian,
std::vector< Vector< BaseFloat > *> &  train_feats,
std::vector< Vector< BaseFloat > *> &  adapt_feats 
)
static

Definition at line 64 of file regtree-fmllr-diag-gmm-test.cc.

References MatrixBase< Real >::AddMatMat(), VectorBase< Real >::AddMatVec(), VectorBase< Real >::CopyColFromMat(), MatrixBase< Real >::CopyFromMat(), rnnlm::d, diag, Exp(), full, rnnlm::i, MatrixBase< Real >::Invert(), rnnlm::j, kNoTrans, RandFullCova(), RandGauss(), MatrixBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::SetZero().

Referenced by UnitTestRegtreeFmllrDiagGmm().

71  {
72  // compute inverse of the transformation matrix
73  Matrix<BaseFloat> inv_trans_mat(dim, dim);
74  inv_trans_mat.CopyFromMat(trans_mat, kNoTrans);
75  inv_trans_mat.Invert();
76  // the untransformed means are random
77  Matrix<BaseFloat> untransformed_means(dim, n_gaussians);
78  untransformed_means.SetRandn();
79  untransformed_means.Scale(10);
80 
81  // the actual means result from
82  // transformation with inv_trans_mat
83  Matrix<BaseFloat> actual_means(dim, n_gaussians);
84 
85  // actual_means = inv_trans_mat * untransformed_means
86  actual_means.AddMatMat(1.0, inv_trans_mat, kNoTrans,
87  untransformed_means, kNoTrans, 0.0);
88 
89  size_t train_counter = 0;
90 
91  // temporary variables
92  Vector<BaseFloat> randomvec(dim);
93  Matrix<BaseFloat> Sj(dim, dim);
94 
95  // loop over all gaussians
96  for (size_t j = 0; j < n_gaussians; j++) {
97  if (covariance_type == diag) {
98  // random diagonal covariance for gaussian j
99  Sj.SetZero();
100  for (size_t d = 0; d < dim; d++) {
101  Sj(d, d) = 2*Exp(RandGauss());
102  }
103  }
104  if (covariance_type == full) {
105  // random full covariance for gaussian j
106  RandFullCova(&Sj);
107  }
108  // compute inv_trans_mat * Sj
109  Matrix<BaseFloat> tmp_matrix(dim, dim);
110  tmp_matrix.AddMatMat(1.0, inv_trans_mat, kNoTrans, Sj, kNoTrans, 0.0);
111 
112  // compute features
113  for (size_t i = 0; i < frames_per_gaussian; i++) {
114  train_feats[train_counter] = new Vector<BaseFloat>(dim);
115  adapt_feats[train_counter] = new Vector<BaseFloat>(dim);
116 
117  // initalize feature vector with mean of class j
118  train_feats[train_counter]->CopyColFromMat(untransformed_means, j);
119  adapt_feats[train_counter]->CopyColFromMat(actual_means, j);
120 
121  // determine random vector and
122  // multiply the random vector with SJ
123  // and add it to train_feats:
124  // train_feats = train_feats + SJ * random
125  // for adapt_feats we include the invtrans_mat:
126  // adapt_feats = adapt_feats + invtrans_mat * SJ * random
127  for (size_t d = 0; d < dim; d++) {
128  randomvec(d) = RandGauss();
129  }
130  train_feats[train_counter]->AddMatVec(1.0, Sj, kNoTrans,
131  randomvec, 1.0);
132  adapt_feats[train_counter]->AddMatVec(1.0, tmp_matrix, kNoTrans,
133  randomvec, 1.0);
134  train_counter++;
135  }
136  }
137  return;
138 }
double Exp(double x)
Definition: kaldi-math.h:83
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
static void RandFullCova(Matrix< BaseFloat > *matrix)

◆ GenerateActivePaths()

bool kaldi::GenerateActivePaths ( const KwsLexicographicFst proxy,
std::vector< ActivePath > *  paths,
KwsLexicographicFst::StateId  cur_state,
std::vector< KwsLexicographicArc::Label >  cur_path,
KwsLexicographicArc::Weight  cur_weight 
)

Definition at line 90 of file kws-search.cc.

References ActivePath::last, ActivePath::path, fst::Times(), and ActivePath::weight.

Referenced by OutputDetailedStatistics().

94  {
95  for (fst::ArcIterator<KwsLexicographicFst> aiter(proxy, cur_state);
96  !aiter.Done(); aiter.Next()) {
97  const Arc &arc = aiter.Value();
98  Weight temp_weight = Times(arc.weight, cur_weight);
99 
100  cur_path.push_back(arc.ilabel);
101 
102  if ( arc.olabel != 0 ) {
103  ActivePath path;
104  path.path = cur_path;
105  path.weight = temp_weight;
106  path.last = arc.olabel;
107  paths->push_back(path);
108  } else {
109  GenerateActivePaths(proxy, paths,
110  arc.nextstate, cur_path, temp_weight);
111  }
112  cur_path.pop_back();
113  }
114 
115  return true;
116 }
KwsLexicographicArc::Weight weight
Definition: kws-search.cc:86
LatticeWeightTpl< FloatType > Times(const LatticeWeightTpl< FloatType > &w1, const LatticeWeightTpl< FloatType > &w2)
KwsLexicographicArc::Label last
Definition: kws-search.cc:87
bool GenerateActivePaths(const KwsLexicographicFst &proxy, std::vector< ActivePath > *paths, KwsLexicographicFst::StateId cur_state, std::vector< KwsLexicographicArc::Label > cur_path, KwsLexicographicArc::Weight cur_weight)
Definition: kws-search.cc:90
fst::StdArc::Weight Weight
std::vector< KwsLexicographicArc::Label > path
Definition: kws-search.cc:85

◆ GenerateCompactLatticeRandomly()

void kaldi::GenerateCompactLatticeRandomly ( const std::vector< int32 > &  alignment,
const std::vector< int32 > &  words,
CompactLattice clat 
)

Definition at line 132 of file word-align-lattice-lexicon-test.cc.

References rnnlm::i, LatticeWeightTpl< BaseFloat >::One(), CompactLatticeWeightTpl< WeightType, IntType >::One(), and RandInt().

Referenced by TestWordAlignLatticeLexicon().

134  {
135  clat->DeleteStates();
136  clat->AddState();
137  clat->SetStart(0);
138  int32 cur_state = 0;
139  size_t word_start = 0, alignment_start = 0,
140  num_words = words.size(), num_transition_ids = alignment.size();
141  for (; word_start < num_words; word_start++) {
142  int32 word = words[word_start];
143  int32 ali_length = RandInt(0, num_transition_ids - alignment_start);
144  std::vector<int32> this_ali(ali_length);
145  for (int32 i = 0; i < ali_length; i++)
146  this_ali[i] = alignment[alignment_start + i];
147  alignment_start += ali_length;
148  CompactLatticeWeight weight(LatticeWeight::One(), this_ali);
149  int32 ilabel = word;
150  int32 next_state = clat->AddState();
151  CompactLatticeArc arc(ilabel, ilabel, weight, next_state);
152  clat->AddArc(cur_state, arc);
153  cur_state = next_state;
154  }
155  if (alignment_start < alignment.size()) {
156  int32 ali_length = num_transition_ids - alignment_start;
157  std::vector<int32> this_ali(ali_length);
158  for (int32 i = 0; i < ali_length; i++)
159  this_ali[i] = alignment[alignment_start + i];
160  alignment_start += ali_length;
161  CompactLatticeWeight weight(LatticeWeight::One(), this_ali);
162  int32 ilabel = 0;
163  int32 next_state = clat->AddState();
164  CompactLatticeArc arc(ilabel, ilabel, weight, next_state);
165  clat->AddArc(cur_state, arc);
166  cur_state = next_state;
167  }
168  clat->SetFinal(cur_state, CompactLatticeWeight::One());
169 }
int32 words[kMaxOrder]
kaldi::int32 int32
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42
CompactLatticeWeightTpl< LatticeWeight, int32 > CompactLatticeWeight
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GenerateLexicon()

void kaldi::GenerateLexicon ( const std::vector< int32 > &  phones,
bool  allow_zero_words,
bool  allow_empty_word,
bool  allow_multiple_prons,
std::vector< std::vector< int32 > > *  lexicon 
)

Definition at line 32 of file word-align-lattice-lexicon-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, RandInt(), and SortAndUniq().

Referenced by TestWordAlignLatticeLexicon().

36  {
37  KALDI_ASSERT(!phones.empty());
38  lexicon->clear();
39  int32 num_words = RandInt(1, 20);
40  for (int32 word = 1; word <= num_words; word++) {
41  int32 num_prons = RandInt(1, (allow_multiple_prons ? 2 : 1));
42  bool is_zero_word = allow_zero_words && (RandInt(1, 5) == 1);
43 
44  for (int32 j = 0; j < num_prons; j++) {
45  // don't allow empty pron if this word isn't labeled in the lattice (zero word,
46  // like optional silence). This doesn't make sense.
47  int32 pron_length = RandInt(((allow_empty_word && !is_zero_word) ? 0 : 1),
48  4);
49  std::vector<int32> this_entry;
50  this_entry.push_back(is_zero_word ? 0 : word);
51  this_entry.push_back(word);
52  for (int32 p = 0; p < pron_length; p++)
53  this_entry.push_back(phones[RandInt(0, phones.size() - 1)]);
54  lexicon->push_back(this_entry);
55  }
56  }
57  SortAndUniq(lexicon);
58  // randomize the order.
59  std::random_shuffle(lexicon->begin(), lexicon->end());
60 
61 
62  for (size_t i = 0; i < lexicon->size(); i++) {
63  if ((*lexicon)[i].size() > 2) {
64  // ok, this lexicon has at least one nonempty word: potentially OK. Do
65  // further check that the info object doesn't complain.
66  try {
67  WordAlignLatticeLexiconInfo info(*lexicon);
68  return; // OK, we're satisfied with this lexicon.
69  } catch (...) {
70  break; // will re-try, see below.
71  }
72  }
73  }
74  // there were no nonempty words in the lexicon -> try again.
75  // recursing is the easiest way.
76  GenerateLexicon(phones, allow_zero_words, allow_empty_word, allow_multiple_prons,
77  lexicon);
78 
79 
80 }
kaldi::int32 int32
void SortAndUniq(std::vector< T > *vec)
Sorts and uniq&#39;s (removes duplicates) from a vector.
Definition: stl-utils.h:39
void GenerateLexicon(const std::vector< int32 > &phones, bool allow_zero_words, bool allow_empty_word, bool allow_multiple_prons, std::vector< std::vector< int32 > > *lexicon)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GeneratePathThroughHmm()

void GeneratePathThroughHmm ( const HmmTopology topology,
bool  reorder,
int32  phone,
std::vector< std::pair< int32, int32 > > *  path 
)

This function generates a random path through the HMM for the given phone.

The 'path' output is a list of pairs (HMM-state, transition-index) in which any nonemitting states will have been removed. This is used in other test code. the 'reorder' option is as described in the documentation; if true, the self-loops from a state are reordered to come after the forward-transition.

Definition at line 190 of file hmm-test-utils.cc.

References HmmTopology::HmmState::forward_pdf_class, KALDI_ASSERT, RandInt(), HmmTopology::TopologyForPhone(), and HmmTopology::HmmState::transitions.

Referenced by GenerateRandomAlignment().

193  {
194  path->clear();
195  const HmmTopology::TopologyEntry &this_entry =
196  topology.TopologyForPhone(phone);
197  int32 cur_state = 0; // start-state is always state zero.
198  int32 num_states = this_entry.size(), final_state = num_states - 1;
199  KALDI_ASSERT(num_states > 1); // there has to be a final nonemitting state
200  // that's different from the start state.
201  std::vector<std::pair<int32, int32> > pending_self_loops;
202  while (cur_state != final_state) {
203  const HmmTopology::HmmState &cur_hmm_state = this_entry[cur_state];
204  int32 num_transitions = cur_hmm_state.transitions.size(),
205  transition_index = RandInt(0, num_transitions - 1);
206  if (cur_hmm_state.forward_pdf_class != -1) {
207  std::pair<int32, int32> pr(cur_state, transition_index);
208  if (!reorder) {
209  path->push_back(pr);
210  } else {
211  bool is_self_loop = (cur_state ==
212  cur_hmm_state.transitions[transition_index].first);
213  if (is_self_loop) { // save these up, we'll put them after the forward
214  // transition.
215  pending_self_loops.push_back(pr);
216  } else {
217  // non-self-loop: output it and then flush out any self-loops we
218  // stored up.
219  path->push_back(pr);
220  path->insert(path->end(), pending_self_loops.begin(),
221  pending_self_loops.end());
222  pending_self_loops.clear();
223  }
224  }
225  }
226  cur_state = cur_hmm_state.transitions[transition_index].first;
227  }
228  KALDI_ASSERT(pending_self_loops.empty());
229 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GenerateRandomAlignment()

void GenerateRandomAlignment ( const ContextDependencyInterface ctx_dep,
const TransitionModel trans_model,
bool  reorder,
const std::vector< int32 > &  phone_sequence,
std::vector< int32 > *  alignment 
)

For use in test code, this function generates an alignment (a sequence of transition-ids) corresponding to a given phone sequence.

Definition at line 232 of file hmm-test-utils.cc.

References ContextDependencyInterface::CentralPosition(), ContextDependencyInterface::Compute(), ContextDependencyInterface::ContextWidth(), GeneratePathThroughHmm(), TransitionModel::GetTopo(), rnnlm::i, rnnlm::j, KALDI_ASSERT, TransitionModel::PairToTransitionId(), HmmTopology::TopologyForPhone(), and TransitionModel::TupleToTransitionState().

Referenced by TestConvertAlignment(), TestSplitToPhones(), and TestWordAlignLatticeLexicon().

236  {
237  int32 context_width = ctx_dep.ContextWidth(),
238  central_position = ctx_dep.CentralPosition(),
239  num_phones = phone_sequence.size();
240  alignment->clear();
241  for (int32 i = 0; i < num_phones; i++) {
242  std::vector<int32> context_window;
243  context_window.reserve(context_width);
244  for (int32 j = i - central_position;
245  j < i - central_position + context_width;
246  j++) {
247  if (j >= 0 && j < num_phones) context_window.push_back(phone_sequence[j]);
248  else context_window.push_back(0); // zero for out-of-window phones
249  }
250  // 'path' is the path through this phone's HMM, represented as
251  // (emitting-HMM-state, transition-index) pairs
252  std::vector<std::pair<int32, int32> > path;
253  int32 phone = phone_sequence[i];
254  GeneratePathThroughHmm(trans_model.GetTopo(), reorder, phone, &path);
255  for (size_t k = 0; k < path.size(); k++) {
256  const HmmTopology::TopologyEntry &entry =
257  trans_model.GetTopo().TopologyForPhone(phone);
258  int32 hmm_state = path[k].first,
259  transition_index = path[k].second,
260  forward_pdf_class = entry[hmm_state].forward_pdf_class,
261  self_loop_pdf_class = entry[hmm_state].self_loop_pdf_class,
262  forward_pdf_id, self_loop_pdf_id;
263  bool ans = ctx_dep.Compute(context_window, forward_pdf_class, &forward_pdf_id);
264  KALDI_ASSERT(ans && "context-dependency computation failed.");
265  ans = ctx_dep.Compute(context_window, self_loop_pdf_class, &self_loop_pdf_id);
266  KALDI_ASSERT(ans && "context-dependency computation failed.");
267  int32 transition_state = trans_model.TupleToTransitionState(
268  phone, hmm_state, forward_pdf_id, self_loop_pdf_id),
269  transition_id = trans_model.PairToTransitionId(transition_state,
270  transition_index);
271  alignment->push_back(transition_id);
272  }
273  }
274 }
kaldi::int32 int32
void GeneratePathThroughHmm(const HmmTopology &topology, bool reorder, int32 phone, std::vector< std::pair< int32, int32 > > *path)
This function generates a random path through the HMM for the given phone.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GenerateWordAndPhoneSequence()

void kaldi::GenerateWordAndPhoneSequence ( std::vector< std::vector< int32 > > &  lexicon,
std::vector< int32 > *  phone_seq,
std::vector< int32 > *  word_seq 
)

Definition at line 109 of file word-align-lattice-lexicon-test.cc.

References rnnlm::i, and RandInt().

Referenced by TestWordAlignLatticeLexicon().

111  {
112  int32 num_words = RandInt(0, 5);
113  phone_seq->clear();
114  word_seq->clear();
115  for (int32 i = 0; i < num_words; i++) {
116  const std::vector<int32> &lexicon_entry =
117  lexicon[RandInt(0, lexicon.size() - 1)];
118  // the zeroth element of 'lexicon_entry' is how it appears in
119  // the lattice prior to word alignment.
120  int32 word = lexicon_entry[0];
121  if (word != 0) word_seq->push_back(word);
122  // add everything from position 2 in the lexicon entry, to the
123  // phone sequence.
124  phone_seq->insert(phone_seq->end(),
125  lexicon_entry.begin() + 2,
126  lexicon_entry.end());
127  }
128 }
kaldi::int32 int32
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GenRandContextDependency()

ContextDependency * GenRandContextDependency ( const std::vector< int32 > &  phones,
bool  ensure_all_covered,
std::vector< int32 > *  num_pdf_classes 
)

GenRandContextDependency is mainly of use for debugging.

Phones must be sorted and uniq on input.

Parameters
phones[in] A vector of phone id's [must be sorted and uniq].
ensure_all_covered[in] boolean argument; if true, GenRandContextDependency generates a context-dependency object that "works" for all phones [no gaps].
num_pdf_classes[out] outputs a vector indexed by phone, of the number of pdf classes (e.g. states) for that phone.
Returns
Returns the a context dependency object.

Definition at line 46 of file context-dep.cc.

References BuildTree(), ContextDependency::ContextDependency(), DeleteBuildTreeStats(), GenRandStats(), rnnlm::i, Questions::InitRand(), IsSortedAndUniq(), KALDI_ASSERT, KALDI_VLOG, kAllKeysUnion, Rand(), and RandUniform().

Referenced by TestGenRandContextDependency().

48  {
49  KALDI_ASSERT(IsSortedAndUniq(phone_ids));
50  int32 num_phones = phone_ids.size();
51  int32 num_stats = 1 + (Rand() % 15) * (Rand() % 15); // up to 14^2 + 1 separate stats.
52  int32 N = 2 + Rand() % 3; // 2, 3 or 4.
53  int32 P = Rand() % N;
54  float ctx_dep_prob = 0.7 + 0.3*RandUniform();
55  int32 max_phone = *std::max_element(phone_ids.begin(), phone_ids.end());
56  hmm_lengths->clear();
57  hmm_lengths->resize(max_phone + 1, -1);
58  std::vector<bool> is_ctx_dep(max_phone + 1);
59 
60  for (int32 i = 0; i <= max_phone; i++) {
61  (*hmm_lengths)[i] = 1 + Rand() % 3;
62  is_ctx_dep[i] = (RandUniform() < ctx_dep_prob); // true w.p. ctx_dep_prob.
63  }
64  for (size_t i = 0; i < (size_t) num_phones; i++)
65  KALDI_VLOG(2) << "For idx = " << i
66  << ", (phone_id, hmm_length, is_ctx_dep) == "
67  << (phone_ids[i]) << " " << ((*hmm_lengths)[phone_ids[i]])
68  << " " << (is_ctx_dep[phone_ids[i]]);
69  // Generate rand stats.
70  BuildTreeStatsType stats;
71  size_t dim = 3 + Rand() % 20;
72  GenRandStats(dim, num_stats, N, P, phone_ids, *hmm_lengths,
73  is_ctx_dep, ensure_all_covered, &stats);
74 
75  // Now build the tree.
76 
77  Questions qopts;
78  int32 num_quest = Rand() % 10, num_iters = rand () % 5;
79  qopts.InitRand(stats, num_quest, num_iters, kAllKeysUnion); // This was tested in build-tree-utils-test.cc
80 
81  float thresh = 100.0 * RandUniform();
82 
83  EventMap *tree = NULL;
84  std::vector<std::vector<int32> > phone_sets(phone_ids.size());
85  for (size_t i = 0; i < phone_ids.size(); i++)
86  phone_sets[i].push_back(phone_ids[i]);
87  std::vector<bool> share_roots(phone_sets.size(), true),
88  do_split(phone_sets.size(), true);
89 
90  tree = BuildTree(qopts, phone_sets, *hmm_lengths, share_roots,
91  do_split, stats, thresh, 1000, 0.0, P);
92  DeleteBuildTreeStats(&stats);
93  return new ContextDependency(N, P, tree);
94 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
void GenRandStats(int32 dim, int32 num_stats, int32 N, int32 P, const std::vector< int32 > &phone_ids, const std::vector< int32 > &phone2hmm_length, const std::vector< bool > &is_ctx_dep, bool ensure_all_phones_covered, BuildTreeStatsType *stats_out)
GenRandStats generates random statistics of the form used by BuildTree.
Definition: build-tree.cc:30
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
EventMap * BuildTree(Questions &qopts, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, const std::vector< bool > &do_split, const BuildTreeStatsType &stats, BaseFloat thresh, int32 max_leaves, BaseFloat cluster_thresh, int32 P, bool round_num_leaves)
BuildTree is the normal way to build a set of decision trees.
Definition: build-tree.cc:136
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ GenRandContextDependencyLarge()

ContextDependency * GenRandContextDependencyLarge ( const std::vector< int32 > &  phones,
int  N,
int  P,
bool  ensure_all_covered,
std::vector< int32 > *  num_pdf_classes 
)

GenRandContextDependencyLarge is like GenRandContextDependency but generates a larger tree with specified N and P for use in "one-time" larger-scale tests.

Definition at line 97 of file context-dep.cc.

References BuildTree(), ContextDependency::ContextDependency(), DeleteBuildTreeStats(), GenRandStats(), rnnlm::i, Questions::InitRand(), IsSortedAndUniq(), KALDI_ASSERT, KALDI_VLOG, kAllKeysUnion, Rand(), and RandUniform().

Referenced by GenRandTransitionModel(), TestConvertAlignment(), kaldi::nnet2::UnitTestAmNnet(), and kaldi::nnet2::UnitTestNnetDecodable().

100  {
101  KALDI_ASSERT(IsSortedAndUniq(phone_ids));
102  int32 num_phones = phone_ids.size();
103  int32 num_stats = 3000; // each is a separate context.
104  float ctx_dep_prob = 0.9;
105  KALDI_ASSERT(num_phones > 0);
106  hmm_lengths->clear();
107  int32 max_phone = *std::max_element(phone_ids.begin(), phone_ids.end());
108  hmm_lengths->resize(max_phone + 1, -1);
109  std::vector<bool> is_ctx_dep(max_phone + 1);
110 
111  for (int32 i = 0; i <= max_phone; i++) {
112  (*hmm_lengths)[i] = 1 + Rand() % 3;
113  is_ctx_dep[i] = (RandUniform() < ctx_dep_prob); // true w.p. ctx_dep_prob.
114  }
115  for (size_t i = 0; i < (size_t) num_phones; i++) {
116  KALDI_VLOG(2) << "For idx = "<< i << ", (phone_id, hmm_length, is_ctx_dep) == " << (phone_ids[i]) << " " << ((*hmm_lengths)[phone_ids[i]]) << " " << (is_ctx_dep[phone_ids[i]]);
117  }
118  // Generate rand stats.
119  BuildTreeStatsType stats;
120  size_t dim = 3 + Rand() % 20;
121  GenRandStats(dim, num_stats, N, P, phone_ids, *hmm_lengths, is_ctx_dep, ensure_all_covered, &stats);
122 
123  // Now build the tree.
124 
125  Questions qopts;
126  int32 num_quest = 40, num_iters = 0;
127  qopts.InitRand(stats, num_quest, num_iters, kAllKeysUnion); // This was tested in build-tree-utils-test.cc
128 
129  float thresh = 100.0 * RandUniform();
130 
131  EventMap *tree = NULL;
132  std::vector<std::vector<int32> > phone_sets(phone_ids.size());
133  for (size_t i = 0; i < phone_ids.size(); i++)
134  phone_sets[i].push_back(phone_ids[i]);
135  std::vector<bool> share_roots(phone_sets.size(), true),
136  do_split(phone_sets.size(), true);
137 
138  tree = BuildTree(qopts, phone_sets, *hmm_lengths, share_roots,
139  do_split, stats, thresh, 1000, 0.0, P);
140  DeleteBuildTreeStats(&stats);
141  return new ContextDependency(N, P, tree);
142 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
void GenRandStats(int32 dim, int32 num_stats, int32 N, int32 P, const std::vector< int32 > &phone_ids, const std::vector< int32 > &phone2hmm_length, const std::vector< bool > &is_ctx_dep, bool ensure_all_phones_covered, BuildTreeStatsType *stats_out)
GenRandStats generates random statistics of the form used by BuildTree.
Definition: build-tree.cc:30
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
EventMap * BuildTree(Questions &qopts, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, const std::vector< bool > &do_split, const BuildTreeStatsType &stats, BaseFloat thresh, int32 max_leaves, BaseFloat cluster_thresh, int32 P, bool round_num_leaves)
BuildTree is the normal way to build a set of decision trees.
Definition: build-tree.cc:136
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ GenRandTopology() [1/2]

HmmTopology GenRandTopology ( const std::vector< int32 > &  phones,
const std::vector< int32 > &  num_pdf_classes 
)

This method of generating an arbitrary HmmTopology object allows you to specify the number of pdf-classes for each phone separately.

'num_pdf_classes' is indexed by the phone-index (so the length will be longer than the length of the 'phones' vector, which for example lacks the zero index and may have gaps).

Definition at line 87 of file hmm-test-utils.cc.

References rnnlm::i, IsSortedAndUniq(), rnnlm::j, KALDI_ASSERT, rnnlm::n, RandInt(), and HmmTopology::Read().

Referenced by GenRandTopology(), GenRandTransitionModel(), TestConvertAlignment(), and TestHmmTopology().

88  {
89  std::vector<int32> phones(phones_in);
90  std::sort(phones.begin(), phones.end());
91  KALDI_ASSERT(IsSortedAndUniq(phones) && !phones.empty());
92 
93  std::ostringstream topo_string;
94 
95  std::map<int32, std::vector<int32> > num_pdf_classes_to_phones;
96  for (size_t i = 0; i < phones.size(); i++) {
97  int32 p = phones[i];
98  KALDI_ASSERT(static_cast<size_t>(p) < num_pdf_classes.size());
99  int32 n = num_pdf_classes[p];
100  KALDI_ASSERT(n > 0 && "num-pdf-classes cannot be zero.");
101  num_pdf_classes_to_phones[n].push_back(p);
102  }
103 
104  topo_string << "<Topology>\n";
105  std::map<int32, std::vector<int32> >::const_iterator
106  iter = num_pdf_classes_to_phones.begin(),
107  end = num_pdf_classes_to_phones.end();
108  for (; iter != end; ++iter) {
109  topo_string << "<TopologyEntry>\n"
110  "<ForPhones> ";
111  int32 this_num_pdf_classes = iter->first;
112  const std::vector<int32> &phones = iter->second;
113  for (size_t i = 0; i < phones.size(); i++)
114  topo_string << phones[i] << " ";
115  topo_string << "</ForPhones> ";
116  bool ergodic = (RandInt(0, 1) == 0);
117  if (ergodic) {
118  // Note, this type of topology is not something we ever use in practice- it
119  // has an initial nonemitting state (no PdfClass specified). But it's
120  // supported so we're testing it.
121  std::vector<int32> state_to_pdf_class;
122  state_to_pdf_class.push_back(-1); // state zero, nonemitting.
123  for (int32 i = 0; i < this_num_pdf_classes; i++) {
124  int32 num_states = RandInt(1, 2);
125  for (int32 j = 0; j < num_states; j++)
126  state_to_pdf_class.push_back(i);
127  }
128  state_to_pdf_class.push_back(-1); // final non-emitting state.
129  { // state zero is nonemitting. This is not something used in any current
130  // example script.
131  topo_string << "<State> 0\n";
132  BaseFloat prob = 1.0 / (state_to_pdf_class.size() - 2);
133  for (size_t i = 1; i + 1 < state_to_pdf_class.size(); i++) {
134  topo_string << "<Transition> " << i << ' ' << prob << '\n';
135  }
136  topo_string << "</State>\n";
137  }
138  // ergodic part.
139  for (size_t i = 1; i + 1 < state_to_pdf_class.size(); i++) {
140  BaseFloat prob = 1.0 / (state_to_pdf_class.size() - 1);
141  topo_string << "<State> " << i << " <PdfClass> "
142  << state_to_pdf_class[i] << '\n';
143  for (size_t j = 1; j < state_to_pdf_class.size(); j++)
144  topo_string << "<Transition> " << j << ' ' << prob << '\n';
145  topo_string << "</State>\n";
146  }
147  // final, nonemitting state. No pdf-class, no transitions.
148  topo_string << "<State> " << (state_to_pdf_class.size() - 1) << " </State>\n";
149  } else {
150  // feedforward topology.
151  int32 cur_state = 0;
152  for (int32 pdf_class = 0; pdf_class < this_num_pdf_classes; pdf_class++) {
153  int32 this_num_states = RandInt(1, 2);
154  for (int32 s = 0; s < this_num_states; s++) {
155  topo_string << "<State> " << cur_state << " <PdfClass> " << pdf_class
156  << "\n<Transition> " << cur_state << " 0.5\n<Transition> "
157  << (cur_state + 1) << " 0.5\n</State>\n";
158  cur_state++;
159  }
160  }
161  // final, non-emitting state.
162  topo_string << "<State> " << cur_state << " </State>\n";
163  }
164  topo_string << "</TopologyEntry>\n";
165  }
166  topo_string << "</Topology>\n";
167 
168  HmmTopology topo;
169  std::istringstream iss(topo_string.str());
170  topo.Read(iss, false);
171  return topo;
172 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GenRandTopology() [2/2]

HmmTopology GenRandTopology ( )

This version of GenRandTopology() generates the phone list and number of pdf classes randomly.

Definition at line 174 of file hmm-test-utils.cc.

References GenRandTopology(), GetDefaultTopology(), rnnlm::i, and RandInt().

174  {
175  std::vector<int32> phones;
176  phones.push_back(1);
177  for (int32 i = 2; i < 20; i++)
178  if (rand() % 2 == 0)
179  phones.push_back(i);
180  if (RandInt(0, 1) == 0) {
181  return GetDefaultTopology(phones);
182  } else {
183  std::vector<int32> num_pdf_classes(phones.back() + 1, -1);
184  for (int32 i = 0; i < phones.size(); i++)
185  num_pdf_classes[phones[i]] = RandInt(1, 5);
186  return GenRandTopology(phones, num_pdf_classes);
187  }
188 }
HmmTopology GetDefaultTopology(const std::vector< int32 > &phones_in)
This function returns a HmmTopology object giving a normal 3-state topology, covering all phones in t...
kaldi::int32 int32
HmmTopology GenRandTopology()
This version of GenRandTopology() generates the phone list and number of pdf classes randomly...
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GenRandTransitionModel()

TransitionModel * GenRandTransitionModel ( ContextDependency **  ctx_dep_out)

Definition at line 26 of file hmm-test-utils.cc.

References GenRandContextDependencyLarge(), GenRandTopology(), and rnnlm::i.

Referenced by TestSplitToPhones(), TestTransitionModel(), and TestWordAlignLatticeLexicon().

26  {
27  std::vector<int32> phones;
28  phones.push_back(1);
29  for (int32 i = 2; i < 20; i++)
30  if (rand() % 2 == 0)
31  phones.push_back(i);
32  int32 N = 2 + rand() % 2, // context-size N is 2 or 3.
33  P = rand() % N; // Central-phone is random on [0, N)
34 
35  std::vector<int32> num_pdf_classes;
36 
37  ContextDependency *ctx_dep =
38  GenRandContextDependencyLarge(phones, N, P,
39  true, &num_pdf_classes);
40 
41  HmmTopology topo = GenRandTopology(phones, num_pdf_classes);
42 
43  TransitionModel *trans_model = new TransitionModel(*ctx_dep, topo);
44 
45  if (ctx_dep_out == NULL) delete ctx_dep;
46  else *ctx_dep_out = ctx_dep;
47  return trans_model;
48 }
ContextDependency * GenRandContextDependencyLarge(const std::vector< int32 > &phone_ids, int N, int P, bool ensure_all_covered, std::vector< int32 > *hmm_lengths)
GenRandContextDependencyLarge is like GenRandContextDependency but generates a larger tree with speci...
Definition: context-dep.cc:97
kaldi::int32 int32
HmmTopology GenRandTopology()
This version of GenRandTopology() generates the phone list and number of pdf classes randomly...

◆ GetActiveParents()

static bool kaldi::GetActiveParents ( int32  node,
const vector< int32 > &  parents,
const vector< bool > &  is_active,
vector< int32 > *  active_parents_out 
)
static

Definition at line 129 of file regression-tree.cc.

References KALDI_ASSERT.

Referenced by RegressionTree::GatherStats().

131  {
132  KALDI_ASSERT(parents.size() == is_active.size());
133  KALDI_ASSERT(static_cast<size_t>(node) < parents.size());
134  active_parents_out->clear();
135 
136  if (node == static_cast<int32> (parents.size() - 1)) { // root node
137  if (is_active[node]) {
138  active_parents_out->push_back(node);
139  return true;
140  } else {
141  return false;
142  }
143  }
144 
145  bool ret_val = false;
146  while (node < static_cast<int32> (parents.size() - 1)) { // exclude the root
147  node = parents[node];
148  if (is_active[node]) {
149  active_parents_out->push_back(node);
150  ret_val = true;
151  }
152  }
153  return ret_val; // will return if not starting from root
154 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetBootstrapWERInterval()

void kaldi::GetBootstrapWERInterval ( const std::vector< std::pair< int32, int32 > > &  edit_word_per_hyp,
int32  replications,
BaseFloat mean,
BaseFloat interval 
)

Definition at line 113 of file compute-wer-bootci.cc.

References rnnlm::i, rnnlm::j, and RandInt().

Referenced by main().

116  {
117  BaseFloat wer_accum = 0.0, wer_mult_accum = 0.0;
118 
119  for (int32 i = 0; i < replications; ++i) {
120  int32 num_words = 0, word_errs = 0;
121  for (int32 j = 0; j < edit_word_per_hyp.size(); ++j) {
122  int32 random_pos = kaldi::RandInt(0, edit_word_per_hyp.size() - 1);
123  word_errs += edit_word_per_hyp[random_pos].first;
124  num_words += edit_word_per_hyp[random_pos].second;
125  }
126 
127  BaseFloat wer_rep = static_cast<BaseFloat>(word_errs) / num_words;
128  wer_accum += wer_rep;
129  wer_mult_accum += wer_rep*wer_rep;
130  }
131 
132  // Compute mean WER and std WER
133  *mean = wer_accum / replications;
134  *interval = 1.96*sqrt(wer_mult_accum/replications-(*mean)*(*mean));
135 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GetBootstrapWERTwoSystemComparison()

void kaldi::GetBootstrapWERTwoSystemComparison ( const std::vector< std::pair< int32, int32 > > &  edit_word_per_hyp,
const std::vector< std::pair< int32, int32 > > &  edit_word_per_hyp2,
int32  replications,
BaseFloat p_improv 
)

Definition at line 137 of file compute-wer-bootci.cc.

References rnnlm::i, rnnlm::j, and RandInt().

Referenced by main().

140  {
141  int32 improv_accum = 0.0;
142 
143  for (int32 i = 0; i < replications; ++i) {
144  int32 word_errs = 0;
145  for (int32 j = 0; j < edit_word_per_hyp.size(); ++j) {
146  int32 random_pos = kaldi::RandInt(0, edit_word_per_hyp.size() - 1);
147  word_errs += edit_word_per_hyp[random_pos].first -
148  edit_word_per_hyp2[random_pos].first;
149  }
150  if(word_errs > 0)
151  ++improv_accum;
152  }
153  // Compute mean WER and std WER
154  *p_improv = static_cast<BaseFloat>(improv_accum) / replications;
155 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ GetCount()

int32 kaldi::GetCount ( double  expected_count)

Definition at line 29 of file nnet3-discriminative-copy-egs.cc.

References KALDI_ASSERT, and WithProb().

29  {
30  KALDI_ASSERT(expected_count >= 0.0);
31  int32 ans = floor(expected_count);
32  expected_count -= ans;
33  if (WithProb(expected_count))
34  ans++;
35  return ans;
36 }
bool WithProb(BaseFloat prob, struct RandomState *state)
Definition: kaldi-math.cc:72
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetDefaultTopology()

HmmTopology GetDefaultTopology ( const std::vector< int32 > &  phones)

This function returns a HmmTopology object giving a normal 3-state topology, covering all phones in the list "phones".

This is mainly of use in testing code.

Definition at line 50 of file hmm-test-utils.cc.

References rnnlm::i, IsSortedAndUniq(), KALDI_ASSERT, and HmmTopology::Read().

Referenced by GenRandTopology(), TestHmmTopology(), kaldi::nnet2::UnitTestAmNnet(), and kaldi::nnet2::UnitTestNnetDecodable().

50  {
51  std::vector<int32> phones(phones_in);
52  std::sort(phones.begin(), phones.end());
53  KALDI_ASSERT(IsSortedAndUniq(phones) && !phones.empty());
54 
55  std::ostringstream topo_string;
56  topo_string << "<Topology>\n"
57  "<TopologyEntry>\n"
58  "<ForPhones> ";
59  for (size_t i = 0; i < phones.size(); i++)
60  topo_string << phones[i] << " ";
61 
62  topo_string << "</ForPhones>\n"
63  "<State> 0 <PdfClass> 0\n"
64  "<Transition> 0 0.5\n"
65  "<Transition> 1 0.5\n"
66  "</State> \n"
67  "<State> 1 <PdfClass> 1 \n"
68  "<Transition> 1 0.5\n"
69  "<Transition> 2 0.5\n"
70  "</State> \n"
71  " <State> 2 <PdfClass> 2\n"
72  " <Transition> 2 0.5\n"
73  " <Transition> 3 0.5\n"
74  " </State> \n"
75  " <State> 3 </State>\n"
76  " </TopologyEntry>\n"
77  " </Topology>\n";
78 
79  HmmTopology topo;
80  std::istringstream iss(topo_string.str());
81  topo.Read(iss, false);
82  return topo;
83 
84 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ GetDiagnosticsAndPrintOutput()

void GetDiagnosticsAndPrintOutput ( const std::string &  utt,
const fst::SymbolTable *  word_syms,
const CompactLattice clat,
int64 *  tot_num_frames,
double *  tot_like 
)

Definition at line 31 of file online2-wav-gmm-latgen-faster.cc.

References CompactLatticeShortestPath(), fst::ConvertLattice(), fst::GetLinearSymbolSequence(), rnnlm::i, KALDI_ERR, KALDI_VLOG, KALDI_WARN, LatticeWeightTpl< FloatType >::Value1(), LatticeWeightTpl< FloatType >::Value2(), and words.

Referenced by main().

35  {
36  if (clat.NumStates() == 0) {
37  KALDI_WARN << "Empty lattice.";
38  return;
39  }
40  CompactLattice best_path_clat;
41  CompactLatticeShortestPath(clat, &best_path_clat);
42 
43  Lattice best_path_lat;
44  ConvertLattice(best_path_clat, &best_path_lat);
45 
46  double likelihood;
47  LatticeWeight weight;
48  int32 num_frames;
49  std::vector<int32> alignment;
50  std::vector<int32> words;
51  GetLinearSymbolSequence(best_path_lat, &alignment, &words, &weight);
52  num_frames = alignment.size();
53  likelihood = -(weight.Value1() + weight.Value2());
54  *tot_num_frames += num_frames;
55  *tot_like += likelihood;
56  KALDI_VLOG(2) << "Likelihood per frame for utterance " << utt << " is "
57  << (likelihood / num_frames) << " over " << num_frames
58  << " frames.";
59 
60  if (word_syms != NULL) {
61  std::cerr << utt << ' ';
62  for (size_t i = 0; i < words.size(); i++) {
63  std::string s = word_syms->Find(words[i]);
64  if (s == "")
65  KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
66  std::cerr << s << ' ';
67  }
68  std::cerr << std::endl;
69  }
70 }
int32 words[kMaxOrder]
kaldi::int32 int32
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
void CompactLatticeShortestPath(const CompactLattice &clat, CompactLattice *shortest_path)
A form of the shortest-path/best-path algorithm that&#39;s specially coded for CompactLattice.
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ GetEditsDualHyp()

void kaldi::GetEditsDualHyp ( const std::string &  hyp_rspecifier,
const std::string &  hyp_rspecifier2,
const std::string &  ref_rspecifier,
const std::string &  mode,
std::vector< std::pair< int32, int32 > > &  edit_word_per_hyp,
std::vector< std::pair< int32, int32 > > &  edit_word_per_hyp2 
)

Definition at line 63 of file compute-wer-bootci.cc.

References SequentialTableReader< Holder >::Done(), RandomAccessTableReader< Holder >::HasKey(), KALDI_ERR, SequentialTableReader< Holder >::Key(), LevenshteinEditDistance(), SequentialTableReader< Holder >::Next(), RandomAccessTableReader< Holder >::Value(), and SequentialTableReader< Holder >::Value().

Referenced by main().

68  {
69 
70  // Both text and integers are loaded as vector of strings,
71  SequentialTokenVectorReader ref_reader(ref_rspecifier);
72  RandomAccessTokenVectorReader hyp_reader(hyp_rspecifier);
73  RandomAccessTokenVectorReader hyp_reader2(hyp_rspecifier2);
74  int32 num_words = 0, word_errs = 0,
75  num_ins = 0, num_del = 0, num_sub = 0;
76 
77  // Main loop, store WER stats per hyp,
78  for (; !ref_reader.Done(); ref_reader.Next()) {
79  std::string key = ref_reader.Key();
80  const std::vector<std::string> &ref_sent = ref_reader.Value();
81  std::vector<std::string> hyp_sent, hyp_sent2;
82  if (mode == "strict" &&
83  (!hyp_reader.HasKey(key) || !hyp_reader2.HasKey(key))) {
84  KALDI_ERR << "No hypothesis for key " << key << " in both transcripts "
85  "comparison is not possible.";
86  } else if (mode == "present" &&
87  (!hyp_reader.HasKey(key) || !hyp_reader2.HasKey(key)))
88  continue;
89 
90  num_words = ref_sent.size();
91 
92  //all mode, if a hypothesis is not present, consider as an error
93  if(hyp_reader.HasKey(key)){
94  hyp_sent = hyp_reader.Value(key);
95  word_errs = LevenshteinEditDistance(ref_sent, hyp_sent,
96  &num_ins, &num_del, &num_sub);
97  }
98  else
99  word_errs = num_words;
100  edit_word_per_hyp.push_back(std::pair<int32, int32>(word_errs, num_words));
101 
102  if(hyp_reader2.HasKey(key)){
103  hyp_sent2 = hyp_reader2.Value(key);
104  word_errs = LevenshteinEditDistance(ref_sent, hyp_sent2,
105  &num_ins, &num_del, &num_sub);
106  }
107  else
108  word_errs = num_words;
109  edit_word_per_hyp2.push_back(std::pair<int32, int32>(word_errs, num_words));
110  }
111 }
kaldi::int32 int32
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
int32 LevenshteinEditDistance(const std::vector< T > &a, const std::vector< T > &b)
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ GetEditsSingleHyp()

void kaldi::GetEditsSingleHyp ( const std::string &  hyp_rspecifier,
const std::string &  ref_rspecifier,
const std::string &  mode,
std::vector< std::pair< int32, int32 > > &  edit_word_per_hyp 
)

Definition at line 32 of file compute-wer-bootci.cc.

References SequentialTableReader< Holder >::Done(), RandomAccessTableReader< Holder >::HasKey(), KALDI_ERR, SequentialTableReader< Holder >::Key(), LevenshteinEditDistance(), SequentialTableReader< Holder >::Next(), RandomAccessTableReader< Holder >::Value(), and SequentialTableReader< Holder >::Value().

Referenced by main().

35  {
36 
37  // Both text and integers are loaded as vector of strings,
38  SequentialTokenVectorReader ref_reader(ref_rspecifier);
39  RandomAccessTokenVectorReader hyp_reader(hyp_rspecifier);
40  int32 num_words = 0, word_errs = 0, num_ins = 0, num_del = 0, num_sub = 0;
41 
42  // Main loop, store WER stats per hyp,
43  for (; !ref_reader.Done(); ref_reader.Next()) {
44  std::string key = ref_reader.Key();
45  const std::vector<std::string> &ref_sent = ref_reader.Value();
46  std::vector<std::string> hyp_sent;
47  if (!hyp_reader.HasKey(key)) {
48  if (mode == "strict")
49  KALDI_ERR << "No hypothesis for key " << key << " and strict "
50  "mode specifier.";
51  if (mode == "present") // do not score this one.
52  continue;
53  } else {
54  hyp_sent = hyp_reader.Value(key);
55  }
56  num_words = ref_sent.size();
57  word_errs = LevenshteinEditDistance(ref_sent, hyp_sent,
58  &num_ins, &num_del, &num_sub);
59  edit_word_per_hyp.push_back(std::pair<int32, int32>(word_errs, num_words));
60  }
61 }
kaldi::int32 int32
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
int32 LevenshteinEditDistance(const std::vector< T > &a, const std::vector< T > &b)
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ GetEventKeys()

static void kaldi::GetEventKeys ( const EventType vec,
std::vector< EventKeyType > *  keys 
)
static

Definition at line 81 of file build-tree-utils.cc.

Referenced by FindAllKeys().

81  {
82  keys->resize(vec.size());
83  EventType::const_iterator iter = vec.begin(), end = vec.end();
84  std::vector<EventKeyType>::iterator out_iter = keys->begin();
85  for (; iter!= end; ++iter, ++out_iter)
86  *out_iter = iter->first;
87 }

◆ GetFeatDeriv()

void kaldi::GetFeatDeriv ( const DiagGmm gmm,
const Matrix< BaseFloat > &  feats,
Matrix< BaseFloat > *  deriv 
)

Definition at line 32 of file fmpe-test.cc.

References VectorBase< Real >::AddMatVec(), VectorBase< Real >::AddVecVec(), DiagGmm::ComponentPosteriors(), rnnlm::i, DiagGmm::inv_vars(), kTrans, DiagGmm::means_invvars(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Matrix< Real >::Resize(), and VectorBase< Real >::Scale().

Referenced by TestFmpe().

34  {
35 
36  deriv->Resize(feats.NumRows(), feats.NumCols());
37 
38  Vector<BaseFloat> gauss_posteriors;
39  Vector<BaseFloat> temp_vec(feats.NumCols());
40  for (int32 i = 0; i < feats.NumRows(); i++) {
41  SubVector<BaseFloat> this_feat(feats, i);
42  SubVector<BaseFloat> this_deriv(*deriv, i);
43  gmm.ComponentPosteriors(this_feat, &gauss_posteriors);
44  BaseFloat weight = 1.0;
45  gauss_posteriors.Scale(weight);
46  // The next line does: to i'th row of deriv, add
47  // means_invvars^T * gauss_posteriors,
48  // where each row of means_invvars is the mean times
49  // diagonal inverse covariance... after transposing,
50  // this becomes a weighted of these rows, weighted by
51  // the posteriors. This comes from the term
52  // feat^T * inv_var * mean
53  // in the objective function.
54  this_deriv.AddMatVec(1.0, gmm.means_invvars(), kTrans,
55  gauss_posteriors, 1.0);
56 
57  // next line does temp_vec == inv_vars^T * gauss_posteriors,
58  // which sets temp_vec to a weighted sum of the inv_vars,
59  // weighed by Gaussian posterior.
60  temp_vec.AddMatVec(1.0, gmm.inv_vars(), kTrans,
61  gauss_posteriors, 0.0);
62  // Add to the derivative, -(this_feat .* temp_vec),
63  // which is the term that comes from the -0.5 * inv_var^T feat_sq,
64  // in the objective function (where inv_var is a vector, and feat_sq
65  // is a vector of squares of the feature values).
66  this_deriv.AddVecVec(-1.0, this_feat, temp_vec, 1.0);
67  }
68 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ GetFeatureMeanAndVariance()

void kaldi::GetFeatureMeanAndVariance ( const std::string &  feat_rspecifier,
Vector< BaseFloat > *  inv_var_out,
Vector< BaseFloat > *  mean_out 
)

Definition at line 33 of file gmm-init-model-flat.cc.

References VectorBase< Real >::AddVec(), VectorBase< Real >::AddVec2(), VectorBase< Real >::CopyFromVec(), count, VectorBase< Real >::Dim(), SequentialTableReader< Holder >::Done(), rnnlm::i, VectorBase< Real >::InvertElements(), KALDI_ERR, VectorBase< Real >::Min(), SequentialTableReader< Holder >::Next(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Vector< Real >::Resize(), MatrixBase< Real >::Row(), VectorBase< Real >::Scale(), and SequentialTableReader< Holder >::Value().

Referenced by main().

35  {
36  double count = 0.0;
37  Vector<double> x_stats, x2_stats;
38 
39  SequentialDoubleMatrixReader feat_reader(feat_rspecifier);
40  for (; !feat_reader.Done(); feat_reader.Next()) {
41  const Matrix<double> &mat = feat_reader.Value();
42  if (x_stats.Dim() == 0) {
43  int32 dim = mat.NumCols();
44  x_stats.Resize(dim);
45  x2_stats.Resize(dim);
46  }
47  for (int32 i = 0; i < mat.NumRows(); i++) {
48  count += 1.0;
49  x_stats.AddVec(1.0, mat.Row(i));
50  x2_stats.AddVec2(1.0, mat.Row(i));
51  }
52  }
53  if (count == 0) { KALDI_ERR << "No features were read!"; }
54  x_stats.Scale(1.0/count);
55  x2_stats.Scale(1.0/count);
56  x2_stats.AddVec2(-1.0, x_stats);
57  if (x2_stats.Min() <= 0.0)
58  KALDI_ERR << "Variance is zero or negative!";
59  x2_stats.InvertElements();
60  int32 dim = x_stats.Dim();
61  inv_var_out->Resize(dim);
62  mean_out->Resize(dim);
63  inv_var_out->CopyFromVec(x2_stats);
64  mean_out->CopyFromVec(x_stats);
65 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
Real Min() const
Returns the minimum value of any element, or +infinity for the empty vector.
void AddVec2(const Real alpha, const VectorBase< Real > &v)
Add vector : *this = *this + alpha * rv^2 [element-wise squaring].
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
const size_t count
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_ERR
Definition: kaldi-error.h:147
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
void Scale(Real alpha)
Multiplies all elements by this constant.
void InvertElements()
Invert all elements.
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...

◆ GetFullBiphoneStubMap()

EventMap* kaldi::GetFullBiphoneStubMap ( const std::vector< std::vector< int32 > > &  phone_sets,
const std::vector< int32 > &  phone2num_pdf_classes,
const std::vector< int32 > &  ci_phones_list,
const std::vector< std::vector< int32 > > &  bi_counts,
int32  biphone_min_count,
const std::vector< int32 > &  mono_counts,
int32  mono_min_count 
)

Definition at line 53 of file gmm-init-biphone.cc.

References rnnlm::i, IsSortedAndUniq(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, KALDI_VLOG, and kPdfClass.

Referenced by BiphoneContextDependencyFull().

59  {
60 
61  { // Check the inputs
62  KALDI_ASSERT(!phone_sets.empty());
63  std::set<int32> all_phones;
64  for (size_t i = 0; i < phone_sets.size(); i++) {
65  KALDI_ASSERT(IsSortedAndUniq(phone_sets[i]));
66  KALDI_ASSERT(!phone_sets[i].empty());
67  for (size_t j = 0; j < phone_sets[i].size(); j++) {
68  KALDI_ASSERT(all_phones.count(phone_sets[i][j]) == 0); // Check not present.
69  all_phones.insert(phone_sets[i][j]);
70  }
71  }
72  }
73 
74 
75  int32 numpdfs_per_phone = phone2num_pdf_classes[1];
76  int32 current_pdfid = 0;
77  std::map<EventValueType, EventMap*> level1_map; // key is 1
78 
79  for (size_t i = 0; i < ci_phones_list.size(); i++) {
80  std::map<EventValueType, EventAnswerType> level2_map;
81  level2_map[0] = current_pdfid++;
82  if (numpdfs_per_phone == 2) level2_map[1] = current_pdfid++;
83  level1_map[ci_phones_list[i]] = new TableEventMap(kPdfClass, level2_map);
84  }
85 
86  // If there is not enough data for a biphone, we will revert to monophone
87  // and if there is not enough data for the monophone either, we will revert
88  // to zerophone (which is like a global garbage pdf) after initializing it.
89  int32 zerophone_pdf = -1;
90  // If a monophone state is created for a phone-set, the corresponding pdf will
91  // be stored in this vector.
92  std::vector<int32> monophone_pdf(phone_sets.size(), -1);
93 
94  for (size_t i = 0; i < phone_sets.size(); i++) {
95 
96  if (numpdfs_per_phone == 1) {
97  // Create an event map for level2:
98  std::map<EventValueType, EventAnswerType> level2_map; // key is 0
99  level2_map[0] = current_pdfid++; // no-left-context case
100  for (size_t j = 0; j < phone_sets.size(); j++) {
101  int32 pdfid = current_pdfid++;
102  std::vector<int32> pset = phone_sets[j]; // All these will have a
103  // shared pdf with id=pdfid
104  for (size_t k = 0; k < pset.size(); k++)
105  level2_map[pset[k]] = pdfid;
106  }
107  std::vector<int32> pset = phone_sets[i]; // All these will have a
108  // shared event-map child
109  for (size_t k = 0; k < pset.size(); k++)
110  level1_map[pset[k]] = new TableEventMap(0, level2_map);
111  } else {
112  KALDI_ASSERT(numpdfs_per_phone == 2);
113  std::vector<int32> right_phoneset = phone_sets[i]; // All these will have a shared
114  // event-map child
115  // Create an event map for level2:
116  std::map<EventValueType, EventMap*> level2_map; // key is 0
117  { // Handle CI phones
118  std::map<EventValueType, EventAnswerType> level3_map; // key is kPdfClass
119  level3_map[0] = current_pdfid++;
120  level3_map[1] = current_pdfid++;
121  level2_map[0] = new TableEventMap(kPdfClass, level3_map); // no-left-context case
122  for (size_t i = 0; i < ci_phones_list.size(); i++) // ci-phone left-context cases
123  level2_map[ci_phones_list[i]] = new TableEventMap(kPdfClass, level3_map);
124  }
125  for (size_t j = 0; j < phone_sets.size(); j++) {
126  std::vector<int32> left_phoneset = phone_sets[j]; // All these will have a
127  // shared subtree with 2 pdfids
128  std::map<EventValueType, EventAnswerType> level3_map; // key is kPdfClass
129  if (bi_counts.empty() ||
130  bi_counts[left_phoneset[0]][right_phoneset[0]] >= biphone_min_count) {
131  level3_map[0] = current_pdfid++;
132  level3_map[1] = current_pdfid++;
133  } else if (mono_counts.empty() ||
134  mono_counts[right_phoneset[0]] > mono_min_count) {
135  // Revert to mono.
136  KALDI_VLOG(2) << "Reverting to mono for biphone (" << left_phoneset[0]
137  << "," << right_phoneset[0] << ")";
138  if (monophone_pdf[i] == -1) {
139  KALDI_VLOG(1) << "Reserving mono PDFs for phone-set " << i;
140  monophone_pdf[i] = current_pdfid++;
141  current_pdfid++; // num-pdfs-per-phone is 2
142  }
143  level3_map[0] = monophone_pdf[i];
144  level3_map[1] = monophone_pdf[i] + 1;
145  } else {
146  KALDI_VLOG(2) << "Reverting to zerophone for biphone ("
147  << left_phoneset[0]
148  << "," << right_phoneset[0] << ")";
149  // Revert to zerophone
150  if (zerophone_pdf == -1) {
151  KALDI_VLOG(1) << "Reserving zero PDFs.";
152  zerophone_pdf = current_pdfid++;
153  current_pdfid++; // num-pdfs-per-phone is 2
154  }
155  level3_map[0] = zerophone_pdf;
156  level3_map[1] = zerophone_pdf + 1;
157  }
158 
159  for (size_t k = 0; k < left_phoneset.size(); k++) {
160  int32 left_phone = left_phoneset[k];
161  level2_map[left_phone] = new TableEventMap(kPdfClass, level3_map);
162  }
163  }
164  for (size_t k = 0; k < right_phoneset.size(); k++) {
165  std::map<EventValueType, EventMap*> level2_copy;
166  for (auto const& kv: level2_map)
167  level2_copy[kv.first] = kv.second->Copy(std::vector<EventMap*>());
168  int32 right_phone = right_phoneset[k];
169  level1_map[right_phone] = new TableEventMap(0, level2_copy);
170  }
171  }
172 
173  }
174  KALDI_LOG << "Num PDFs: " << current_pdfid;
175  return new TableEventMap(1, level1_map);
176 }
kaldi::int32 int32
static const EventKeyType kPdfClass
Definition: context-dep.h:39
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ GetGmmLike()

BaseFloat kaldi::GetGmmLike ( const DiagGmm gmm,
const Matrix< BaseFloat > &  feats 
)

Definition at line 71 of file fmpe-test.cc.

References rnnlm::i, DiagGmm::LogLikelihood(), MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

Referenced by TestFmpe().

72  {
73  BaseFloat ans = 0.0;
74  for (int32 i = 0; i < feats.NumRows(); i++)
75  ans += gmm.LogLikelihood(feats.Row(i));
76  return ans;
77 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ GetLatticeTimeSpan()

int32 kaldi::GetLatticeTimeSpan ( const Lattice lat)

Definition at line 96 of file online2-tcp-nnet3-decode-faster.cc.

References LatticeStateTimes().

Referenced by main().

96  {
97  std::vector<int32> times;
98  LatticeStateTimes(lat, &times);
99  return times.back();
100 }
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...

◆ GetLogDetNoFailure()

static double kaldi::GetLogDetNoFailure ( const SpMatrix< double > &  var)
static

Definition at line 345 of file ivector-extractor.cc.

References SpMatrix< Real >::Eig(), KALDI_WARN, SpMatrix< Real >::LogPosDefDet(), and PackedMatrix< Real >::NumRows().

Referenced by IvectorExtractor::GetPriorAuxf().

345  {
346  try {
347  return var.LogPosDefDet();
348  } catch (...) {
349  Vector<double> eigs(var.NumRows());
350  var.Eig(&eigs);
351  int32 floored;
352  eigs.ApplyFloor(1.0e-20, &floored);
353  if (floored > 0)
354  KALDI_WARN << "Floored " << floored << " eigenvalues of variance.";
355  eigs.ApplyLog();
356  return eigs.Sum();
357  }
358 }
kaldi::int32 int32
void Eig(VectorBase< Real > *s, MatrixBase< Real > *P=NULL) const
Solves the symmetric eigenvalue problem: at end we should have (*this) = P * diag(s) * P^T...
Definition: qr.cc:433
MatrixIndexT NumRows() const
Real LogPosDefDet() const
Computes log determinant but only for +ve-def matrices (it uses Cholesky).
Definition: sp-matrix.cc:36
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ GetOccs()

void kaldi::GetOccs ( const BuildTreeStatsType stats,
const EventMap to_pdf_map,
Vector< BaseFloat > *  occs 
)

Get state occupation counts.

Definition at line 92 of file gmm-init-model.cc.

References VectorBase< Real >::Dim(), KALDI_ASSERT, EventMap::MaxResult(), Vector< Real >::Resize(), SplitStatsByMap(), and SumNormalizer().

Referenced by main().

94  {
95 
96  // Get stats split by tree-leaf ( == pdf):
97  std::vector<BuildTreeStatsType> split_stats;
98  SplitStatsByMap(stats, to_pdf_map, &split_stats);
99  if (split_stats.size() != to_pdf_map.MaxResult()+1) {
100  KALDI_ASSERT(split_stats.size() < to_pdf_map.MaxResult()+1);
101  split_stats.resize(to_pdf_map.MaxResult()+1);
102  }
103  occs->Resize(split_stats.size());
104  for (int32 pdf = 0; pdf < occs->Dim(); pdf++)
105  (*occs)(pdf) = SumNormalizer(split_stats[pdf]);
106 }
BaseFloat SumNormalizer(const BuildTreeStatsType &stats_in)
Sums the normalizer [typically, data-count] over the stats.
virtual EventAnswerType MaxResult() const
Definition: event-map.h:142
void SplitStatsByMap(const BuildTreeStatsType &stats, const EventMap &e, std::vector< BuildTreeStatsType > *stats_out)
Splits stats according to the EventMap, indexing them at output by the leaf type. ...
kaldi::int32 int32
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetOptionImpl()

static bool kaldi::GetOptionImpl ( const std::string &  key,
T *  value,
std::map< std::string, T *> &  some_map 
)
static

Definition at line 130 of file simple-options.cc.

Referenced by SimpleOptions::GetOption().

131  {
132  typename std::map<std::string, T*>::iterator it = some_map.find(key);
133  if (it != some_map.end()) {
134  *value = *(it->second);
135  return true;
136  }
137  return false;
138 }

◆ GetOutput() [1/2]

void kaldi::GetOutput ( OnlineFeatureInterface a,
Matrix< BaseFloat > *  output 
)

Definition at line 29 of file online-feature-test.cc.

References OnlineCacheFeature::ClearCache(), MatrixBase< Real >::CopyRowFromVec(), OnlineFeatureInterface::Dim(), OnlineCacheFeature::GetFrame(), rnnlm::i, OnlineCacheFeature::IsLastFrame(), KALDI_ASSERT, OnlineFeatureInterface::NumFramesReady(), and Matrix< Real >::Resize().

Referenced by PldaEstimator::Dim(), TestOnlineAppendFeature(), TestOnlineCmnInput(), TestOnlineDeltaFeature(), TestOnlineDeltaInput(), TestOnlineLdaInput(), TestOnlineMatrixCacheFeature(), TestOnlineMatrixInput(), TestOnlineMfcc(), TestOnlinePlp(), TestOnlineSpliceFrames(), and TestOnlineTransform().

30  {
31  int32 dim = a->Dim();
32  int32 frame_num = 0;
33  OnlineCacheFeature cache(a);
34 
35  std::vector<Vector<BaseFloat>* > cached_frames;
36  while (true) {
37  Vector<BaseFloat> garbage(dim);
38  cache.GetFrame(frame_num, &garbage);
39  cached_frames.push_back(new Vector<BaseFloat>(garbage));
40  if (cache.IsLastFrame(frame_num))
41  break;
42  frame_num++;
43  }
44 
45  KALDI_ASSERT(cached_frames.size() == a->NumFramesReady());
46 
47  output->Resize(cached_frames.size(), dim);
48  for (int32 i = 0; i < cached_frames.size(); i++) {
49  output->CopyRowFromVec(*(cached_frames[i]), i);
50  delete cached_frames[i];
51  }
52  cached_frames.clear();
53  cache.ClearCache();
54 }
kaldi::int32 int32
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void CopyRowFromVec(const VectorBase< Real > &v, const MatrixIndexT row)
Copy vector into specific row of matrix.
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
This feature type can be used to cache its input, to avoid repetition of computation in a multi-pass ...
virtual int32 NumFramesReady() const =0
returns the feature dimension.
virtual int32 Dim() const =0

◆ GetOutput() [2/2]

void kaldi::GetOutput ( OnlineFeatInputItf a,
Matrix< BaseFloat > *  output 
)

Definition at line 81 of file online-feat-test.cc.

References OnlineCacheInput::Compute(), OnlineFeatInputItf::Dim(), OnlineCacheInput::GetCachedData(), Rand(), and Matrix< Real >::Resize().

82  {
83  int32 dim = a->Dim();
84  OnlineCacheInput cache(a);
85  while (true) {
86  Matrix<BaseFloat> garbage;
87  int32 batch_size = 1 + Rand() % 10;
88  garbage.Resize(batch_size, dim); // some random requested amount.
89  if (!cache.Compute(&garbage)) // returns false when done.
90  break;
91  }
92  cache.GetCachedData(output);
93 }
virtual int32 Dim() const =0
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ GetPerFrameAcousticCosts()

void GetPerFrameAcousticCosts ( const Lattice nbest,
Vector< BaseFloat > *  per_frame_loglikes 
)

This function extracts the per-frame log likelihoods from a linear lattice (which we refer to as an 'nbest' lattice elsewhere in Kaldi code).

The dimension of *per_frame_loglikes will be set to the number of input symbols in 'nbest'. The elements of '*per_frame_loglikes' will be set to the .Value2() elements of the lattice weights, which represent the acoustic costs; you may want to scale this vector afterward by -1/acoustic_scale to get the original loglikes. If there are acoustic costs on input-epsilon arcs or the final-prob in 'nbest' (and this should not normally be the case in situations where it makes sense to call this function), they will be included to the cost of the preceding input symbol, or the following input symbol for input-epsilons encountered prior to any input symbol. If 'nbest' has no input symbols, 'per_frame_loglikes' will be set to the empty vector.

Definition at line 36 of file lattice-functions.cc.

References KALDI_ASSERT.

Referenced by AlignUtteranceWrapper().

36  {
37  using namespace fst;
39  vector<BaseFloat> loglikes;
40 
41  int32 cur_state = nbest.Start();
42  int32 prev_frame = -1;
43  BaseFloat eps_acwt = 0.0;
44  while(1) {
45  Weight w = nbest.Final(cur_state);
46  if (w != Weight::Zero()) {
47  KALDI_ASSERT(nbest.NumArcs(cur_state) == 0);
48  if (per_frame_loglikes != NULL) {
49  SubVector<BaseFloat> subvec(&(loglikes[0]), loglikes.size());
50  Vector<BaseFloat> vec(subvec);
51  *per_frame_loglikes = vec;
52  }
53  break;
54  } else {
55  KALDI_ASSERT(nbest.NumArcs(cur_state) == 1);
56  fst::ArcIterator<Lattice> iter(nbest, cur_state);
57  const Lattice::Arc &arc = iter.Value();
58  BaseFloat acwt = arc.weight.Value2();
59  if (arc.ilabel != 0) {
60  if (eps_acwt > 0) {
61  acwt += eps_acwt;
62  eps_acwt = 0.0;
63  }
64  loglikes.push_back(acwt);
65  prev_frame++;
66  } else if (acwt == acwt){
67  if (prev_frame > -1) {
68  loglikes[prev_frame] += acwt;
69  } else {
70  eps_acwt += acwt;
71  }
72  }
73  cur_state = arc.nextstate;
74  }
75  }
76 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
float BaseFloat
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetRandChar()

char kaldi::GetRandChar ( )

Definition at line 28 of file text-utils-test.cc.

References Rand().

Referenced by TestSplitStringToVector().

28  {
29  return static_cast<char>(32 + Rand() % 95); // between ' ' and '~'
30 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ GetRandDelim()

char kaldi::GetRandDelim ( )

Definition at line 33 of file text-utils-test.cc.

References Rand().

Referenced by TestSplitStringToVector().

33  {
34  if (Rand() % 2 == 0)
35  return static_cast<char>(33 + Rand() % 94); // between '!' and '~';
36  else
37  return ws_delim[Rand() % 4];
38 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
const char * ws_delim

◆ GetScaledTransitionLogProb()

static BaseFloat kaldi::GetScaledTransitionLogProb ( const TransitionModel trans_model,
int32  trans_id,
BaseFloat  transition_scale,
BaseFloat  self_loop_scale 
)
static

Definition at line 1065 of file hmm-utils.cc.

References TransitionModel::GetNonSelfLoopLogProb(), TransitionModel::GetTransitionLogProb(), TransitionModel::GetTransitionLogProbIgnoringSelfLoops(), TransitionModel::IsSelfLoop(), and TransitionModel::TransitionIdToTransitionState().

Referenced by AddTransitionProbs().

1068  {
1069  if (transition_scale == self_loop_scale) {
1070  return trans_model.GetTransitionLogProb(trans_id) * transition_scale;
1071  } else {
1072  if (trans_model.IsSelfLoop(trans_id)) {
1073  return self_loop_scale * trans_model.GetTransitionLogProb(trans_id);
1074  } else {
1075  int32 trans_state = trans_model.TransitionIdToTransitionState(trans_id);
1076  return self_loop_scale * trans_model.GetNonSelfLoopLogProb(trans_state)
1077  + transition_scale * trans_model.GetTransitionLogProbIgnoringSelfLoops(trans_id);
1078  // This could be simplified to
1079  // (self_loop_scale - transition_scale) * trans_model.GetNonSelfLoopLogProb(trans_state)
1080  // + trans_model.GetTransitionLogProb(trans_id);
1081  // this simplifies if self_loop_scale == 0.0
1082  }
1083  }
1084 }
kaldi::int32 int32

◆ GetSeenPhones()

void kaldi::GetSeenPhones ( BuildTreeStatsType stats,
int  P,
std::vector< int32 > *  phones_out 
)

Definition at line 32 of file build-tree-two-level.cc.

References CopySetToVector(), rnnlm::i, rnnlm::j, and KALDI_ASSERT.

Referenced by main().

32  {
33  // Get list of phones that we saw (in the central position P, although it
34  // shouldn't matter what position).
35 
36  std::set<int32> phones_set;
37  for (size_t i = 0 ; i < stats.size(); i++) {
38  const EventType &evec = stats[i].first;
39  for (size_t j = 0; j < evec.size(); j++) {
40  if (evec[j].first == P) { // "key" is position P
41  KALDI_ASSERT(evec[j].second != 0);
42  phones_set.insert(evec[j].second); // insert "value" of this
43  // phone.
44  }
45  }
46  CopySetToVector(phones_set, phones_out);
47  }
48 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetShortFileName()

static const char* kaldi::GetShortFileName ( const char *  path)
static

Definition at line 63 of file kaldi-error.cc.

Referenced by MessageLogger::MessageLogger().

63  {
64  if (path == nullptr)
65  return "";
66 
67  const char *prev = path, *last = path;
68  while ((path = std::strpbrk(path, "\\/")) != nullptr) {
69  ++path;
70  prev = last;
71  last = path;
72  }
73  return prev;
74 }

◆ GetSingleStatsDerivative()

void kaldi::GetSingleStatsDerivative ( double  ml_count,
double  ml_x_stats,
double  ml_x2_stats,
double  disc_count,
double  disc_x_stats,
double  disc_x2_stats,
double  model_mean,
double  model_var,
BaseFloat  min_variance,
double *  ml_x_stats_deriv,
double *  ml_x2_stats_deriv 
)

Definition at line 25 of file indirect-diff-diag-gmm.cc.

References KALDI_VLOG.

Referenced by GetStatsDerivative().

29  {
30 
31  double model_inv_var = 1.0/model_var,
32  model_inv_var_sq = model_inv_var*model_inv_var,
33  model_mean_sq = model_mean*model_mean;
34 
35  // First get derivative of discriminative objective function w.r.t. the
36  // model mean and variance.
37  // Below: eqs. 11 and 13 in 2005 ICASSP paper on fMPE. Note: the factor of
38  // kappa (in the fMPE case) is assumed to have been accounted for by
39  // scaling the num and den accs at the command-line level. We substituted
40  // eq. 12 into 13 and rearranged to get the second expression.
41  double diff_wrt_model_mean = (1.0/model_var) * (disc_x_stats - model_mean*disc_count),
42  diff_wrt_model_var =
43  0.5 * ((disc_x2_stats - 2*model_mean*disc_x_stats + disc_count*model_mean_sq)
44  * model_inv_var_sq
45  - disc_count*model_inv_var);
46 
47  double stats_mean = ml_x_stats / ml_count,
48  stats_var = ml_x2_stats / ml_count - (ml_x_stats / ml_count)*(ml_x_stats / ml_count);
49 
50  // We assume the "rescaling" update will be as follows. Apologies if this is
51  // a bit confusing. The idea is that if the mean and var from (stats versus
52  // model) differ we assume that the model will be updated with
53  // DoRescalingUpdate(), which takes two sets of ML accs (old and new). The old ML
54  // accs given to the update will be the current ml accumulators we have here in
55  // this function, and the new ML accs will be affected by change in fMPE transform.
56  // The update in DoRescalingUpdate() will preserve any current difference between
57  // the ml stats and the model [represented as a shift in mean and factor in variance].
58  // Concretely: the update in DoRescalingUpdate() will do:
59  //
60  // new_model_mean := old_model_mean + new_stats_mean - old_stats_mean (eq. 1)
61  // new_model_var := max(min_variance, old_model_var * new_stats_var / old_stats_var). (eq. 2)
62  //
63  // We're differentiating back through this process to new_stats_mean.
64  // If the model and the stats were actually the same (e.g. we had been doing ML updates),
65  // then all this is equivalent to what was in the original fMPE paper. It's just
66  // extended to make sense outside of that scenario where you're doing ML.
67 
68  double diff_wrt_stats_mean = diff_wrt_model_mean; // This comes from eq. 1 above.
69  double diff_wrt_stats_var;
70  if (model_var <= min_variance*1.01) {
71  diff_wrt_stats_var = 0.0; // model would be "pinned" at minimum variance.
72  KALDI_VLOG(2) << "Variance derivative is zero (min variance)";
73  } else {
74  diff_wrt_stats_var = diff_wrt_model_var * model_var / stats_var; // note:
75  // the factor "model_var / stats_var" comes from "old_model_var / old_stats_var" in eq. 2.
76  // Also note: the {old_,new_} versions of variables are numerically the same here, at the
77  // point where we're differentiating.
78  }
79 
80  // The next equations don't appear in the paper but represent the backpropagation
81  // of the derivative through the equations:
82  // stats_mean := ml_x_stats / ml_count
83  // stats_var := ml_x2_stats / ml_count - (ml_x_stats/ml_count)^2
84  // [we use stats_mean = ml_x_stats/ml_count, here].
85  *ml_x_stats_deriv = diff_wrt_stats_mean / ml_count - 2 * diff_wrt_stats_var * stats_mean / ml_count;
86  *ml_x2_stats_deriv = diff_wrt_stats_var / ml_count;
87 }
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ GetSkipLayers()

std::vector<bool> kaldi::GetSkipLayers ( const std::string &  skip_layers_str,
const int32  first_layer_idx,
const int32  last_layer_idx 
)

Definition at line 58 of file nnet-am-average.cc.

References KALDI_ERR, and SplitStringToIntegers().

Referenced by main().

60  {
61 
62  std::vector<bool> skip_layers(last_layer_idx, false);
63 
64  if (skip_layers_str.empty()) {
65  return skip_layers;
66  }
67 
68  std::vector<int> layer_indices;
69  bool ret = SplitStringToIntegers(skip_layers_str, ":", true, &layer_indices);
70  if (!ret) {
71  KALDI_ERR << "Cannot parse the skip layers specifier. It should be"
72  << "colon-separated list of integers";
73  }
74 
75  int min_elem = std::numeric_limits<int>().max(),
76  max_elem = std::numeric_limits<int>().min();
77 
78  std::vector<int>::iterator it;
79  for ( it = layer_indices.begin(); it != layer_indices.end(); ++it ) {
80  if ( *it < 0 )
81  *it = last_layer_idx + *it; // convert the negative indices to
82  // correct indices -- -1 would be the
83  // last one, -2 the one before the last
84  // and so on.
85  if (*it > max_elem)
86  max_elem = *it;
87 
88  if (*it < min_elem)
89  min_elem = *it;
90  }
91 
92  if (max_elem >= last_layer_idx) {
93  KALDI_ERR << "--skip-layers option has to be a colon-separated list"
94  << "of indices which are supposed to be skipped.\n"
95  << "Maximum expected index: " << last_layer_idx
96  << " got: " << max_elem ;
97  }
98  if (min_elem < first_layer_idx) {
99  KALDI_ERR << "--skip-layers option has to be a colon-separated list"
100  << "of indices which are supposed to be skipped.\n"
101  << "Minimum expected index: " << first_layer_idx
102  << " got: " << min_elem ;
103  }
104 
105  for ( it = layer_indices.begin(); it != layer_indices.end(); ++it ) {
106  skip_layers[*it] = true;
107  }
108  return skip_layers;
109 }
bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
Split a string (e.g.
Definition: text-utils.h:68
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ GetSplitTargets()

void GetSplitTargets ( const Vector< BaseFloat > &  state_occs,
int32  target_components,
BaseFloat  power,
BaseFloat  min_count,
std::vector< int32 > *  targets 
)

Get Gaussian-mixture or substate-mixture splitting targets, according to a power rule (e.g.

typically power = 0.2). Returns targets for number of mixture components (Gaussians, or sub-states), allocating the Gaussians or whatever according to a power of occupancy in order to acheive the total supplied "target". During splitting we ensure that each Gaussian [or sub-state] would get a count of at least "min-count", assuming counts were evenly distributed between Gaussians in a state. The vector "targets" will be resized to the appropriate dimension; its value at input is ignored.

Definition at line 116 of file model-common.cc.

References CountStats::CountStats(), VectorBase< Real >::Dim(), KALDI_WARN, CountStats::num_components, CountStats::occupancy, and CountStats::pdf_index.

Referenced by AmDiagGmm::MergeByCount(), LogisticRegression::MixUp(), SoftmaxComponent::MixUp(), AmDiagGmm::SplitByCount(), and AmSgmm2::SplitSubstates().

120  {
121  std::priority_queue<CountStats> split_queue;
122  int32 num_pdfs = state_occs.Dim();
123 
124  for (int32 pdf_index = 0; pdf_index < num_pdfs; pdf_index++) {
125  BaseFloat occ = pow(state_occs(pdf_index), power);
126  // initialize with one Gaussian per PDF, to put a floor
127  // of 1 on the #Gauss
128  split_queue.push(CountStats(pdf_index, 1, occ));
129  }
130 
131  for (int32 num_gauss = num_pdfs; num_gauss < target_components;) {
132  CountStats state_to_split = split_queue.top();
133  if (state_to_split.occupancy == 0) {
134  KALDI_WARN << "Could not split up to " << target_components
135  << " due to min-count = " << min_count
136  << " (or no counts at all)\n";
137  break;
138  }
139  split_queue.pop();
140  BaseFloat orig_occ = state_occs(state_to_split.pdf_index);
141  if ((state_to_split.num_components+1) * min_count >= orig_occ) {
142  state_to_split.occupancy = 0; // min-count active -> disallow splitting
143  // this state any more by setting occupancy = 0.
144  } else {
145  state_to_split.num_components++;
146  num_gauss++;
147  }
148  split_queue.push(state_to_split);
149  }
150  targets->resize(num_pdfs);
151  while (!split_queue.empty()) {
152  int32 pdf_index = split_queue.top().pdf_index;
153  int32 pdf_tgt_comp = split_queue.top().num_components;
154  (*targets)[pdf_index] = pdf_tgt_comp;
155  split_queue.pop();
156  }
157 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ GetStatsDerivative() [1/2]

void kaldi::GetStatsDerivative ( const DiagGmm gmm,
const AccumDiagGmm num_acc,
const AccumDiagGmm den_acc,
const AccumDiagGmm ml_acc,
BaseFloat  min_variance,
BaseFloat  min_gaussian_occupancy,
AccumDiagGmm out_accs 
)

Definition at line 94 of file indirect-diff-diag-gmm.cc.

References AccumDiagGmm::AddStatsForComponent(), rnnlm::d, DiagGmm::Dim(), AccumDiagGmm::Dim(), AccumDiagGmm::Flags(), GetSingleStatsDerivative(), KALDI_ASSERT, KALDI_WARN, kGmmAll, kGmmMeans, kGmmVariances, AccumDiagGmm::mean_accumulator(), DiagGmmNormal::means_, DiagGmm::NumGauss(), AccumDiagGmm::NumGauss(), AccumDiagGmm::occupancy(), AccumDiagGmm::Resize(), AccumDiagGmm::variance_accumulator(), and DiagGmmNormal::vars_.

Referenced by GetStatsDerivative(), and main().

100  {
101  out_accs->Resize(gmm, kGmmAll);
102  int32 num_gauss = gmm.NumGauss(), dim = gmm.Dim();
103  KALDI_ASSERT(num_gauss == num_acc.NumGauss() && dim == num_acc.Dim());
104  KALDI_ASSERT(num_gauss == den_acc.NumGauss()); // don't check den dim--
105  // in the "compressed" form of stats (where num acc stores diff),
106  // it could be zero.
107  KALDI_ASSERT(num_gauss == ml_acc.NumGauss() && dim == ml_acc.Dim());
108 
109  KALDI_ASSERT((ml_acc.Flags() & (kGmmMeans|kGmmVariances)) ==
111  KALDI_ASSERT((num_acc.Flags() & (kGmmMeans|kGmmVariances)) ==
113  DiagGmmNormal gmm_normal(gmm);
114 
115  // if have_den_stats == false, we assume the num and den have been
116  // "compressed" by putting the difference in mean and var stats in num.
117  bool have_den_stats = ((den_acc.Flags() & (kGmmMeans|kGmmVariances)) != 0);
118 
119  for (int32 gauss = 0; gauss < num_gauss; gauss++) {
120  Vector<double> x_stats_deriv(dim), x2_stats_deriv(dim);
121  double num_count = num_acc.occupancy()(gauss),
122  den_count = den_acc.occupancy()(gauss),
123  ml_count = ml_acc.occupancy()(gauss);
124 
125  if (ml_count <= min_gaussian_occupancy) {
126  // This Gaussian won't be updated since has small count
127  KALDI_WARN << "Skipping Gaussian because very small ML count: (num,den,ml) = "
128  << num_count << ", " << den_count << ", " << ml_count;
129  } else {
130  double disc_count = num_count - den_count;
131  for (int32 d = 0; d < dim; d++) {
132  double disc_x_acc = num_acc.mean_accumulator()(gauss, d)
133  - (have_den_stats ? den_acc.mean_accumulator()(gauss, d) : 0.0),
134  disc_x2_acc = num_acc.variance_accumulator()(gauss, d)
135  - (have_den_stats ? den_acc.variance_accumulator()(gauss, d) : 0.0),
136  ml_x_acc = ml_acc.mean_accumulator()(gauss, d),
137  ml_x2_acc = ml_acc.variance_accumulator()(gauss, d),
138  model_mean = gmm_normal.means_(gauss, d),
139  model_var = gmm_normal.vars_(gauss, d);
140 
141  double x_acc_deriv = 0.0, x2_acc_deriv = 0.0;
142  GetSingleStatsDerivative(ml_count, ml_x_acc, ml_x2_acc,
143  disc_count, disc_x_acc, disc_x2_acc,
144  model_mean, model_var, min_variance,
145  &x_acc_deriv, &x2_acc_deriv);
146 
147  x_stats_deriv(d) = x_acc_deriv;
148  x2_stats_deriv(d) = x2_acc_deriv;
149  }
150  // set the stats to these quantities (we're adding, but the stats
151  // are currently zero).
152  out_accs->AddStatsForComponent(gauss, 0.0, x_stats_deriv, x2_stats_deriv);
153  }
154  }
155 }
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void GetSingleStatsDerivative(double ml_count, double ml_x_stats, double ml_x2_stats, double disc_count, double disc_x_stats, double disc_x2_stats, double model_mean, double model_var, BaseFloat min_variance, double *ml_x_stats_deriv, double *ml_x2_stats_deriv)

◆ GetStatsDerivative() [2/2]

void GetStatsDerivative ( const AmDiagGmm gmm,
const AccumAmDiagGmm num_accs,
const AccumAmDiagGmm den_accs,
const AccumAmDiagGmm ml_accs,
BaseFloat  min_variance,
BaseFloat  min_gaussian_occupancy,
AccumAmDiagGmm out_accs 
)

Definition at line 157 of file indirect-diff-diag-gmm.cc.

References AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), GetStatsDerivative(), AccumAmDiagGmm::Init(), KALDI_ASSERT, kGmmAll, AccumAmDiagGmm::NumAccs(), and AmDiagGmm::NumPdfs().

163  {
164  out_accs->Init(gmm, kGmmAll);
165  int32 num_pdfs = gmm.NumPdfs();
166  KALDI_ASSERT(num_accs.NumAccs() == num_pdfs);
167  KALDI_ASSERT(den_accs.NumAccs() == num_pdfs);
168  KALDI_ASSERT(ml_accs.NumAccs() == num_pdfs);
169  for (int32 pdf = 0; pdf < num_pdfs; pdf++)
170  GetStatsDerivative(gmm.GetPdf(pdf), num_accs.GetAcc(pdf), den_accs.GetAcc(pdf),
171  ml_accs.GetAcc(pdf), min_variance, min_gaussian_occupancy,
172  &(out_accs->GetAcc(pdf)));
173 
174 }
void GetStatsDerivative(const AmDiagGmm &gmm, const AccumAmDiagGmm &num_accs, const AccumAmDiagGmm &den_accs, const AccumAmDiagGmm &ml_accs, BaseFloat min_variance, BaseFloat min_gaussian_occupancy, AccumAmDiagGmm *out_accs)
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetTimeString()

std::string kaldi::GetTimeString ( int32  t_beg,
int32  t_end,
BaseFloat  time_unit 
)

Definition at line 88 of file online2-tcp-nnet3-decode-faster.cc.

Referenced by main().

88  {
89  char buffer[100];
90  double t_beg2 = t_beg * time_unit;
91  double t_end2 = t_end * time_unit;
92  snprintf(buffer, 100, "%.2f %.2f", t_beg2, t_end2);
93  return std::string(buffer);
94 }

◆ GetToLengthMap()

EventMap* kaldi::GetToLengthMap ( const BuildTreeStatsType stats,
int32  P,
const std::vector< EventValueType > *  phones,
int32  default_length 
)

Definition at line 760 of file build-tree-utils.cc.

References rnnlm::i, KALDI_ERR, kPdfClass, and SplitStatsByKey().

762  {
763  std::vector<BuildTreeStatsType> stats_by_phone;
764  try {
765  SplitStatsByKey(stats, P, &stats_by_phone);
766  } catch(const KaldiFatalError &) {
767  KALDI_ERR <<
768  "You seem to have provided invalid stats [no central-phone key].";
769  }
770  std::map<EventValueType, EventAnswerType> phone_to_length;
771  for (size_t p = 0; p < stats_by_phone.size(); p++) {
772  if (! stats_by_phone[p].empty()) {
773  std::vector<BuildTreeStatsType> stats_by_length;
774  try {
775  SplitStatsByKey(stats_by_phone[p], kPdfClass, &stats_by_length);
776  } catch(const KaldiFatalError &) {
777  KALDI_ERR <<
778  "You seem to have provided invalid stats [no position key].";
779  }
780  size_t length = stats_by_length.size();
781  for (size_t i = 0; i < length; i++) {
782  if (stats_by_length[i].empty()) {
783  KALDI_ERR << "There are no stats available for position " << i
784  << " of phone " << p;
785  }
786  }
787  phone_to_length[p] = length;
788  }
789  }
790  if (phones != NULL) { // set default length for unseen phones.
791  for (size_t i = 0; i < phones->size(); i++) {
792  if (phone_to_length.count( (*phones)[i] ) == 0) { // unseen.
793  phone_to_length[(*phones)[i]] = default_length;
794  }
795  }
796  }
797  EventMap *ans = new TableEventMap(P, phone_to_length);
798  return ans;
799 }
void SplitStatsByKey(const BuildTreeStatsType &stats_in, EventKeyType key, std::vector< BuildTreeStatsType > *stats_out)
SplitStatsByKey splits stats up according to the value of a particular key, which must be always defi...
static const EventKeyType kPdfClass
Definition: context-dep.h:39
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ GetTotalPosterior()

static BaseFloat kaldi::GetTotalPosterior ( const std::vector< std::pair< int32, BaseFloat > > &  post_entry)
inlinestatic

Definition at line 429 of file posterior.cc.

Referenced by VectorToPosteriorEntry().

430  {
431  BaseFloat tot = 0.0;
432  std::vector<std::pair<int32, BaseFloat> >::const_iterator
433  iter = post_entry.begin(), end = post_entry.end();
434  for (; iter != end; ++iter) {
435  tot += iter->second;
436  }
437  return tot;
438 }
float BaseFloat
Definition: kaldi-types.h:29

◆ GetTreeStructure()

bool GetTreeStructure ( const EventMap map,
int32 num_leaves,
std::vector< int32 > *  parents 
)

This function gets the tree structure of the EventMap "map" in a convenient form.

If "map" corresponds to a tree structure (not necessarily binary) with leaves uniquely numbered from 0 to num_leaves-1, then the function will return true, output "num_leaves", and set "parent" to a vector of size equal to the number of nodes in the tree (nonleaf and leaf), where each index corresponds to a node and the leaf indices correspond to the values returned by the EventMap from that leaf; for an index i, parent[i] equals the parent of that node in the tree structure, where parent[i] > i, except for the last (root) node where parent[i] == i. If the EventMap does not have this structure (e.g. if multiple different leaf nodes share the same number), then it will return false.

Definition at line 429 of file event-map.cc.

References GetTreeStructureInternal(), rnnlm::i, IsLeafNode(), KALDI_ASSERT, and EventMap::Map().

Referenced by TestEventMap().

431  {
432  KALDI_ASSERT (num_leaves != NULL && parents != NULL);
433 
434  if (IsLeafNode(&map)) { // handle degenerate case where root is a leaf.
435  int32 leaf;
436  if (!map.Map(EventType(), &leaf)
437  || leaf != 0) return false;
438  *num_leaves = 1;
439  parents->resize(1);
440  (*parents)[0] = 0;
441  return true;
442  }
443 
444 
445  // This vector gives the address of nonleaf nodes in the tree,
446  // in a numbering where 0 is the root and children always come
447  // after parents.
448  std::vector<const EventMap*> nonleaf_nodes;
449 
450  // Map from each nonleaf node to its parent node
451  // (or to itself for the root node).
452  std::map<const EventMap*, const EventMap*> nonleaf_parents;
453 
454  // Map from leaf nodes to their parent nodes.
455  std::vector<const EventMap*> leaf_parents;
456 
457  if (!GetTreeStructureInternal(map, &nonleaf_nodes,
458  &nonleaf_parents,
459  &leaf_parents)) return false;
460 
461  *num_leaves = leaf_parents.size();
462  int32 num_nodes = leaf_parents.size() + nonleaf_nodes.size();
463 
464  std::map<const EventMap*, int32> nonleaf_indices;
465 
466  // number the nonleaf indices so they come after the leaf
467  // indices and the root is last.
468  for (size_t i = 0; i < nonleaf_nodes.size(); i++)
469  nonleaf_indices[nonleaf_nodes[i]] = num_nodes - i - 1;
470 
471  parents->resize(num_nodes);
472  for (size_t i = 0; i < leaf_parents.size(); i++) {
473  KALDI_ASSERT(nonleaf_indices.count(leaf_parents[i]) != 0);
474  (*parents)[i] = nonleaf_indices[leaf_parents[i]];
475  }
476  for (size_t i = 0; i < nonleaf_nodes.size(); i++) {
477  KALDI_ASSERT(nonleaf_indices.count(nonleaf_nodes[i]) != 0);
478  KALDI_ASSERT(nonleaf_parents.count(nonleaf_nodes[i]) != 0);
479  KALDI_ASSERT(nonleaf_indices.count(nonleaf_parents[nonleaf_nodes[i]]) != 0);
480  int32 index = nonleaf_indices[nonleaf_nodes[i]],
481  parent_index = nonleaf_indices[nonleaf_parents[nonleaf_nodes[i]]];
482  KALDI_ASSERT(index > 0 && parent_index >= index);
483  (*parents)[index] = parent_index;
484  }
485  for (int32 i = 0; i < num_nodes; i++)
486  KALDI_ASSERT ((*parents)[i] > i || (i+1==num_nodes && (*parents)[i] == i));
487  return true;
488 }
kaldi::int32 int32
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
static bool GetTreeStructureInternal(const EventMap &map, std::vector< const EventMap *> *nonleaf_nodes, std::map< const EventMap *, const EventMap *> *nonleaf_parents, std::vector< const EventMap *> *leaf_parents)
Definition: event-map.cc:375
static bool IsLeafNode(const EventMap *e)
Definition: event-map.cc:354
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetTreeStructureInternal()

static bool kaldi::GetTreeStructureInternal ( const EventMap map,
std::vector< const EventMap *> *  nonleaf_nodes,
std::map< const EventMap *, const EventMap *> *  nonleaf_parents,
std::vector< const EventMap *> *  leaf_parents 
)
static

Definition at line 375 of file event-map.cc.

References EventMap::GetChildren(), rnnlm::i, IsLeafNode(), KALDI_ASSERT, KALDI_WARN, and EventMap::Map().

Referenced by GetTreeStructure().

379  {
380 
381  std::vector<const EventMap*> queue; // parents to be processed.
382 
383  const EventMap *top_node = &map;
384 
385  queue.push_back(top_node);
386  nonleaf_nodes->push_back(top_node);
387  (*nonleaf_parents)[top_node] = top_node;
388 
389  while (!queue.empty()) {
390  const EventMap *parent = queue.back();
391  queue.pop_back();
392  std::vector<EventMap*> children;
393  parent->GetChildren(&children);
394  KALDI_ASSERT(!children.empty());
395  for (size_t i = 0; i < children.size(); i++) {
396  EventMap *child = children[i];
397  if (IsLeafNode(child)) {
398  int32 leaf;
399  if (!child->Map(EventType(), &leaf)
400  || leaf < 0) return false;
401  if (static_cast<int32>(leaf_parents->size()) <= leaf)
402  leaf_parents->resize(leaf+1, NULL);
403  if ((*leaf_parents)[leaf] != NULL) {
404  KALDI_WARN << "Repeated leaf! Did you suppress leaf clustering when building the tree?";
405  return false; // repeated leaf.
406  }
407  (*leaf_parents)[leaf] = parent;
408  } else {
409  nonleaf_nodes->push_back(child);
410  (*nonleaf_parents)[child] = parent;
411  queue.push_back(child);
412  }
413  }
414  }
415 
416  for (size_t i = 0; i < leaf_parents->size(); i++)
417  if ((*leaf_parents)[i] == NULL) {
418  KALDI_WARN << "non-consecutively numbered leaves";
419  return false;
420  }
421  // non-consecutively numbered leaves.
422 
423  KALDI_ASSERT(!leaf_parents->empty()); // or no leaves.
424 
425  return true;
426 }
kaldi::int32 int32
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
#define KALDI_WARN
Definition: kaldi-error.h:150
static bool IsLeafNode(const EventMap *e)
Definition: event-map.cc:354
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ GetUtterancePairs()

void kaldi::GetUtterancePairs ( const std::string &  reco2file_and_channel_rxfilename,
std::vector< std::vector< std::string > > *  utt_pairs 
)

Definition at line 34 of file compute-cmvn-stats-two-channel.cc.

References rnnlm::i, KALDI_ERR, KALDI_WARN, PrintableRxfilename(), SplitStringToVector(), and Input::Stream().

Referenced by main().

35  {
36  Input ki(reco2file_and_channel_rxfilename);
37  std::string line;
38  std::map<std::string, std::vector<std::string> > call_to_uttlist;
39  while (std::getline(ki.Stream(), line)) {
40  std::vector<std::string> split_line;
41  SplitStringToVector(line, " \t\r", true, &split_line);
42  if (split_line.size() != 3) {
43  KALDI_ERR << "Expecting 3 fields per line of reco2file_and_channel file "
44  << PrintableRxfilename(reco2file_and_channel_rxfilename)
45  << ", got: " << line;
46  }
47  // lines like: sw02001-A sw02001 A
48  std::string utt = split_line[0],
49  call = split_line[1];
50  call_to_uttlist[call].push_back(utt);
51  }
52  for (std::map<std::string, std::vector<std::string> >::const_iterator
53  iter = call_to_uttlist.begin(); iter != call_to_uttlist.end(); ++iter) {
54  const std::vector<std::string> &uttlist = iter->second;
55  if (uttlist.size() == 2) {
56  utt_pairs->push_back(uttlist);
57  } else {
58  KALDI_WARN << "Call " << iter->first << " has " << uttlist.size()
59  << " utterances, expected two; treating them singly.";
60  for (size_t i = 0; i < uttlist.size(); i++) {
61  std::vector<std::string> singleton_list;
62  singleton_list.push_back(uttlist[i]);
63  utt_pairs->push_back(singleton_list);
64  }
65  }
66  }
67 }
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string PrintableRxfilename(const std::string &rxfilename)
PrintableRxfilename turns the rxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:61

◆ GetWeights()

void GetWeights ( const std::string &  weights_str,
int32  num_inputs,
std::vector< BaseFloat > *  weights 
)

Definition at line 30 of file nnet-am-average.cc.

References rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_WARN, and SplitStringToFloats().

Referenced by main().

32  {
33  KALDI_ASSERT(num_inputs >= 1);
34  if (!weights_str.empty()) {
35  SplitStringToFloats(weights_str, ":", true, weights);
36  if (weights->size() != num_inputs) {
37  KALDI_ERR << "--weights option must be a colon-separated list "
38  << "with " << num_inputs << " elements, got: "
39  << weights_str;
40  }
41  } else {
42  for (int32 i = 0; i < num_inputs; i++)
43  weights->push_back(1.0 / num_inputs);
44  }
45  // normalize the weights to sum to one.
46  float weight_sum = 0.0;
47  for (int32 i = 0; i < num_inputs; i++)
48  weight_sum += (*weights)[i];
49  for (int32 i = 0; i < num_inputs; i++)
50  (*weights)[i] = (*weights)[i] / weight_sum;
51  if (fabs(weight_sum - 1.0) > 0.01) {
52  KALDI_WARN << "Normalizing weights to sum to one, sum was " << weight_sum;
53  }
54 }
bool SplitStringToFloats(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< F > *out)
Definition: text-utils.cc:30
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Givens()

void kaldi::Givens ( Real  a,
Real  b,
Real *  c,
Real *  s 
)
inline

Create Givens rotations, as in Golub and Van Loan 3rd ed., page 216.

Definition at line 221 of file qr.cc.

Referenced by QrStep().

221  {
222  if (b == 0) {
223  *c = 1;
224  *s = 0;
225  } else {
226  if (std::abs(b) > std::abs(a)) {
227  Real tau = -a / b;
228  *s = 1 / std::sqrt(1 + tau*tau);
229  *c = *s * tau;
230  } else {
231  Real tau = -b / a;
232  *c = 1 / std::sqrt(1 + tau*tau);
233  *s = *c * tau;
234  }
235  }
236 }

◆ GmmFlagsToString()

std::string GmmFlagsToString ( GmmFlagsType  flags)

Convert GMM flags to string.

Definition at line 43 of file model-common.cc.

References kGmmMeans, kGmmTransitions, kGmmVariances, and kGmmWeights.

Referenced by AccumFullGmm::Read(), AccumDiagGmm::Read(), UnitTestEstimateMmieDiagGmm(), and UpdateEbwDiagGmm().

43  {
44  std::string ans;
45  if (flags & kGmmMeans) ans += "m";
46  if (flags & kGmmVariances) ans += "v";
47  if (flags & kGmmWeights) ans += "w";
48  if (flags & kGmmTransitions) ans += "t";
49  return ans;
50 }

◆ HandleOutput()

void kaldi::HandleOutput ( bool  determinize,
const fst::SymbolTable *  word_syms,
nnet3::NnetBatchDecoder decoder,
CompactLatticeWriter clat_writer,
LatticeWriter lat_writer 
)

Definition at line 35 of file nnet3-latgen-faster-batch.cc.

References NnetBatchDecoder::GetOutput(), and TableWriter< Holder >::Write().

Referenced by main().

39  {
40  // Write out any lattices that are ready.
41  std::string output_utterance_id, sentence;
42  if (determinize) {
43  CompactLattice clat;
44  while (decoder->GetOutput(&output_utterance_id, &clat, &sentence)) {
45  if (word_syms != NULL)
46  std::cerr << output_utterance_id << ' ' << sentence << '\n';
47  clat_writer->Write(output_utterance_id, clat);
48  }
49  } else {
50  Lattice lat;
51  while (decoder->GetOutput(&output_utterance_id, &lat, &sentence)) {
52  if (word_syms != NULL)
53  std::cerr << output_utterance_id << ' ' << sentence << '\n';
54  lat_writer->Write(output_utterance_id, lat);
55  }
56  }
57 }
void Write(const std::string &key, const T &value) const
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
bool GetOutput(std::string *utterance_id, CompactLattice *clat, std::string *sentence)
The user should call this to obtain output (This version should only be called if config...

◆ HouseBackward()

void kaldi::HouseBackward ( MatrixIndexT  dim,
const Real *  x,
Real *  v,
Real *  beta 
)

Definition at line 102 of file qr.cc.

References cblas_Xscal(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_ISFINITE, KALDI_ISINF, and KALDI_ISNAN.

Referenced by SpMatrix< float >::Tridiagonalize().

102  {
103  KALDI_ASSERT(dim > 0);
104  // To avoid overflow, we first compute the max of x_ (or
105  // one if that's zero, and we'll replace "x" by x/max(x_i)
106  // below. The householder vector is anyway invariant to
107  // the magnitude of x. We could actually avoid this extra loop
108  // over x if we wanted to be a bit smarter, but anyway this
109  // doesn't dominate the O(N) performance of the algorithm.
110  Real s; // s is a scale on x.
111  {
112  Real max_x = std::numeric_limits<Real>::min();
113  for (MatrixIndexT i = 0; i < dim; i++)
114  max_x = std::max(max_x, (x[i] < 0 ? -x[i] : x[i]));
115  s = 1.0 / max_x;
116  }
117  Real sigma = 0.0;
118  v[dim-1] = 1.0;
119  for (MatrixIndexT i = 0; i + 1 < dim; i++) {
120  sigma += (x[i] * s) * (x[i] * s);
121  v[i] = x[i] * s;
122  }
123  KALDI_ASSERT(KALDI_ISFINITE(sigma) &&
124  "Tridiagonalizing matrix that is too large or has NaNs.");
125  if (sigma == 0.0) *beta = 0.0;
126  else {
127  Real x1 = x[dim-1] * s, mu = std::sqrt(x1 * x1 + sigma);
128  if (x1 <= 0) {
129  v[dim-1] = x1 - mu;
130  } else {
131  v[dim-1] = -sigma / (x1 + mu);
132  KALDI_ASSERT(KALDI_ISFINITE(v[dim-1]));
133  }
134  Real v1 = v[dim-1];
135  Real v1sq = v1 * v1;
136  *beta = 2 * v1sq / (sigma + v1sq);
137  Real inv_v1 = 1.0 / v1;
138  if (KALDI_ISINF(inv_v1)) {
139  // can happen if v1 is denormal.
140  KALDI_ASSERT(v1 == v1 && v1 != 0.0);
141  for (MatrixIndexT i = 0; i < dim; i++) v[i] /= v1;
142  } else {
143  cblas_Xscal(dim, inv_v1, v, 1);
144  }
145  if (KALDI_ISNAN(inv_v1)) {
146  KALDI_ERR << "NaN encountered in HouseBackward";
147  }
148  }
149 }
#define KALDI_ISINF
Definition: kaldi-math.h:73
#define KALDI_ISFINITE(x)
Definition: kaldi-math.h:74
int32 MatrixIndexT
Definition: matrix-common.h:98
void cblas_Xscal(const int N, const float alpha, float *data, const int inc)
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ISNAN
Definition: kaldi-math.h:72
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Hypot() [1/2]

double kaldi::Hypot ( double  x,
double  y 
)
inline

Definition at line 354 of file kaldi-math.h.

Referenced by EigenvalueDecomposition< Real >::Tql2().

354 { return hypot(x, y); }

◆ Hypot() [2/2]

float kaldi::Hypot ( float  x,
float  y 
)
inline

Definition at line 355 of file kaldi-math.h.

355 { return hypotf(x, y); }

◆ IncreaseTransformDimension()

void IncreaseTransformDimension ( int32  new_dimension,
Matrix< BaseFloat > *  mat 
)

Definition at line 26 of file extend-transform-dim.cc.

References VectorBase< Real >::CopyColFromMat(), rnnlm::d, rnnlm::i, KALDI_ERR, kCopyData, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and Matrix< Real >::Resize().

Referenced by main().

27  {
28  int32 d = mat->NumRows();
29  if (new_dimension < d)
30  KALDI_ERR << "--new-dimension argument invalid or not specified: "
31  << new_dimension << " < " << d;
32  if (mat->NumCols() == d) { // linear transform d->d
33  mat->Resize(new_dimension, new_dimension, kCopyData);
34  for (int32 i = d; i < new_dimension; i++)
35  (*mat)(i, i) = 1.0; // set new dims to unit matrix.
36  } else if (mat->NumCols() == d+1) { // affine transform d->d.
37  Vector<BaseFloat> offset(mat->NumRows());
38  offset.CopyColFromMat(*mat, d);
39  mat->Resize(d, d, kCopyData); // remove offset from mat->
40  mat->Resize(new_dimension, new_dimension+1, kCopyData); // extend with zeros.
41  for (int32 i = d; i < new_dimension; i++)
42  (*mat)(i, i) = 1.0; // set new dims to unit matrix.
43  for (int32 i = 0; i < d; i++) // and set offset [last column]
44  (*mat)(i, new_dimension) = offset(i);
45  } else {
46  KALDI_ERR << "Input matrix has unexpected dimension " << d
47  << " x " << mat->NumCols();
48  }
49 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
void CopyColFromMat(const MatrixBase< OtherReal > &M, MatrixIndexT col)
Extracts a column of the matrix M.
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ InitAmGmm()

void kaldi::InitAmGmm ( const BuildTreeStatsType stats,
const EventMap to_pdf_map,
AmDiagGmm am_gmm,
const TransitionModel trans_model,
BaseFloat  var_floor 
)

InitAmGmm initializes the GMM with one Gaussian per state.

Definition at line 35 of file gmm-init-model.cc.

References AmDiagGmm::AddPdf(), count, GaussClusterable::count(), DeletePointers(), GetPhonesForPdfs(), rnnlm::i, KALDI_ASSERT, KALDI_WARN, EventMap::MaxResult(), SplitStatsByMap(), SumClusterable(), and SumStatsVec().

Referenced by main().

39  {
40  // Get stats split by tree-leaf ( == pdf):
41  std::vector<BuildTreeStatsType> split_stats;
42  SplitStatsByMap(stats, to_pdf_map, &split_stats);
43 
44  split_stats.resize(to_pdf_map.MaxResult() + 1); // ensure that
45  // if the last leaf had no stats, this vector still has the right size.
46 
47  // Make sure each leaf has stats.
48  for (size_t i = 0; i < split_stats.size(); i++) {
49  if (split_stats[i].empty()) {
50  std::vector<int32> bad_pdfs(1, i), bad_phones;
51  GetPhonesForPdfs(trans_model, bad_pdfs, &bad_phones);
52  std::ostringstream ss;
53  for (int32 idx = 0; idx < bad_phones.size(); idx ++)
54  ss << bad_phones[idx] << ' ';
55  KALDI_WARN << "Tree has pdf-id " << i
56  << " with no stats; corresponding phone list: " << ss.str();
57  /*
58  This probably means you have phones that were unseen in training
59  and were not shared with other phones in the roots file.
60  You should modify your roots file as necessary to fix this.
61  (i.e. share that phone with a similar but seen phone on one line
62  of the roots file). Be sure to regenerate roots.int from roots.txt,
63  if using s5 scripts. To work out the phone, search for
64  pdf-id i in the output of show-transitions (for this model). */
65  }
66  }
67  std::vector<Clusterable*> summed_stats;
68  SumStatsVec(split_stats, &summed_stats);
69  Clusterable *avg_stats = SumClusterable(summed_stats);
70  KALDI_ASSERT(avg_stats != NULL && "No stats available in gmm-init-model.");
71  for (size_t i = 0; i < summed_stats.size(); i++) {
72  GaussClusterable *c =
73  static_cast<GaussClusterable*>(summed_stats[i] != NULL ? summed_stats[i] : avg_stats);
74  DiagGmm gmm(*c, var_floor);
75  am_gmm->AddPdf(gmm);
76  BaseFloat count = c->count();
77  if (count < 100) {
78  std::vector<int32> bad_pdfs(1, i), bad_phones;
79  GetPhonesForPdfs(trans_model, bad_pdfs, &bad_phones);
80  std::ostringstream ss;
81  for (int32 idx = 0; idx < bad_phones.size(); idx ++)
82  ss << bad_phones[idx] << ' ';
83  KALDI_WARN << "Very small count for state " << i << ": "
84  << count << "; corresponding phone list: " << ss.str();
85  }
86  }
87  DeletePointers(&summed_stats);
88  delete avg_stats;
89 }
void AddPdf(const DiagGmm &gmm)
Adds a GMM to the model, and increments the total number of PDFs.
Definition: am-diag-gmm.cc:57
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
virtual EventAnswerType MaxResult() const
Definition: event-map.h:142
void SplitStatsByMap(const BuildTreeStatsType &stats, const EventMap &e, std::vector< BuildTreeStatsType > *stats_out)
Splits stats according to the EventMap, indexing them at output by the leaf type. ...
kaldi::int32 int32
const size_t count
bool GetPhonesForPdfs(const TransitionModel &trans_model, const std::vector< int32 > &pdfs, std::vector< int32 > *phones)
Works out which phones might correspond to the given pdfs.
float BaseFloat
Definition: kaldi-types.h:29
void SumStatsVec(const std::vector< BuildTreeStatsType > &stats_in, std::vector< Clusterable *> *stats_out)
Sum a vector of stats.
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Definition for Gaussian Mixture Model with diagonal covariances.
Definition: diag-gmm.h:42
GaussClusterable wraps Gaussian statistics in a form accessible to generic clustering algorithms...
Clusterable * SumClusterable(const std::vector< Clusterable *> &vec)
Sums stats (ptrs may be NULL). Returns NULL if no non-NULL stats present.

◆ InitAmGmmFromOld()

void kaldi::InitAmGmmFromOld ( const BuildTreeStatsType stats,
const EventMap to_pdf_map,
int32  N,
int32  P,
const std::string &  old_tree_rxfilename,
const std::string &  old_model_rxfilename,
BaseFloat  var_floor,
AmDiagGmm am_gmm 
)

InitAmGmmFromOld initializes the GMM based on a previously trained model and tree, which must require no more phonetic context than the current tree.

It does this by finding the closest PDF in the old model, to any given PDF in the new model. Here, "closest" is defined as: has the largest count in common from the tree stats.

Definition at line 116 of file gmm-init-model.cc.

References AmDiagGmm::AddPdf(), ContextDependency::CentralPosition(), ContextDependency::ContextWidth(), ConvertStats(), AmDiagGmm::GetPdf(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_WARN, EventMap::Map(), EventMap::MaxResult(), AmDiagGmm::NumPdfs(), AmDiagGmm::Read(), ContextDependency::Read(), TransitionModel::Read(), SplitStatsByMap(), Input::Stream(), SumStats(), and ContextDependency::ToPdfMap().

Referenced by main().

123  {
124 
125  AmDiagGmm old_am_gmm;
126  ContextDependency old_tree;
127  { // Read old_gm_gmm
128  bool binary_in;
129  TransitionModel old_trans_model;
130  Input ki(old_model_rxfilename, &binary_in);
131  old_trans_model.Read(ki.Stream(), binary_in);
132  old_am_gmm.Read(ki.Stream(), binary_in);
133  }
134  { // Read tree.
135  bool binary_in;
136  Input ki(old_tree_rxfilename, &binary_in);
137  old_tree.Read(ki.Stream(), binary_in);
138  }
139 
140 
141  // Get stats split by (new) tree-leaf ( == pdf):
142  std::vector<BuildTreeStatsType> split_stats;
143  SplitStatsByMap(stats, to_pdf_map, &split_stats);
144  // Make sure each leaf has stats.
145  for (size_t i = 0; i < split_stats.size(); i++) {
146  if (split_stats[i].empty()) {
147  KALDI_WARN << "Leaf " << i << " of new tree has no stats.";
148  }
149  }
150  if (static_cast<int32>(split_stats.size()) != to_pdf_map.MaxResult() + 1) {
151  KALDI_ASSERT(static_cast<int32>(split_stats.size()) <
152  to_pdf_map.MaxResult() + 1);
153  KALDI_WARN << "Tree may have final leaf with no stats.";
154  split_stats.resize(to_pdf_map.MaxResult() + 1);
155  // avoid indexing errors later.
156  }
157 
158  int32 oldN = old_tree.ContextWidth(), oldP = old_tree.CentralPosition();
159 
160  // avg_stats will be used for leaves that have no stats.
161  Clusterable *avg_stats = SumStats(stats);
162  GaussClusterable *avg_stats_gc = dynamic_cast<GaussClusterable*>(avg_stats);
163  KALDI_ASSERT(avg_stats_gc != NULL && "Empty stats input.");
164  DiagGmm avg_gmm(*avg_stats_gc, var_floor);
165  delete avg_stats;
166  avg_stats = NULL;
167  avg_stats_gc = NULL;
168 
169  const EventMap &old_map = old_tree.ToPdfMap();
170 
171  KALDI_ASSERT(am_gmm->NumPdfs() == 0);
172  int32 num_pdfs = static_cast<int32>(split_stats.size());
173  for (int32 pdf = 0; pdf < num_pdfs; pdf++) {
174  BuildTreeStatsType &my_stats = split_stats[pdf];
175  // The next statement converts the stats to a possibly narrower older
176  // context-width (e.g. triphone -> monophone).
177  // note: don't get confused by the "old" and "new" in the parameters
178  // to ConvertStats. The next line is correct.
179  bool ret = ConvertStats(N, P, oldN, oldP, &my_stats);
180  if (!ret)
181  KALDI_ERR << "InitAmGmmFromOld: old system has wider context "
182  "so cannot convert stats.";
183  // oldpdf_to_count works out a map from old pdf-id to count (for stats
184  // that align to this "new" pdf... we'll use it to work out the old pdf-id
185  // that's "closest" in stats overlap to this new pdf ("pdf").
186  std::map<int32, BaseFloat> oldpdf_to_count;
187  for (size_t i = 0; i < my_stats.size(); i++) {
188  EventType evec = my_stats[i].first;
189  EventAnswerType ans;
190  bool ret = old_map.Map(evec, &ans);
191  if (!ret) { KALDI_ERR << "Could not map context using old tree."; }
192  KALDI_ASSERT(my_stats[i].second != NULL);
193  BaseFloat stats_count = my_stats[i].second->Normalizer();
194  if (oldpdf_to_count.count(ans) == 0) oldpdf_to_count[ans] = stats_count;
195  else oldpdf_to_count[ans] += stats_count;
196  }
197  BaseFloat max_count = 0; int32 max_old_pdf = -1;
198  for (std::map<int32, BaseFloat>::const_iterator iter = oldpdf_to_count.begin();
199  iter != oldpdf_to_count.end();
200  ++iter) {
201  if (iter->second > max_count) {
202  max_count = iter->second;
203  max_old_pdf = iter->first;
204  }
205  }
206  if (max_count == 0) { // no overlap - probably a leaf with no stats at all.
207  KALDI_WARN << "Leaf " << pdf << " of new tree being initialized with "
208  << "globally averaged stats.";
209  am_gmm->AddPdf(avg_gmm);
210  } else {
211  am_gmm->AddPdf(old_am_gmm.GetPdf(max_old_pdf)); // Here is where we copy the relevant old PDF.
212  }
213  }
214 }
void AddPdf(const DiagGmm &gmm)
Adds a GMM to the model, and increments the total number of PDFs.
Definition: am-diag-gmm.cc:57
virtual int32 ContextWidth() const
ContextWidth() returns the value N (e.g.
Definition: context-dep.h:61
const EventMap & ToPdfMap() const
Definition: context-dep.h:98
bool ConvertStats(int32 oldN, int32 oldP, int32 newN, int32 newP, BuildTreeStatsType *stats)
Converts stats from a given context-window (N) and central-position (P) to a different N and P...
Clusterable * SumStats(const BuildTreeStatsType &stats_in)
Sums stats, or returns NULL stats_in has no non-NULL stats.
virtual EventAnswerType MaxResult() const
Definition: event-map.h:142
void SplitStatsByMap(const BuildTreeStatsType &stats, const EventMap &e, std::vector< BuildTreeStatsType > *stats_out)
Splits stats according to the EventMap, indexing them at output by the leaf type. ...
kaldi::int32 int32
virtual bool Map(const EventType &event, EventAnswerType *ans) const =0
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
void Read(std::istream &is, bool binary)
virtual int32 CentralPosition() const
Central position P of the phone context, in 0-based numbering, e.g.
Definition: context-dep.h:62
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
int32 NumPdfs() const
Definition: am-diag-gmm.h:82
DiagGmm & GetPdf(int32 pdf_index)
Accessors.
Definition: am-diag-gmm.h:119
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
void Read(std::istream &is, bool binary)
Read context-dependency object from disk; throws on error.
Definition: context-dep.cc:155
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Definition for Gaussian Mixture Model with diagonal covariances.
Definition: diag-gmm.h:42
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
GaussClusterable wraps Gaussian statistics in a form accessible to generic clustering algorithms...
void Read(std::istream &in_stream, bool binary)
Definition: am-diag-gmm.cc:147

◆ InitCmvnStats()

void InitCmvnStats ( int32  dim,
Matrix< double > *  stats 
)

This function initializes the matrix to dimension 2 by (dim+1); 1st "dim" elements of 1st row are mean stats, 1st "dim" elements of 2nd row are var stats, last element of 1st row is count, last element of 2nd row is zero.

Definition at line 25 of file cmvn.cc.

References KALDI_ASSERT, and Matrix< Real >::Resize().

Referenced by main().

25  {
26  KALDI_ASSERT(dim > 0);
27  stats->Resize(2, dim+1);
28 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ InitFmllr()

void kaldi::InitFmllr ( int32  dim,
Matrix< BaseFloat > *  out_fmllr 
)
inline

Definition at line 161 of file fmllr-diag-gmm.h.

References ComputeFmllrDiagGmm(), Matrix< Real >::Resize(), and MatrixBase< Real >::SetUnit().

162  {
163  out_fmllr->Resize(dim, dim+1);
164  out_fmllr->SetUnit(); // sets diagonal elements to one.
165 }
void SetUnit()
Sets to zero, except ones along diagonal [for non-square matrices too].
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ InitGmmFromRandomFrames()

void kaldi::InitGmmFromRandomFrames ( const Matrix< BaseFloat > &  feats,
DiagGmm gmm 
)

Definition at line 32 of file gmm-global-init-from-feats.cc.

References VectorBase< Real >::AddVec2(), DiagGmm::ComputeGconsts(), DiagGmm::CopyFromNormal(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, VectorBase< Real >::Max(), DiagGmmNormal::means_, MatrixBase< Real >::NumCols(), DiagGmm::NumGauss(), MatrixBase< Real >::NumRows(), RandInt(), MatrixBase< Real >::Row(), DiagGmmNormal::vars_, and DiagGmmNormal::weights_.

Referenced by main().

32  {
33  int32 num_gauss = gmm->NumGauss(), num_frames = feats.NumRows(),
34  dim = feats.NumCols();
35  KALDI_ASSERT(num_frames >= 10 * num_gauss && "Too few frames to train on");
36  Vector<double> mean(dim), var(dim);
37  for (int32 i = 0; i < num_frames; i++) {
38  mean.AddVec(1.0 / num_frames, feats.Row(i));
39  var.AddVec2(1.0 / num_frames, feats.Row(i));
40  }
41  var.AddVec2(-1.0, mean);
42  if (var.Max() <= 0.0)
43  KALDI_ERR << "Features do not have positive variance " << var;
44 
45  DiagGmmNormal gmm_normal(*gmm);
46 
47  std::set<int32> used_frames;
48  for (int32 g = 0; g < num_gauss; g++) {
49  int32 random_frame = RandInt(0, num_frames - 1);
50  while (used_frames.count(random_frame) != 0)
51  random_frame = RandInt(0, num_frames - 1);
52  used_frames.insert(random_frame);
53  gmm_normal.weights_(g) = 1.0 / num_gauss;
54  gmm_normal.means_.Row(g).CopyFromVec(feats.Row(random_frame));
55  gmm_normal.vars_.Row(g).CopyFromVec(var);
56  }
57  gmm->CopyFromNormal(gmm_normal);
58  gmm->ComputeGconsts();
59 }
Definition for Gaussian Mixture Model with diagonal covariances in normal mode: where the parameters ...
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
int32 ComputeGconsts()
Sets the gconsts.
Definition: diag-gmm.cc:114
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
#define KALDI_ERR
Definition: kaldi-error.h:147
int32 NumGauss() const
Returns the number of mixture components in the GMM.
Definition: diag-gmm.h:72
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void CopyFromNormal(const DiagGmmNormal &diag_gmm_normal)
Copies from DiagGmmNormal; does not resize.
Definition: diag-gmm.cc:918
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ InitKaldiInputStream()

bool InitKaldiInputStream ( std::istream &  is,
bool binary 
)
inline

Initialize an opened stream for reading by detecting the binary header and.

InitKaldiInputStream initializes an opened stream for reading by detecting the binary header and setting the "binary" value appropriately; It will typically not be called by users directly.

Definition at line 306 of file io-funcs-inl.h.

Referenced by main(), Input::OpenInternal(), PosteriorHolder::Read(), KaldiObjectHolder< KaldiType >::Read(), GaussPostHolder::Read(), BasicHolder< BasicType >::Read(), BasicVectorHolder< BasicType >::Read(), BasicVectorVectorHolder< BasicType >::Read(), BasicPairVectorHolder< BasicType >::Read(), ReadBasicType(), UnitTestCompressedMatrix(), UnitTestGeneralMatrix(), UnitTestIo(), and UnitTestIoCross().

306  {
307  // Sets the 'binary' variable.
308  // Throws exception in the very unusual situation that stream
309  // starts with '\0' but not then 'B'.
310 
311  if (is.peek() == '\0') { // seems to be binary
312  is.get();
313  if (is.peek() != 'B') {
314  return false;
315  }
316  is.get();
317  *binary = true;
318  return true;
319  } else {
320  *binary = false;
321  return true;
322  }
323 }

◆ InitKaldiOutputStream()

void InitKaldiOutputStream ( std::ostream &  os,
bool  binary 
)
inline

InitKaldiOutputStream initializes an opened stream for writing by writing an optional binary header and modifying the floating-point precision; it will typically not be called by users directly.

Definition at line 291 of file io-funcs-inl.h.

Referenced by Output::Open(), ReadBasicType(), UnitTestCompressedMatrix(), UnitTestGeneralMatrix(), UnitTestIo(), UnitTestIoCross(), KaldiObjectHolder< KaldiType >::Write(), PosteriorHolder::Write(), GaussPostHolder::Write(), BasicHolder< BasicType >::Write(), BasicVectorHolder< BasicType >::Write(), BasicVectorVectorHolder< BasicType >::Write(), and BasicPairVectorHolder< BasicType >::Write().

291  {
292  // This does not throw exceptions (does not check for errors).
293  if (binary) {
294  os.put('\0');
295  os.put('B');
296  }
297  // Note, in non-binary mode we may at some point want to mess with
298  // the precision a bit.
299  // 7 is a bit more than the precision of float..
300  if (os.precision() < 7)
301  os.precision(7);
302 }

◆ InitRand() [1/4]

static void kaldi::InitRand ( SpMatrix< Real > *  M)
static

Definition at line 42 of file cu-test.cc.

References SpMatrix< Real >::Cond(), rnnlm::i, rnnlm::j, PackedMatrix< Real >::NumRows(), and RandGauss().

42  {
43  do {
44  for (MatrixIndexT i = 0; i < M->NumRows(); i++) {
45  for (MatrixIndexT j = 0; j <= i; j++ ) {
46  (*M)(i,j) = RandGauss();
47  }
48  }
49  } while (M->NumRows() != 0 && M->Cond() > 100);
50 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
Real Cond() const
Returns maximum ratio of singular values.
Definition: sp-matrix.h:145

◆ InitRand() [2/4]

◆ InitRand() [3/4]

static void kaldi::InitRand ( MatrixBase< Real > *  M)
static

Definition at line 53 of file cu-matrix-test.cc.

References MatrixBase< Real >::Cond(), rnnlm::i, rnnlm::j, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and RandGauss().

53  {
54  do {
55  for (MatrixIndexT i = 0;i < M->NumRows();i++)
56  for (MatrixIndexT j = 0;j < M->NumCols();j++)
57  (*M)(i, j) = RandGauss();
58  } while (M->NumRows() != 0 && M->Cond() > 100);
59 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
Real Cond() const
Returns condition number by computing Svd.
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ InitRand() [4/4]

static void kaldi::InitRand ( VectorBase< Real > *  v)
static

Definition at line 53 of file cu-test.cc.

References VectorBase< Real >::Dim(), rnnlm::i, and RandGauss().

53  {
54  for (MatrixIndexT i = 0; i < v->Dim(); i++) {
55  (*v)(i) = RandGauss();
56  }
57 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64

◆ InitRandNonsingular() [1/2]

static void kaldi::InitRandNonsingular ( MatrixBase< Real > *  M)
static

Definition at line 56 of file matrix-lib-test.cc.

References MatrixBase< Real >::Cond(), rnnlm::i, rnnlm::j, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and RandGauss().

Referenced by CholeskyUnitTestTr(), UnitTestAxpy(), UnitTestDeterminant(), UnitTestDeterminantSign(), UnitTestEig(), UnitTestEigSp(), UnitTestFloorChol(), UnitTestInverse(), UnitTestNonsymmetricPower(), UnitTestRow(), UnitTestSimpleForMat(), UnitTestTridiagonalize(), and UnitTestTridiagonalizeAndQr().

56  {
57 start:
58  for (MatrixIndexT i = 0;i < M->NumRows();i++)
59  for (MatrixIndexT j = 0;j < M->NumCols();j++)
60  (*M)(i, j) = RandGauss();
61  if (M->NumRows() != 0 && M->Cond() > 100) {
62  printf("Condition number of random matrix large %f, trying again (this is normal)\n",
63  (float) M->Cond());
64  goto start;
65  }
66 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
Real Cond() const
Returns condition number by computing Svd.
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ InitRandNonsingular() [2/2]

static void kaldi::InitRandNonsingular ( SpMatrix< Real > *  M)
static

Definition at line 69 of file matrix-lib-test.cc.

References SpMatrix< Real >::Cond(), rnnlm::i, rnnlm::j, PackedMatrix< Real >::NumRows(), and RandGauss().

69  {
70 start:
71  for (MatrixIndexT i = 0;i < M->NumRows();i++)
72  for (MatrixIndexT j = 0;j<=i;j++)
73  (*M)(i, j) = RandGauss();
74  if (M->NumRows() != 0 && M->Cond() > 100)
75  goto start;
76 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98
Real Cond() const
Returns maximum ratio of singular values.
Definition: sp-matrix.h:145

◆ InitRandomGmm()

void InitRandomGmm ( DiagGmm gmm_in)

Definition at line 27 of file diag-gmm-test.cc.

References DiagGmm::ComputeGconsts(), Exp(), rnnlm::i, rnnlm::j, DiagGmm::Perturb(), Rand(), RandGauss(), RandUniform(), DiagGmm::Resize(), VectorBase< Real >::Scale(), DiagGmm::SetInvVarsAndMeans(), DiagGmm::SetWeights(), and VectorBase< Real >::Sum().

Referenced by UnitTestDiagGmmGenerate(), UnitTestFmllrDiagGmm(), UnitTestFmllrDiagGmmDiagonal(), UnitTestFmllrDiagGmmOffset(), and UnitTestFmllrRaw().

27  {
28  int32 num_gauss = 10 + Rand() % 5;
29  int32 dim = 10 + Rand() % 10;
30  DiagGmm &gmm(*gmm_in);
31  gmm.Resize(num_gauss, dim);
32  Matrix<BaseFloat> inv_vars(num_gauss, dim),
33  means(num_gauss, dim);
34  Vector<BaseFloat> weights(num_gauss);
35  for (int32 i = 0; i < num_gauss; i++) {
36  for (int32 j = 0; j < dim; j++) {
37  inv_vars(i, j) = Exp(RandGauss() * (1.0 / (1 + j)));
38  means(i, j) = RandGauss() * (1.0 / (1 + j));
39  }
40  weights(i) = Exp(RandGauss());
41  }
42  weights.Scale(1.0 / weights.Sum());
43  gmm.SetWeights(weights);
44  gmm.SetInvVarsAndMeans(inv_vars, means);
45  gmm.Perturb(0.5 * RandUniform());
46  gmm.ComputeGconsts(); // this is unnecessary; computed in Perturb
47 }
double Exp(double x)
Definition: kaldi-math.h:83
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ IsLeafNode()

static bool kaldi::IsLeafNode ( const EventMap e)
static

Definition at line 354 of file event-map.cc.

References EventMap::GetChildren().

Referenced by GetTreeStructure(), and GetTreeStructureInternal().

354  {
355  std::vector<EventMap*> children;
356  e->GetChildren(&children);
357  return children.empty();
358 }

◆ IsLine()

bool IsLine ( const std::string &  line)

Returns true if "line" is free of
characters and unprintable characters, and does not contain leading or trailing whitespace.

Definition at line 154 of file text-utils.cc.

Referenced by ConvertStringToInteger(), and TestIsLine().

154  {
155  if (line.find('\n') != std::string::npos) return false;
156  if (line.empty()) return true;
157  if (isspace(*(line.begin()))) return false;
158  if (isspace(*(line.rbegin()))) return false;
159  std::string::const_iterator iter = line.begin(), end = line.end();
160  for (; iter != end; iter++)
161  if (!isprint(*iter)) return false;
162  return true;
163 }

◆ IsmoothStatsAmDiagGmm()

void IsmoothStatsAmDiagGmm ( const AccumAmDiagGmm src_stats,
double  tau,
AccumAmDiagGmm dst_stats 
)

Smooth "dst_stats" with "src_stats".

They don't have to be different.

Definition at line 358 of file ebw-diag-gmm.cc.

References AccumAmDiagGmm::GetAcc(), IsmoothStatsDiagGmm(), KALDI_ASSERT, and AccumAmDiagGmm::NumAccs().

Referenced by main(), and EbwWeightOptions::Register().

360  {
361  int num_pdfs = src_stats.NumAccs();
362  KALDI_ASSERT(num_pdfs == dst_stats->NumAccs());
363  for (int32 pdf = 0; pdf < num_pdfs; pdf++)
364  IsmoothStatsDiagGmm(src_stats.GetAcc(pdf), tau, &(dst_stats->GetAcc(pdf)));
365 }
kaldi::int32 int32
void IsmoothStatsDiagGmm(const AccumDiagGmm &src_stats, double tau, AccumDiagGmm *dst_stats)
I-Smooth the stats. src_stats and dst_stats do not have to be different.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ IsmoothStatsAmDiagGmmFromModel()

void IsmoothStatsAmDiagGmmFromModel ( const AmDiagGmm src_model,
double  tau,
AccumAmDiagGmm dst_stats 
)

This version of the I-smoothing function takes a model as input.

Definition at line 367 of file ebw-diag-gmm.cc.

References DiagGmmToStats(), AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), IsmoothStatsDiagGmm(), KALDI_ASSERT, kGmmAll, AccumAmDiagGmm::NumAccs(), and AmDiagGmm::NumPdfs().

Referenced by main(), and EbwWeightOptions::Register().

369  {
370  int num_pdfs = src_model.NumPdfs();
371  KALDI_ASSERT(num_pdfs == dst_stats->NumAccs());
372  for (int32 pdf = 0; pdf < num_pdfs; pdf++) {
373  AccumDiagGmm tmp_stats;
374  double occ = 1.0; // its value doesn't matter.
375  DiagGmmToStats(src_model.GetPdf(pdf), kGmmAll, occ, &tmp_stats);
376  IsmoothStatsDiagGmm(tmp_stats, tau, &(dst_stats->GetAcc(pdf)));
377  }
378 }
kaldi::int32 int32
void IsmoothStatsDiagGmm(const AccumDiagGmm &src_stats, double tau, AccumDiagGmm *dst_stats)
I-Smooth the stats. src_stats and dst_stats do not have to be different.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void DiagGmmToStats(const DiagGmm &gmm, GmmFlagsType flags, double state_occ, AccumDiagGmm *dst_stats)
Creates stats from the GMM. Resizes them as needed.

◆ IsmoothStatsDiagGmm()

void IsmoothStatsDiagGmm ( const AccumDiagGmm src_stats,
double  tau,
AccumDiagGmm dst_stats 
)

I-Smooth the stats. src_stats and dst_stats do not have to be different.

Definition at line 318 of file ebw-diag-gmm.cc.

References AccumDiagGmm::AddStatsForComponent(), VectorBase< Real >::CopyFromVec(), AccumDiagGmm::Dim(), AccumDiagGmm::Flags(), KALDI_ASSERT, kGmmMeans, kGmmVariances, AccumDiagGmm::mean_accumulator(), AccumDiagGmm::NumGauss(), AccumDiagGmm::occupancy(), VectorBase< Real >::Scale(), and AccumDiagGmm::variance_accumulator().

Referenced by IsmoothStatsAmDiagGmm(), IsmoothStatsAmDiagGmmFromModel(), EbwWeightOptions::Register(), and UnitTestEstimateMmieDiagGmm().

320  {
321  KALDI_ASSERT(src_stats.NumGauss() == dst_stats->NumGauss());
322  int32 dim = src_stats.Dim(), num_gauss = src_stats.NumGauss();
323  for (int32 g = 0; g < num_gauss; g++) {
324  double occ = src_stats.occupancy()(g);
325  if (occ != 0.0) { // can only do this for nonzero occupancies...
326  Vector<double> x_stats(dim), x2_stats(dim);
327  if (dst_stats->Flags() & kGmmMeans)
328  x_stats.CopyFromVec(src_stats.mean_accumulator().Row(g));
329  if (dst_stats->Flags() & kGmmVariances)
330  x2_stats.CopyFromVec(src_stats.variance_accumulator().Row(g));
331  x_stats.Scale(tau / occ);
332  x2_stats.Scale(tau / occ);
333  dst_stats->AddStatsForComponent(g, tau, x_stats, x2_stats);
334  }
335  }
336 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ IsPlausibleWord() [1/2]

static bool kaldi::IsPlausibleWord ( const WordBoundaryInfo info,
const TransitionModel tmodel,
const std::vector< int32 > &  transition_ids 
)
static

Definition at line 543 of file word-align-lattice.cc.

References rnnlm::i, TransitionModel::IsFinal(), TransitionModel::IsSelfLoop(), WordBoundaryInfo::kWordBeginAndEndPhone, WordBoundaryInfo::kWordBeginPhone, WordBoundaryInfo::kWordEndPhone, WordBoundaryInfo::reorder, TransitionModel::TransitionIdToPhone(), and WordBoundaryInfo::TypeOfPhone().

545  {
546  if (transition_ids.empty()) return false;
547  int32 first_phone = tmodel.TransitionIdToPhone(transition_ids.front()),
548  last_phone = tmodel.TransitionIdToPhone(transition_ids.back());
549  if ( (info.TypeOfPhone(first_phone) == WordBoundaryInfo::kWordBeginAndEndPhone
550  && first_phone == last_phone)
551  ||
552  (info.TypeOfPhone(first_phone) == WordBoundaryInfo::kWordBeginPhone &&
553  info.TypeOfPhone(last_phone) == WordBoundaryInfo::kWordEndPhone) ) {
554  if (! info.reorder) {
555  return (tmodel.IsFinal(transition_ids.back()));
556  } else {
557  int32 i = transition_ids.size() - 1;
558  while (i > 0 && tmodel.IsSelfLoop(transition_ids[i])) i--;
559  return tmodel.IsFinal(transition_ids[i]);
560  }
561  } else return false;
562 }
kaldi::int32 int32

◆ IsPlausibleWord() [2/2]

static bool kaldi::IsPlausibleWord ( const WordAlignLatticeLexiconInfo lexicon_info,
const TransitionModel tmodel,
int32  word_id,
const std::vector< int32 > &  transition_ids 
)
static

Definition at line 745 of file word-align-lattice-lexicon.cc.

References rnnlm::i, WordAlignLatticeLexiconInfo::IsValidEntry(), KALDI_ASSERT, KALDI_WARN, SplitToPhones(), and TransitionModel::TransitionIdToPhone().

Referenced by LatticeWordAligner::ComputationState::OutputArcForce(), and TestWordAlignedLattice().

748  {
749 
750  std::vector<std::vector<int32> > split_alignment; // Split into phones.
751  if (!SplitToPhones(tmodel, transition_ids, &split_alignment)) {
752  KALDI_WARN << "Could not split word into phones correctly (forced-out?)";
753  }
754  std::vector<int32> phones(split_alignment.size());
755  for (size_t i = 0; i < split_alignment.size(); i++) {
756  KALDI_ASSERT(!split_alignment[i].empty());
757  phones[i] = tmodel.TransitionIdToPhone(split_alignment[i][0]);
758  }
759  std::vector<int32> lexicon_entry;
760  lexicon_entry.push_back(word_id);
761  lexicon_entry.insert(lexicon_entry.end(), phones.begin(), phones.end());
762 
763  if (!lexicon_info.IsValidEntry(lexicon_entry)) {
764  std::ostringstream ostr;
765  for (size_t i = 0; i < lexicon_entry.size(); i++)
766  ostr << lexicon_entry[i] << ' ';
767  KALDI_WARN << "Invalid arc in aligned lattice (code error?) lexicon-entry is " << ostr.str();
768  return false;
769  } else {
770  return true;
771  }
772 }
bool SplitToPhones(const TransitionModel &trans_model, const std::vector< int32 > &alignment, std::vector< std::vector< int32 > > *split_alignment)
SplitToPhones splits up the TransitionIds in "alignment" into their individual phones (one vector per...
Definition: hmm-utils.cc:723
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ IsReordered()

static bool kaldi::IsReordered ( const TransitionModel trans_model,
const std::vector< int32 > &  alignment 
)
static

Definition at line 625 of file hmm-utils.cc.

References rnnlm::i, TransitionModel::IsSelfLoop(), KALDI_ASSERT, and TransitionModel::TransitionIdToTransitionState().

Referenced by ConvertAlignmentInternal(), and SplitToPhones().

626  {
627  for (size_t i = 0; i + 1 < alignment.size(); i++) {
628  int32 tstate1 = trans_model.TransitionIdToTransitionState(alignment[i]),
629  tstate2 = trans_model.TransitionIdToTransitionState(alignment[i+1]);
630  if (tstate1 != tstate2) {
631  bool is_loop_1 = trans_model.IsSelfLoop(alignment[i]),
632  is_loop_2 = trans_model.IsSelfLoop(alignment[i+1]);
633  KALDI_ASSERT(!(is_loop_1 && is_loop_2)); // Invalid.
634  if (is_loop_1) return true; // Reordered. self-loop is last.
635  if (is_loop_2) return false; // Not reordered. self-loop is first.
636  }
637  }
638 
639  // Just one trans-state in whole sequence.
640  if (alignment.empty()) return false;
641  else {
642  bool is_loop_front = trans_model.IsSelfLoop(alignment.front()),
643  is_loop_back = trans_model.IsSelfLoop(alignment.back());
644  if (is_loop_front) return false; // Not reordered. Self-loop is first.
645  if (is_loop_back) return true; // Reordered. Self-loop is last.
646  return false; // We really don't know in this case but calling code should
647  // not care.
648  }
649 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ IsSorted()

bool kaldi::IsSorted ( const std::vector< T > &  vec)
inline

Returns true if the vector is sorted.

Definition at line 47 of file stl-utils.h.

Referenced by QuestionsForKey::Check(), DiscriminativeSupervisionSplitter::LatticeInfo::Check(), fst::CheckPhones(), PldaStats::Sort(), SplitEventMap::SplitEventMap(), TestIsSorted(), TestMergePairVectorSumming(), and Uniq().

47  {
48  typename std::vector<T>::const_iterator iter = vec.begin(), end = vec.end();
49  if (iter == end) return true;
50  while (1) {
51  typename std::vector<T>::const_iterator next_iter = iter;
52  ++next_iter;
53  if (next_iter == end) return true; // end of loop and nothing out of order
54  if (*next_iter < *iter) return false;
55  iter = next_iter;
56  }
57 }

◆ IsSortedAndUniq()

bool kaldi::IsSortedAndUniq ( const std::vector< T > &  vec)
inline

Returns true if the vector is sorted and contains each element only once.

Definition at line 63 of file stl-utils.h.

Referenced by AccumulateTreeStatsInfo::AccumulateTreeStatsInfo(), AddTransitionProbs(), AutomaticallyObtainQuestions(), RegressionTree::BuildTree(), BuildTree(), BuildTreeTwoLevel(), ConvolutionModel::Check(), ComputationGraphBuilder::Check(), Compiler::CompileBackwardFromSubmatLocations(), ExampleMergingConfig::ComputeDerived(), kaldi::nnet3::ComputeMatrixAccesses(), kaldi::nnet3::ComputeVariableAccesses(), ComputationRenumberer::CreateRenumbering(), FeatureTransformEstimateMulti::Estimate(), FilterStatsByKey(), ComputationLoopedOptimizer::FindActiveMatrices(), GenRandContextDependency(), GenRandContextDependencyLarge(), GenRandTopology(), GetDefaultTopology(), GetFullBiphoneStubMap(), ContextDependency::GetPdfInfo(), GetPdfsForPhones(), GetPhonesForPdfs(), kaldi::nnet3::time_height_convolution::GetRandomConvolutionIndexes(), GetStubMap(), SpliceComponent::Init(), TimeHeightConvolutionComponent::InitFromConfig(), KMeansClusterPhones(), LatticeActivePhones(), LatticeBoost(), main(), kaldi::nnet3::time_height_convolution::MakeComputation(), ObtainSetsOfPhones(), HmmTopology::Read(), ReadRootsFile(), ReadSharedPhonesList(), kaldi::nnet3::time_height_convolution::RegularizeTList(), DiagGmm::RemoveComponents(), FullGmm::RemoveComponents(), TestIsSortedAndUniq(), TrailingSilenceLength(), and TrainingGraphCompiler::TrainingGraphCompiler().

63  {
64  typename std::vector<T>::const_iterator iter = vec.begin(), end = vec.end();
65  if (iter == end) return true;
66  while (1) {
67  typename std::vector<T>::const_iterator next_iter = iter;
68  ++next_iter;
69  if (next_iter == end) return true; // end of loop and nothing out of order
70  if (*next_iter <= *iter) return false;
71  iter = next_iter;
72  }
73 }

◆ IsToken()

bool IsToken ( const std::string &  token)

Returns true if "token" is nonempty, and all characters are printable and whitespace-free.

Definition at line 105 of file text-utils.cc.

References rnnlm::i.

Referenced by ConvertStringToInteger(), RandomAccessTableReader< kaldi::TokenHolder >::HasKey(), RandomAccessTableReaderScriptImpl< Holder >::HasKeyInternal(), IsNotToken(), Nnet::ProcessComponentConfigLine(), SplitArgOnEquals(), TestIsToken(), TokenHolder::Write(), TokenVectorHolder::Write(), TableWriterArchiveImpl< Holder >::Write(), TableWriterScriptImpl< Holder >::Write(), TableWriterBothImpl< Holder >::Write(), and WriteScriptFile().

105  {
106  size_t l = token.length();
107  if (l == 0) return false;
108  for (size_t i = 0; i < l; i++) {
109  unsigned char c = token[i];
110  if ((!isprint(c) || isspace(c)) && (isascii(c) || c == (unsigned char)255))
111  return false;
112  // The "&& (isascii(c) || c == 255)" was added so that we won't reject
113  // non-ASCII characters such as French characters with accents [except for
114  // 255 which is "nbsp", a form of space].
115  }
116  return true;
117 }

◆ IsValidName()

bool IsValidName ( const std::string &  name)

Returns true if 'name' would be a valid name for a component or node in a nnet3Nnet.

This is a nonempty string beginning with A-Za-z_, and containing only '-', '_', '.', A-Z, a-z, or 0-9.

Definition at line 553 of file text-utils.cc.

References rnnlm::i.

Referenced by Nnet::AddComponent(), kaldi::nnet3::DescriptorTokenize(), ConfigLine::ParseLine(), Nnet::RemoveRedundantConfigLines(), and Nnet::SetNodeName().

553  {
554  if (name.size() == 0) return false;
555  for (size_t i = 0; i < name.size(); i++) {
556  if (i == 0 && !isalpha(name[i]) && name[i] != '_')
557  return false;
558  if (!isalnum(name[i]) && name[i] != '_' && name[i] != '-' && name[i] != '.')
559  return false;
560  }
561  return true;
562 }

◆ JoinVectorToString()

void JoinVectorToString ( const std::vector< std::string > &  vec_in,
const char *  delim,
bool  omit_empty_strings,
std::string *  str_out 
)

Joins the elements of a vector of strings into a single string using "delim" as the delimiter.

If omit_empty_strings == true, any empty strings in the vector are skipped. A vector of empty strings results in an empty string on the output.

Definition at line 77 of file text-utils.cc.

References rnnlm::i.

Referenced by TestSplitStringToVector().

79  {
80  std::string tmp_str;
81  for (size_t i = 0; i < vec_in.size(); i++) {
82  if (!omit_empty_strings || !vec_in[i].empty()) {
83  tmp_str.append(vec_in[i]);
84  if (i < vec_in.size() - 1)
85  if (!omit_empty_strings || !vec_in[i+1].empty())
86  tmp_str.append(delim);
87  }
88  }
89  str_out->swap(tmp_str);
90 }

◆ KaldiGetStackTrace()

static std::string kaldi::KaldiGetStackTrace ( )
static

Definition at line 133 of file kaldi-error.cc.

References rnnlm::i.

Referenced by MessageLogger::LogMessage().

133  {
134  std::string ans;
135 #ifdef HAVE_EXECINFO_H
136  const size_t KALDI_MAX_TRACE_SIZE = 50;
137  const size_t KALDI_MAX_TRACE_PRINT = 50; // Must be even.
138  // Buffer for the trace.
139  void *trace[KALDI_MAX_TRACE_SIZE];
140  // Get the trace.
141  size_t size = backtrace(trace, KALDI_MAX_TRACE_SIZE);
142  // Get the trace symbols.
143  char **trace_symbol = backtrace_symbols(trace, size);
144  if (trace_symbol == NULL)
145  return ans;
146 
147  // Compose a human-readable backtrace string.
148  ans += "[ Stack-Trace: ]\n";
149  if (size <= KALDI_MAX_TRACE_PRINT) {
150  for (size_t i = 0; i < size; i++) {
151  ans += Demangle(trace_symbol[i]) + "\n";
152  }
153  } else { // Print out first+last (e.g.) 5.
154  for (size_t i = 0; i < KALDI_MAX_TRACE_PRINT / 2; i++) {
155  ans += Demangle(trace_symbol[i]) + "\n";
156  }
157  ans += ".\n.\n.\n";
158  for (size_t i = size - KALDI_MAX_TRACE_PRINT / 2; i < size; i++) {
159  ans += Demangle(trace_symbol[i]) + "\n";
160  }
161  if (size == KALDI_MAX_TRACE_SIZE)
162  ans += ".\n.\n.\n"; // Stack was too long, probably a bug.
163  }
164 
165  // We must free the array of pointers allocated by backtrace_symbols(),
166  // but not the strings themselves.
167  free(trace_symbol);
168 #endif // HAVE_EXECINFO_H
169  return ans;
170 }

◆ LatticeAcousticRescore()

void kaldi::LatticeAcousticRescore ( const TransitionModel trans_model,
const Matrix< BaseFloat > &  log_likes,
const std::vector< int32 > &  state_times,
Lattice lat 
)

Definition at line 31 of file lattice-rescore-mapped.cc.

References rnnlm::i, KALDI_ASSERT, KALDI_ERR, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and TransitionModel::TransitionIdToPdf().

Referenced by main().

34  {
35  kaldi::uint64 props = lat->Properties(fst::kFstProperties, false);
36  if (!(props & fst::kTopSorted))
37  KALDI_ERR << "Input lattice must be topologically sorted.";
38 
39  KALDI_ASSERT(!state_times.empty());
40  std::vector<std::vector<int32> > time_to_state(log_likes.NumRows());
41  for (size_t i = 0; i < state_times.size(); i++) {
42  KALDI_ASSERT(state_times[i] >= 0);
43  if (state_times[i] < log_likes.NumRows()) // end state may be past this..
44  time_to_state[state_times[i]].push_back(i);
45  else
46  KALDI_ASSERT(state_times[i] == log_likes.NumRows()
47  && "There appears to be lattice/feature mismatch.");
48  }
49 
50  for (int32 t = 0; t < log_likes.NumRows(); t++) {
51  for (size_t i = 0; i < time_to_state[t].size(); i++) {
52  int32 state = time_to_state[t][i];
53  for (fst::MutableArcIterator<Lattice> aiter(lat, state); !aiter.Done();
54  aiter.Next()) {
55  LatticeArc arc = aiter.Value();
56  int32 trans_id = arc.ilabel;
57  if (trans_id != 0) { // Non-epsilon input label on arc
58  int32 pdf_id = trans_model.TransitionIdToPdf(trans_id);
59  if (pdf_id > log_likes.NumCols())
60  KALDI_ERR << "Pdf-id " << pdf_id << " is out of the range of "
61  << "input log-likelihoods " << log_likes.NumCols()
62  << " (probably some kind of mismatch).";
63  BaseFloat ll = log_likes(t, pdf_id);
64  arc.weight.SetValue2(-ll + arc.weight.Value2());
65  aiter.SetValue(arc);
66  }
67  }
68  }
69  }
70 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
int32 TransitionIdToPdf(int32 trans_id) const
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ LatticeActivePhones() [1/2]

void kaldi::LatticeActivePhones ( const Lattice lat,
const TransitionModel trans,
const std::vector< int32 > &  sil_phones,
std::vector< std::set< int32 > > *  active_phones 
)

Given a lattice, and a transition model to map pdf-ids to phones, outputs for each frame the set of phones active on that frame.

If sil_phones (which must be sorted and uniq) is nonempty, it excludes phones in this list.

Definition at line 399 of file lattice-functions.cc.

References IsSortedAndUniq(), KALDI_ASSERT, LatticeStateTimes(), and TransitionModel::TransitionIdToPhone().

401  {
402  KALDI_ASSERT(IsSortedAndUniq(silence_phones));
403  vector<int32> state_times;
404  int32 num_states = lat.NumStates();
405  int32 max_time = LatticeStateTimes(lat, &state_times);
406  active_phones->clear();
407  active_phones->resize(max_time);
408  for (int32 state = 0; state < num_states; state++) {
409  int32 cur_time = state_times[state];
410  for (fst::ArcIterator<Lattice> aiter(lat, state); !aiter.Done();
411  aiter.Next()) {
412  const LatticeArc &arc = aiter.Value();
413  if (arc.ilabel != 0) { // Non-epsilon arc
414  int32 phone = trans.TransitionIdToPhone(arc.ilabel);
415  if (!std::binary_search(silence_phones.begin(),
416  silence_phones.end(), phone))
417  (*active_phones)[cur_time].insert(phone);
418  }
419  } // end looping over arcs
420  } // end looping over states
421 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ LatticeActivePhones() [2/2]

void kaldi::LatticeActivePhones ( const Lattice lat,
const TransitionModel trans,
const std::vector< int32 > &  sil_phones,
std::vector< std::set< int32 > > *  active_phones 
)

Given a lattice, and a transition model to map pdf-ids to phones, outputs for each frame the set of phones active on that frame.

If sil_phones (which must be sorted and uniq) is nonempty, it excludes phones in this list.

Definition at line 399 of file lattice-functions.cc.

References IsSortedAndUniq(), KALDI_ASSERT, LatticeStateTimes(), and TransitionModel::TransitionIdToPhone().

401  {
402  KALDI_ASSERT(IsSortedAndUniq(silence_phones));
403  vector<int32> state_times;
404  int32 num_states = lat.NumStates();
405  int32 max_time = LatticeStateTimes(lat, &state_times);
406  active_phones->clear();
407  active_phones->resize(max_time);
408  for (int32 state = 0; state < num_states; state++) {
409  int32 cur_time = state_times[state];
410  for (fst::ArcIterator<Lattice> aiter(lat, state); !aiter.Done();
411  aiter.Next()) {
412  const LatticeArc &arc = aiter.Value();
413  if (arc.ilabel != 0) { // Non-epsilon arc
414  int32 phone = trans.TransitionIdToPhone(arc.ilabel);
415  if (!std::binary_search(silence_phones.begin(),
416  silence_phones.end(), phone))
417  (*active_phones)[cur_time].insert(phone);
418  }
419  } // end looping over arcs
420  } // end looping over states
421 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ LatticeBoost()

bool LatticeBoost ( const TransitionModel trans,
const std::vector< int32 > &  alignment,
const std::vector< int32 > &  silence_phones,
BaseFloat  b,
BaseFloat  max_silence_error,
Lattice lat 
)

Boosts LM probabilities by b * [number of frame errors]; equivalently, adds -b*[number of frame errors] to the graph-component of the cost of each arc/path.

There is a frame error if a particular transition-id on a particular frame corresponds to a phone not matching transcription's alignment for that frame. This is used in "margin-inspired" discriminative training, esp. Boosted MMI. The TransitionModel is used to map transition-ids in the lattice input-side to phones; the phones appearing in "silence_phones" are treated specially in that we replace the frame error f (either zero or 1) for a frame, with the minimum of f or max_silence_error. For the normal recipe, max_silence_error would be zero. Returns true on success, false if there was some kind of mismatch. At input, silence_phones must be sorted and unique.

Definition at line 735 of file lattice-functions.cc.

References IsSortedAndUniq(), KALDI_ASSERT, KALDI_WARN, LatticeStateTimes(), TransitionModel::NumTransitionIds(), TopSortLatticeIfNeeded(), and TransitionModel::TransitionIdToPhone().

Referenced by DiscriminativeComputation::Compute(), NnetDiscriminativeUpdater::LatticeComputations(), and main().

740  {
742 
743  // get all stored properties (test==false means don't test if not known).
744  uint64 props = lat->Properties(fst::kFstProperties,
745  false);
746 
747  KALDI_ASSERT(IsSortedAndUniq(silence_phones));
748  KALDI_ASSERT(max_silence_error >= 0.0 && max_silence_error <= 1.0);
749  vector<int32> state_times;
750  int32 num_states = lat->NumStates();
751  int32 num_frames = LatticeStateTimes(*lat, &state_times);
752  KALDI_ASSERT(num_frames == static_cast<int32>(alignment.size()));
753  for (int32 state = 0; state < num_states; state++) {
754  int32 cur_time = state_times[state];
755  for (fst::MutableArcIterator<Lattice> aiter(lat, state); !aiter.Done();
756  aiter.Next()) {
757  LatticeArc arc = aiter.Value();
758  if (arc.ilabel != 0) { // Non-epsilon arc
759  if (arc.ilabel < 0 || arc.ilabel > trans.NumTransitionIds()) {
760  KALDI_WARN << "Lattice has out-of-range transition-ids: "
761  << "lattice/model mismatch?";
762  return false;
763  }
764  int32 phone = trans.TransitionIdToPhone(arc.ilabel),
765  ref_phone = trans.TransitionIdToPhone(alignment[cur_time]);
766  BaseFloat frame_error;
767  if (phone == ref_phone) {
768  frame_error = 0.0;
769  } else { // an error...
770  if (std::binary_search(silence_phones.begin(), silence_phones.end(), phone))
771  frame_error = max_silence_error;
772  else
773  frame_error = 1.0;
774  }
775  BaseFloat delta_cost = -b * frame_error; // negative cost if
776  // frame is wrong, to boost likelihood of arcs with errors on them.
777  // Add this cost to the graph part.
778  arc.weight.SetValue1(arc.weight.Value1() + delta_cost);
779  aiter.SetValue(arc);
780  }
781  }
782  }
783  // All we changed is the weights, so any properties that were
784  // known before, are still known, except for whether or not the
785  // lattice was weighted.
786  lat->SetProperties(props,
787  ~(fst::kWeighted|fst::kUnweighted));
788 
789  return true;
790 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
void TopSortLatticeIfNeeded(Lattice *lat)
Topologically sort the lattice if not already topologically sorted.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ LatticeForwardBackward()

BaseFloat LatticeForwardBackward ( const Lattice lat,
Posterior arc_post,
double *  acoustic_like_sum = NULL 
)

This function does the forward-backward over lattices and computes the posterior probabilities of the arcs.

It returns the total log-probability of the lattice. The Posterior quantities contain pairs of (transition-id, weight) on each frame. If the pointer "acoustic_like_sum" is provided, this value is set to the sum over the arcs, of the posterior of the arc times the acoustic likelihood [i.e. negated acoustic score] on that link. This is used in combination with other quantities to work out the objective function in MMI discriminative training.

Definition at line 314 of file lattice-functions.cc.

References ApproxEqual(), fst::ConvertToCost(), Exp(), KALDI_ASSERT, KALDI_ERR, KALDI_WARN, kLogZeroDouble, LatticeStateTimes(), LogAdd(), and MergePairVectorSumming().

Referenced by SingleUtteranceGmmDecoder::GetGaussianPosteriors(), LatticeForwardBackwardMmi(), main(), and TestWordAlignedLattice().

315  {
316  // Note, Posterior is defined as follows: Indexed [frame], then a list
317  // of (transition-id, posterior-probability) pairs.
318  // typedef std::vector<std::vector<std::pair<int32, BaseFloat> > > Posterior;
319  using namespace fst;
320  typedef Lattice::Arc Arc;
321  typedef Arc::Weight Weight;
322  typedef Arc::StateId StateId;
323 
324  if (acoustic_like_sum) *acoustic_like_sum = 0.0;
325 
326  // Make sure the lattice is topologically sorted.
327  if (lat.Properties(fst::kTopSorted, true) == 0)
328  KALDI_ERR << "Input lattice must be topologically sorted.";
329  KALDI_ASSERT(lat.Start() == 0);
330 
331  int32 num_states = lat.NumStates();
332  vector<int32> state_times;
333  int32 max_time = LatticeStateTimes(lat, &state_times);
334  std::vector<double> alpha(num_states, kLogZeroDouble);
335  std::vector<double> &beta(alpha); // we re-use the same memory for
336  // this, but it's semantically distinct so we name it differently.
337  double tot_forward_prob = kLogZeroDouble;
338 
339  post->clear();
340  post->resize(max_time);
341 
342  alpha[0] = 0.0;
343  // Propagate alphas forward.
344  for (StateId s = 0; s < num_states; s++) {
345  double this_alpha = alpha[s];
346  for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
347  const Arc &arc = aiter.Value();
348  double arc_like = -ConvertToCost(arc.weight);
349  alpha[arc.nextstate] = LogAdd(alpha[arc.nextstate], this_alpha + arc_like);
350  }
351  Weight f = lat.Final(s);
352  if (f != Weight::Zero()) {
353  double final_like = this_alpha - (f.Value1() + f.Value2());
354  tot_forward_prob = LogAdd(tot_forward_prob, final_like);
355  KALDI_ASSERT(state_times[s] == max_time &&
356  "Lattice is inconsistent (final-prob not at max_time)");
357  }
358  }
359  for (StateId s = num_states-1; s >= 0; s--) {
360  Weight f = lat.Final(s);
361  double this_beta = -(f.Value1() + f.Value2());
362  for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
363  const Arc &arc = aiter.Value();
364  double arc_like = -ConvertToCost(arc.weight),
365  arc_beta = beta[arc.nextstate] + arc_like;
366  this_beta = LogAdd(this_beta, arc_beta);
367  int32 transition_id = arc.ilabel;
368 
369  // The following "if" is an optimization to avoid un-needed exp().
370  if (transition_id != 0 || acoustic_like_sum != NULL) {
371  double posterior = Exp(alpha[s] + arc_beta - tot_forward_prob);
372 
373  if (transition_id != 0) // Arc has a transition-id on it [not epsilon]
374  (*post)[state_times[s]].push_back(std::make_pair(transition_id,
375  static_cast<kaldi::BaseFloat>(posterior)));
376  if (acoustic_like_sum != NULL)
377  *acoustic_like_sum -= posterior * arc.weight.Value2();
378  }
379  }
380  if (acoustic_like_sum != NULL && f != Weight::Zero()) {
381  double final_logprob = - ConvertToCost(f),
382  posterior = Exp(alpha[s] + final_logprob - tot_forward_prob);
383  *acoustic_like_sum -= posterior * f.Value2();
384  }
385  beta[s] = this_beta;
386  }
387  double tot_backward_prob = beta[0];
388  if (!ApproxEqual(tot_forward_prob, tot_backward_prob, 1e-8)) {
389  KALDI_WARN << "Total forward probability over lattice = " << tot_forward_prob
390  << ", while total backward probability = " << tot_backward_prob;
391  }
392  // Now combine any posteriors with the same transition-id.
393  for (int32 t = 0; t < max_time; t++)
394  MergePairVectorSumming(&((*post)[t]));
395  return tot_backward_prob;
396 }
fst::StdArc::StateId StateId
double Exp(double x)
Definition: kaldi-math.h:83
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
bool ApproxEqual(const LatticeWeightTpl< FloatType > &w1, const LatticeWeightTpl< FloatType > &w2, float delta=kDelta)
double ConvertToCost(const LatticeWeightTpl< Float > &w)
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
double LogAdd(double x, double y)
Definition: kaldi-math.h:184
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void MergePairVectorSumming(std::vector< std::pair< I, F > > *vec)
For a vector of pair<I, F> where I is an integer and F a floating-point or integer type...
Definition: stl-utils.h:288
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ LatticeForwardBackwardMmi()

BaseFloat LatticeForwardBackwardMmi ( const TransitionModel trans,
const Lattice lat,
const std::vector< int32 > &  num_ali,
bool  drop_frames,
bool  convert_to_pdf_ids,
bool  cancel,
Posterior arc_post 
)

This function can be used to compute posteriors for MMI, with a positive contribution for the numerator and a negative one for the denominator.

This function is not actually used in our normal MMI training recipes, where it's instead done using various command line programs that each do a part of the job. This function was written for use in neural-net MMI training.

Parameters
[in]transThe transition model. Used to map the transition-ids to phones or pdfs.
[in]latThe denominator lattice
[in]num_aliThe numerator alignment
[in]drop_framesIf "drop_frames" is true, it will not compute any posteriors on frames where the num and den have disjoint pdf-ids.
[in]convert_to_pdf_idsIf "convert_to_pdfs_ids" is true, it will convert the output to be at the level of pdf-ids, not transition-ids.
[in]cancelIf "cancel" is true, it will cancel out any positive and negative parts from the same transition-id (or pdf-id, if convert_to_pdf_ids == true).
[out]arc_postThe output MMI posteriors of transition-ids (or pdf-ids if convert_to_pdf_ids == true) at each frame i.e. the difference between the numerator and denominator posteriors.

It returns the forward-backward likelihood of the lattice.

Definition at line 1414 of file lattice-functions.cc.

References AlignmentToPosterior(), ConvertPosteriorToPdfs(), LatticeForwardBackward(), MergePosteriors(), and ScalePosterior().

Referenced by DiscriminativeComputation::ComputeObjfAndDeriv(), kaldi::nnet2::ExampleToPdfPost(), and NnetDiscriminativeUpdater::GetDiscriminativePosteriors().

1421  {
1422  // First compute the MMI posteriors.
1423 
1424  Posterior den_post;
1426  &den_post,
1427  NULL);
1428 
1429  Posterior num_post;
1430  AlignmentToPosterior(num_ali, &num_post);
1431 
1432  // Now negate the MMI posteriors and add the numerator
1433  // posteriors.
1434  ScalePosterior(-1.0, &den_post);
1435 
1436  if (convert_to_pdf_ids) {
1437  Posterior num_tmp;
1438  ConvertPosteriorToPdfs(tmodel, num_post, &num_tmp);
1439  num_tmp.swap(num_post);
1440  Posterior den_tmp;
1441  ConvertPosteriorToPdfs(tmodel, den_post, &den_tmp);
1442  den_tmp.swap(den_post);
1443  }
1444 
1445  MergePosteriors(num_post, den_post,
1446  cancel, drop_frames, post);
1447 
1448  return ans;
1449 }
float BaseFloat
Definition: kaldi-types.h:29
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
BaseFloat LatticeForwardBackward(const Lattice &lat, Posterior *post, double *acoustic_like_sum)
This function does the forward-backward over lattices and computes the posterior probabilities of the...
void AlignmentToPosterior(const std::vector< int32 > &ali, Posterior *post)
Convert an alignment to a posterior (with a scale of 1.0 on each entry).
Definition: posterior.cc:290
void ScalePosterior(BaseFloat scale, Posterior *post)
Scales the BaseFloat (weight) element in the posterior entries.
Definition: posterior.cc:218
void ConvertPosteriorToPdfs(const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
Converts a posterior over transition-ids to be a posterior over pdf-ids.
Definition: posterior.cc:322
int32 MergePosteriors(const Posterior &post1, const Posterior &post2, bool merge, bool drop_frames, Posterior *post)
Merge two sets of posteriors, which must have the same length.
Definition: posterior.cc:258

◆ LatticeForwardBackwardMpeVariants()

BaseFloat LatticeForwardBackwardMpeVariants ( const TransitionModel trans,
const std::vector< int32 > &  silence_phones,
const Lattice lat,
const std::vector< int32 > &  num_ali,
std::string  criterion,
bool  one_silence_class,
Posterior post 
)

This function implements either the MPFE (minimum phone frame error) or SMBR (state-level minimum bayes risk) forward-backward, depending on whether "criterion" is "mpfe" or "smbr".

It returns the MPFE criterion of SMBR criterion for this utterance, and outputs the posteriors (which may be positive or negative) into "post".

Parameters
[in]transThe transition model. Used to map the transition-ids to phones or pdfs.
[in]silence_phonesA list of integer ids of silence phones. The silence frames i.e. the frames where num_ali corresponds to a silence phones are treated specially. The behavior is determined by 'one_silence_class' being false (traditional behavior) or true. Usually in our setup, several phones including the silence, vocalized noise, non-spoken noise and unk are treated as "silence phones"
[in]latThe denominator lattice
[in]num_aliThe numerator alignment
[in]criterionThe objective function. Must be "mpfe" or "smbr" for MPFE (minimum phone frame error) or sMBR (state minimum bayes risk) training.
[in]one_silence_classDetermines how the silence frames are treated. Setting this to false gives the old traditional behavior, where the silence frames (according to num_ali) are treated as incorrect. However, this means that the insertions are not penalized by the objective. Setting this to true gives the new behaviour, where we treat silence as any other phone, except that all pdfs of silence phones are collapsed into a single class for the frame-error computation. This can possible reduce the insertions in the trained model. This is closer to the WER metric that we actually care about, since WER is generally computed after filtering out noises, but does penalize insertions.
[out]postThe "MBR posteriors" i.e. derivatives w.r.t to the pseudo log-likelihoods of states at each frame.

Definition at line 794 of file lattice-functions.cc.

References ApproxEqual(), fst::ConvertToCost(), Exp(), KALDI_ASSERT, KALDI_ERR, KALDI_ISNAN, kLogZeroDouble, LatticeStateTimes(), LogAdd(), MergePairVectorSumming(), TransitionModel::TransitionIdToPdf(), and TransitionModel::TransitionIdToPhone().

Referenced by DiscriminativeComputation::ComputeObjfAndDeriv(), kaldi::nnet2::ExampleToPdfPost(), NnetDiscriminativeUpdater::GetDiscriminativePosteriors(), and main().

801  {
802  using namespace fst;
803  typedef Lattice::Arc Arc;
804  typedef Arc::Weight Weight;
805  typedef Arc::StateId StateId;
806 
807  KALDI_ASSERT(criterion == "mpfe" || criterion == "smbr");
808  bool is_mpfe = (criterion == "mpfe");
809 
810  if (lat.Properties(fst::kTopSorted, true) == 0)
811  KALDI_ERR << "Input lattice must be topologically sorted.";
812  KALDI_ASSERT(lat.Start() == 0);
813 
814  int32 num_states = lat.NumStates();
815  vector<int32> state_times;
816  int32 max_time = LatticeStateTimes(lat, &state_times);
817  KALDI_ASSERT(max_time == static_cast<int32>(num_ali.size()));
818  std::vector<double> alpha(num_states, kLogZeroDouble),
819  alpha_smbr(num_states, 0), //forward variable for sMBR
820  beta(num_states, kLogZeroDouble),
821  beta_smbr(num_states, 0); //backward variable for sMBR
822 
823  double tot_forward_prob = kLogZeroDouble;
824  double tot_forward_score = 0;
825 
826  post->clear();
827  post->resize(max_time);
828 
829  alpha[0] = 0.0;
830  // First Pass Forward,
831  for (StateId s = 0; s < num_states; s++) {
832  double this_alpha = alpha[s];
833  for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
834  const Arc &arc = aiter.Value();
835  double arc_like = -ConvertToCost(arc.weight);
836  alpha[arc.nextstate] = LogAdd(alpha[arc.nextstate], this_alpha + arc_like);
837  }
838  Weight f = lat.Final(s);
839  if (f != Weight::Zero()) {
840  double final_like = this_alpha - (f.Value1() + f.Value2());
841  tot_forward_prob = LogAdd(tot_forward_prob, final_like);
842  KALDI_ASSERT(state_times[s] == max_time &&
843  "Lattice is inconsistent (final-prob not at max_time)");
844  }
845  }
846  // First Pass Backward,
847  for (StateId s = num_states-1; s >= 0; s--) {
848  Weight f = lat.Final(s);
849  double this_beta = -(f.Value1() + f.Value2());
850  for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
851  const Arc &arc = aiter.Value();
852  double arc_like = -ConvertToCost(arc.weight),
853  arc_beta = beta[arc.nextstate] + arc_like;
854  this_beta = LogAdd(this_beta, arc_beta);
855  }
856  beta[s] = this_beta;
857  }
858  // First Pass Forward-Backward Check
859  double tot_backward_prob = beta[0];
860  // may loose the condition somehow here 1e-6 (was 1e-8)
861  if (!ApproxEqual(tot_forward_prob, tot_backward_prob, 1e-6)) {
862  KALDI_ERR << "Total forward probability over lattice = " << tot_forward_prob
863  << ", while total backward probability = " << tot_backward_prob;
864  }
865 
866  alpha_smbr[0] = 0.0;
867  // Second Pass Forward, calculate forward for MPFE/SMBR
868  for (StateId s = 0; s < num_states; s++) {
869  double this_alpha = alpha[s];
870  for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
871  const Arc &arc = aiter.Value();
872  double arc_like = -ConvertToCost(arc.weight);
873  double frame_acc = 0.0;
874  if (arc.ilabel != 0) {
875  int32 cur_time = state_times[s];
876  int32 phone = trans.TransitionIdToPhone(arc.ilabel),
877  ref_phone = trans.TransitionIdToPhone(num_ali[cur_time]);
878  bool phone_is_sil = std::binary_search(silence_phones.begin(),
879  silence_phones.end(),
880  phone),
881  ref_phone_is_sil = std::binary_search(silence_phones.begin(),
882  silence_phones.end(),
883  ref_phone),
884  both_sil = phone_is_sil && ref_phone_is_sil;
885  if (!is_mpfe) { // smbr.
886  int32 pdf = trans.TransitionIdToPdf(arc.ilabel),
887  ref_pdf = trans.TransitionIdToPdf(num_ali[cur_time]);
888  if (!one_silence_class) // old behavior
889  frame_acc = (pdf == ref_pdf && !phone_is_sil) ? 1.0 : 0.0;
890  else
891  frame_acc = (pdf == ref_pdf || both_sil) ? 1.0 : 0.0;
892  } else {
893  if (!one_silence_class) // old behavior
894  frame_acc = (phone == ref_phone && !phone_is_sil) ? 1.0 : 0.0;
895  else
896  frame_acc = (phone == ref_phone || both_sil) ? 1.0 : 0.0;
897  }
898  }
899  double arc_scale = Exp(alpha[s] + arc_like - alpha[arc.nextstate]);
900  alpha_smbr[arc.nextstate] += arc_scale * (alpha_smbr[s] + frame_acc);
901  }
902  Weight f = lat.Final(s);
903  if (f != Weight::Zero()) {
904  double final_like = this_alpha - (f.Value1() + f.Value2());
905  double arc_scale = Exp(final_like - tot_forward_prob);
906  tot_forward_score += arc_scale * alpha_smbr[s];
907  KALDI_ASSERT(state_times[s] == max_time &&
908  "Lattice is inconsistent (final-prob not at max_time)");
909  }
910  }
911  // Second Pass Backward, collect Mpe style posteriors
912  for (StateId s = num_states-1; s >= 0; s--) {
913  for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
914  const Arc &arc = aiter.Value();
915  double arc_like = -ConvertToCost(arc.weight),
916  arc_beta = beta[arc.nextstate] + arc_like;
917  double frame_acc = 0.0;
918  int32 transition_id = arc.ilabel;
919  if (arc.ilabel != 0) {
920  int32 cur_time = state_times[s];
921  int32 phone = trans.TransitionIdToPhone(arc.ilabel),
922  ref_phone = trans.TransitionIdToPhone(num_ali[cur_time]);
923  bool phone_is_sil = std::binary_search(silence_phones.begin(),
924  silence_phones.end(), phone),
925  ref_phone_is_sil = std::binary_search(silence_phones.begin(),
926  silence_phones.end(),
927  ref_phone),
928  both_sil = phone_is_sil && ref_phone_is_sil;
929  if (!is_mpfe) { // smbr.
930  int32 pdf = trans.TransitionIdToPdf(arc.ilabel),
931  ref_pdf = trans.TransitionIdToPdf(num_ali[cur_time]);
932  if (!one_silence_class) // old behavior
933  frame_acc = (pdf == ref_pdf && !phone_is_sil) ? 1.0 : 0.0;
934  else
935  frame_acc = (pdf == ref_pdf || both_sil) ? 1.0 : 0.0;
936  } else {
937  if (!one_silence_class) // old behavior
938  frame_acc = (phone == ref_phone && !phone_is_sil) ? 1.0 : 0.0;
939  else
940  frame_acc = (phone == ref_phone || both_sil) ? 1.0 : 0.0;
941  }
942  }
943  double arc_scale = Exp(beta[arc.nextstate] + arc_like - beta[s]);
944  // check arc_scale NAN,
945  // this is to prevent partial paths in Lattices
946  // i.e., paths don't survive to the final state
947  if (KALDI_ISNAN(arc_scale)) arc_scale = 0;
948  beta_smbr[s] += arc_scale * (beta_smbr[arc.nextstate] + frame_acc);
949 
950  if (transition_id != 0) { // Arc has a transition-id on it [not epsilon]
951  double posterior = Exp(alpha[s] + arc_beta - tot_forward_prob);
952  double acc_diff = alpha_smbr[s] + frame_acc + beta_smbr[arc.nextstate]
953  - tot_forward_score;
954  double posterior_smbr = posterior * acc_diff;
955  (*post)[state_times[s]].push_back(std::make_pair(transition_id,
956  static_cast<BaseFloat>(posterior_smbr)));
957  }
958  }
959  }
960 
961  //Second Pass Forward Backward check
962  double tot_backward_score = beta_smbr[0]; // Initial state id == 0
963  // may loose the condition somehow here 1e-5/1e-4
964  if (!ApproxEqual(tot_forward_score, tot_backward_score, 1e-4)) {
965  KALDI_ERR << "Total forward score over lattice = " << tot_forward_score
966  << ", while total backward score = " << tot_backward_score;
967  }
968 
969  // Output the computed posteriors
970  for (int32 t = 0; t < max_time; t++)
971  MergePairVectorSumming(&((*post)[t]));
972  return tot_forward_score;
973 }
fst::StdArc::StateId StateId
double Exp(double x)
Definition: kaldi-math.h:83
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
kaldi::int32 int32
bool ApproxEqual(const LatticeWeightTpl< FloatType > &w1, const LatticeWeightTpl< FloatType > &w2, float delta=kDelta)
double ConvertToCost(const LatticeWeightTpl< Float > &w)
#define KALDI_ERR
Definition: kaldi-error.h:147
fst::StdArc::Weight Weight
double LogAdd(double x, double y)
Definition: kaldi-math.h:184
#define KALDI_ISNAN
Definition: kaldi-math.h:72
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void MergePairVectorSumming(std::vector< std::pair< I, F > > *vec)
For a vector of pair<I, F> where I is an integer and F a floating-point or integer type...
Definition: stl-utils.h:288
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ LatticeStateTimes() [1/2]

int32 kaldi::LatticeStateTimes ( const Lattice lat,
std::vector< int32 > *  times 
)

This function iterates over the states of a topologically sorted lattice and counts the time instance corresponding to each state.

The times are returned in a vector of integers 'times' which is resized to have a size equal to the number of states in the lattice. The function also returns the maximum time in the lattice (this will equal the number of frames in the file).

Definition at line 78 of file lattice-functions.cc.

References KALDI_ASSERT, and KALDI_ERR.

Referenced by DiscriminativeSupervision::Check(), DiscriminativeExampleSplitter::CollapseTransitionIds(), ComputeAcousticScoresMap(), DiscriminativeExampleSplitter::ComputeFrameInfo(), DiscriminativeSupervisionSplitter::ComputeLatticeScores(), DiscriminativeSupervisionSplitter::CreateRangeLattice(), GetLatticeTimeSpan(), LatticeActivePhones(), LatticeBoost(), NnetDiscriminativeUpdater::LatticeComputations(), LatticeForwardBackward(), LatticeForwardBackwardMpeVariants(), DiscriminativeComputation::LookupNnetOutput(), main(), DiscriminativeSupervisionSplitter::PrepareLattice(), ReplaceAcousticScoresFromMap(), and RescoreLattice().

78  {
79  if (!lat.Properties(fst::kTopSorted, true))
80  KALDI_ERR << "Input lattice must be topologically sorted.";
81  KALDI_ASSERT(lat.Start() == 0);
82  int32 num_states = lat.NumStates();
83  times->clear();
84  times->resize(num_states, -1);
85  (*times)[0] = 0;
86  for (int32 state = 0; state < num_states; state++) {
87  int32 cur_time = (*times)[state];
88  for (fst::ArcIterator<Lattice> aiter(lat, state); !aiter.Done();
89  aiter.Next()) {
90  const LatticeArc &arc = aiter.Value();
91 
92  if (arc.ilabel != 0) { // Non-epsilon input label on arc
93  // next time instance
94  if ((*times)[arc.nextstate] == -1) {
95  (*times)[arc.nextstate] = cur_time + 1;
96  } else {
97  KALDI_ASSERT((*times)[arc.nextstate] == cur_time + 1);
98  }
99  } else { // epsilon input label on arc
100  // Same time instance
101  if ((*times)[arc.nextstate] == -1)
102  (*times)[arc.nextstate] = cur_time;
103  else
104  KALDI_ASSERT((*times)[arc.nextstate] == cur_time);
105  }
106  }
107  }
108  return (*std::max_element(times->begin(), times->end()));
109 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ LatticeStateTimes() [2/2]

int32 kaldi::LatticeStateTimes ( const Lattice lat,
std::vector< int32 > *  times 
)

This function iterates over the states of a topologically sorted lattice and counts the time instance corresponding to each state.

The times are returned in a vector of integers 'times' which is resized to have a size equal to the number of states in the lattice. The function also returns the maximum time in the lattice (this will equal the number of frames in the file).

Definition at line 78 of file lattice-functions.cc.

References KALDI_ASSERT, and KALDI_ERR.

Referenced by DiscriminativeSupervision::Check(), DiscriminativeExampleSplitter::CollapseTransitionIds(), ComputeAcousticScoresMap(), DiscriminativeExampleSplitter::ComputeFrameInfo(), DiscriminativeSupervisionSplitter::ComputeLatticeScores(), DiscriminativeSupervisionSplitter::CreateRangeLattice(), GetLatticeTimeSpan(), LatticeActivePhones(), LatticeBoost(), NnetDiscriminativeUpdater::LatticeComputations(), LatticeForwardBackward(), LatticeForwardBackwardMpeVariants(), DiscriminativeComputation::LookupNnetOutput(), main(), DiscriminativeSupervisionSplitter::PrepareLattice(), ReplaceAcousticScoresFromMap(), and RescoreLattice().

78  {
79  if (!lat.Properties(fst::kTopSorted, true))
80  KALDI_ERR << "Input lattice must be topologically sorted.";
81  KALDI_ASSERT(lat.Start() == 0);
82  int32 num_states = lat.NumStates();
83  times->clear();
84  times->resize(num_states, -1);
85  (*times)[0] = 0;
86  for (int32 state = 0; state < num_states; state++) {
87  int32 cur_time = (*times)[state];
88  for (fst::ArcIterator<Lattice> aiter(lat, state); !aiter.Done();
89  aiter.Next()) {
90  const LatticeArc &arc = aiter.Value();
91 
92  if (arc.ilabel != 0) { // Non-epsilon input label on arc
93  // next time instance
94  if ((*times)[arc.nextstate] == -1) {
95  (*times)[arc.nextstate] = cur_time + 1;
96  } else {
97  KALDI_ASSERT((*times)[arc.nextstate] == cur_time + 1);
98  }
99  } else { // epsilon input label on arc
100  // Same time instance
101  if ((*times)[arc.nextstate] == -1)
102  (*times)[arc.nextstate] = cur_time;
103  else
104  KALDI_ASSERT((*times)[arc.nextstate] == cur_time);
105  }
106  }
107  }
108  return (*std::max_element(times->begin(), times->end()));
109 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ LatticeToString() [1/2]

std::string kaldi::LatticeToString ( const Lattice lat,
const fst::SymbolTable &  word_syms 
)

Definition at line 70 of file online2-tcp-nnet3-decode-faster.cc.

References fst::GetLinearSymbolSequence(), rnnlm::i, KALDI_WARN, and words.

Referenced by LatticeToString(), and main().

70  {
71  LatticeWeight weight;
72  std::vector<int32> alignment;
73  std::vector<int32> words;
74  GetLinearSymbolSequence(lat, &alignment, &words, &weight);
75 
76  std::ostringstream msg;
77  for (size_t i = 0; i < words.size(); i++) {
78  std::string s = word_syms.Find(words[i]);
79  if (s.empty()) {
80  KALDI_WARN << "Word-id " << words[i] << " not in symbol table.";
81  msg << "<#" << std::to_string(i) << "> ";
82  } else
83  msg << s << " ";
84  }
85  return msg.str();
86 }
int32 words[kMaxOrder]
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ LatticeToString() [2/2]

std::string kaldi::LatticeToString ( const CompactLattice clat,
const fst::SymbolTable &  word_syms 
)

Definition at line 102 of file online2-tcp-nnet3-decode-faster.cc.

References CompactLatticeShortestPath(), fst::ConvertLattice(), KALDI_WARN, and LatticeToString().

102  {
103  if (clat.NumStates() == 0) {
104  KALDI_WARN << "Empty lattice.";
105  return "";
106  }
107  CompactLattice best_path_clat;
108  CompactLatticeShortestPath(clat, &best_path_clat);
109 
110  Lattice best_path_lat;
111  ConvertLattice(best_path_clat, &best_path_lat);
112  return LatticeToString(best_path_lat, word_syms);
113 }
std::string LatticeToString(const CompactLattice &clat, const fst::SymbolTable &word_syms)
void CompactLatticeShortestPath(const CompactLattice &clat, CompactLattice *shortest_path)
A form of the shortest-path/best-path algorithm that&#39;s specially coded for CompactLattice.
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46

◆ Lcm()

I kaldi::Lcm ( m,
n 
)

Returns the least common multiple of two integers.

Will crash unless the inputs are positive.

Definition at line 318 of file kaldi-math.h.

References Gcd(), and KALDI_ASSERT.

Referenced by NnetSimpleComputationOptions::CheckAndFixConfigs(), DecodableNnetSimple::CheckAndFixConfigs(), LinearResample::GetNumOutputSamples(), SwitchingForwardingDescriptor::Modulus(), Nnet::Modulus(), BinarySumDescriptor::Modulus(), Descriptor::Modulus(), and UnitTestGcdLcmTpl().

318  {
319  KALDI_ASSERT(m > 0 && n > 0);
320  I gcd = Gcd(m, n);
321  return gcd * (m/gcd) * (n/gcd);
322 }
I Gcd(I m, I n)
Definition: kaldi-math.h:297
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ LevenshteinAlignment()

int32 LevenshteinAlignment ( const std::vector< T > &  a,
const std::vector< T > &  b,
eps_symbol,
std::vector< std::pair< T, T > > *  output 
)

Definition at line 130 of file edit-distance-inl.h.

References rnnlm::i, KALDI_ASSERT, rnnlm::n, and ReverseVector().

Referenced by main(), and TestLevenshteinAlignment().

133  {
134  // Check inputs:
135  {
136  KALDI_ASSERT(output != NULL);
137  for (size_t i = 0; i < a.size(); i++) KALDI_ASSERT(a[i] != eps_symbol);
138  for (size_t i = 0; i < b.size(); i++) KALDI_ASSERT(b[i] != eps_symbol);
139  }
140  output->clear();
141  // This is very memory-inefficiently implemented using a vector of vectors.
142  size_t M = a.size(), N = b.size();
143  size_t m, n;
144  std::vector<std::vector<int32> > e(M+1);
145  for (m = 0; m <=M; m++) e[m].resize(N+1);
146  for (n = 0; n <= N; n++)
147  e[0][n] = n;
148  for (m = 1; m <= M; m++) {
149  e[m][0] = e[m-1][0] + 1;
150  for (n = 1; n <= N; n++) {
151  int32 sub_or_ok = e[m-1][n-1] + (a[m-1] == b[n-1] ? 0 : 1);
152  int32 del = e[m-1][n] + 1; // assumes a == ref, b == hyp.
153  int32 ins = e[m][n-1] + 1;
154  e[m][n] = std::min(sub_or_ok, std::min(del, ins));
155  }
156  }
157  // get time-reversed output first: trace back.
158  m = M;
159  n = N;
160  while (m != 0 || n != 0) {
161  size_t last_m, last_n;
162  if (m == 0) {
163  last_m = m;
164  last_n = n-1;
165  } else if (n == 0) {
166  last_m = m-1;
167  last_n = n;
168  } else {
169  int32 sub_or_ok = e[m-1][n-1] + (a[m-1] == b[n-1] ? 0 : 1);
170  int32 del = e[m-1][n] + 1; // assumes a == ref, b == hyp.
171  int32 ins = e[m][n-1] + 1;
172  // choose sub_or_ok if all else equal.
173  if (sub_or_ok <= std::min(del, ins)) {
174  last_m = m-1;
175  last_n = n-1;
176  } else {
177  if (del <= ins) { // choose del over ins if equal.
178  last_m = m-1;
179  last_n = n;
180  } else {
181  last_m = m;
182  last_n = n-1;
183  }
184  }
185  }
186  T a_sym, b_sym;
187  a_sym = (last_m == m ? eps_symbol : a[last_m]);
188  b_sym = (last_n == n ? eps_symbol : b[last_n]);
189  output->push_back(std::make_pair(a_sym, b_sym));
190  m = last_m;
191  n = last_n;
192  }
193  ReverseVector(output);
194  return e[M][N];
195 }
kaldi::int32 int32
struct rnnlm::@11::@12 n
void ReverseVector(std::vector< T > *vec)
Reverses the contents of a vector.
Definition: stl-utils.h:264
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ LevenshteinEditDistance() [1/2]

int32 LevenshteinEditDistance ( const std::vector< T > &  a,
const std::vector< T > &  b 
)

Definition at line 30 of file edit-distance-inl.h.

References rnnlm::i, and rnnlm::n.

Referenced by GetEditsDualHyp(), GetEditsSingleHyp(), main(), TestEditDistance(), TestEditDistance2(), TestEditDistance2String(), TestEditDistanceString(), and TestLevenshteinAlignment().

31  {
32  // Algorithm:
33  // write A and B for the sequences, with elements a_0 ..
34  // let |A| = M and |B| = N be the lengths, and have
35  // elements a_0 ... a_{M-1} and b_0 ... b_{N-1}.
36  // We are computing the recursion
37  // E(m, n) = min( E(m-1, n-1) + (1-delta(a_{m-1}, b_{n-1})),
38  // E(m-1, n) + 1,
39  // E(m, n-1) + 1).
40  // where E(m, n) is defined for m = 0..M and n = 0..N and out-of-
41  // bounds quantities are considered to be infinity (i.e. the
42  // recursion does not visit them).
43 
44  // We do this computation using a vector e of size N+1.
45  // The outer iterations range over m = 0..M.
46 
47  int M = a.size(), N = b.size();
48  std::vector<int32> e(N+1);
49  std::vector<int32> e_tmp(N+1);
50  // initialize e.
51  for (size_t i = 0; i < e.size(); i++)
52  e[i] = i;
53  for (int32 m = 1; m <= M; m++) {
54  // computing E(m, .) from E(m-1, .)
55  // handle special case n = 0:
56  e_tmp[0] = e[0] + 1;
57 
58  for (int32 n = 1; n <= N; n++) {
59  int32 term1 = e[n-1] + (a[m-1] == b[n-1] ? 0 : 1);
60  int32 term2 = e[n] + 1;
61  int32 term3 = e_tmp[n-1] + 1;
62  e_tmp[n] = std::min(term1, std::min(term2, term3));
63  }
64  e = e_tmp;
65  }
66  return e.back();
67 }
kaldi::int32 int32
struct rnnlm::@11::@12 n

◆ LevenshteinEditDistance() [2/2]

int32 LevenshteinEditDistance ( const std::vector< T > &  ref,
const std::vector< T > &  hyp,
int32 ins,
int32 del,
int32 sub 
)

Definition at line 79 of file edit-distance-inl.h.

References rnnlm::i.

81  {
82  // temp sequence to remember error type and stats.
83  std::vector<error_stats> e(ref.size()+1);
84  std::vector<error_stats> cur_e(ref.size()+1);
85  // initialize the first hypothesis aligned to the reference at each
86  // position:[hyp_index =0][ref_index]
87  for (size_t i =0; i < e.size(); i ++) {
88  e[i].ins_num = 0;
89  e[i].sub_num = 0;
90  e[i].del_num = i;
91  e[i].total_cost = i;
92  }
93 
94  // for other alignments
95  for (size_t hyp_index = 1; hyp_index <= hyp.size(); hyp_index ++) {
96  cur_e[0] = e[0];
97  cur_e[0].ins_num++;
98  cur_e[0].total_cost++;
99  for (size_t ref_index = 1; ref_index <= ref.size(); ref_index ++) {
100  int32 ins_err = e[ref_index].total_cost + 1;
101  int32 del_err = cur_e[ref_index-1].total_cost + 1;
102  int32 sub_err = e[ref_index-1].total_cost;
103  if (hyp[hyp_index-1] != ref[ref_index-1])
104  sub_err++;
105 
106  if (sub_err < ins_err && sub_err < del_err) {
107  cur_e[ref_index] =e[ref_index-1];
108  if (hyp[hyp_index-1] != ref[ref_index-1])
109  cur_e[ref_index].sub_num++; // substitution error should be increased
110  cur_e[ref_index].total_cost = sub_err;
111  } else if (del_err < ins_err) {
112  cur_e[ref_index] = cur_e[ref_index-1];
113  cur_e[ref_index].total_cost = del_err;
114  cur_e[ref_index].del_num++; // deletion number is increased.
115  } else {
116  cur_e[ref_index] = e[ref_index];
117  cur_e[ref_index].total_cost = ins_err;
118  cur_e[ref_index].ins_num++; // insertion number is increased.
119  }
120  }
121  e = cur_e; // alternate for the next recursion.
122  }
123  size_t ref_index = e.size()-1;
124  *ins = e[ref_index].ins_num, *del =
125  e[ref_index].del_num, *sub = e[ref_index].sub_num;
126  return e[ref_index].total_cost;
127 }
kaldi::int32 int32

◆ LinearCgd< double >()

template int32 kaldi::LinearCgd< double > ( const LinearCgdOptions opts,
const SpMatrix< double > &  A,
const VectorBase< double > &  b,
VectorBase< double > *  x 
)

Referenced by LinearCgd().

◆ LinearCgd< float >()

template int32 kaldi::LinearCgd< float > ( const LinearCgdOptions opts,
const SpMatrix< float > &  A,
const VectorBase< float > &  b,
VectorBase< float > *  x 
)

Referenced by LinearCgd().

◆ LinearlyInterpolatePitch()

void kaldi::LinearlyInterpolatePitch ( Matrix< BaseFloat > *  mat)

Definition at line 252 of file interpolate-pitch.cc.

References rnnlm::i, and MatrixBase< Real >::NumRows().

Referenced by main().

252  {
253  int32 num_frames = mat->NumRows();
254  int i = 0;
255  Matrix<BaseFloat> &features = *mat;
256  while (i < num_frames) {
257  if(features(i, 1) == 0.0) {
258  int start = i - 1;
259  int end = i;
260  while( (features(end, 1)) == 0.0 && (end < num_frames))
261  end++;
262  BaseFloat end_value = -1, start_value = -1;
263  if (end < num_frames) end_value = features(end, 1);
264  if (start > 0) start_value = features(start, 1);
265 
266  if (start_value < 0 && end_value < 0) {
267  // the whole file is unvoiced -> just put an arbitrary value,
268  // it will all be normalized out anyway.
269  start_value = 1.0;
270  end_value = 1.0;
271  }
272  // If we don't have a value for one end of the range, i.e. at the start or
273  // end, set it to 0.9 times the pitch value that we have at the other end
274  // of the range. The reason we don't set it to that value itself, is that
275  // then over this segment we would have zero time-derivative, so if we
276  // took time derivatives we would have an artificial spike at zero.
277  if (start_value < 0.0) start_value = 0.9 * end_value;
278  if (end_value < 0.0) end_value = 0.9 * start_value;
279 
280  for(int k = start + 1; k < end; k++)
281  features(k, 1) = start_value +
282  (end_value - start_value) / (end - start) * (k - start);
283  i = end;
284  }
285  i++;
286  }
287 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ Log() [1/2]

double kaldi::Log ( double  x)
inline

Definition at line 100 of file kaldi-math.h.

Referenced by VectorBase< float >::ApplyLog(), VectorBase< float >::ApplyLogAndCopy(), VectorBase< float >::ApplyLogSoftMax(), VectorBase< float >::ApplySoftMax(), MatrixBase< float >::ApplySoftMax(), CompactLatticeNormalize(), CuMatrix< float >::CompObjfAndDeriv(), AmSgmm2::ComponentPosteriors(), SpectrogramComputer::Compute(), MfccComputer::Compute(), FbankComputer::Compute(), PlpComputer::Compute(), PitchFrameInfo::ComputeBacktraces(), TransitionModel::ComputeDerivedOfProbs(), FullGmm::ComputeGconsts(), ComputeGconsts(), DiagGmm::ComputeGconsts(), NnetComputer::ComputeLastLayerDeriv(), ComputeLpc(), MleAmSgmm2Updater::ComputeMPrior(), AmSgmm2::ComputeNormalizersInternal(), DiscriminativeComputation::ConvertAnswersToLogLike(), CuVectorUnitTestApplyLog(), CuMatrixBase< float >::DiffXent(), DoRescalingUpdate(), EBWUpdateGaussian(), FbankComputer::FbankComputer(), FmllrInnerUpdate(), GetHmmAsFsa(), GetHmmAsFsaSimple(), GetLogLikeTest(), LogisticRegression::GetObjfAndGrad(), OnlineProcessPitch::GetRawLogPitchFeature(), Rbm::InitData(), TransitionModel::InitializeProbs(), SpMatrix< float >::Invert(), MatrixBase< float >::Invert(), KaldiAssertFailure_(), kaldi::nnet2::KlDivergence(), kaldi::nnet3::KlDivergence(), NnetDiscriminativeUpdater::LatticeComputations(), MatrixBase< float >::Log(), Log1p(), AmSgmm2::LogLikelihood(), SpMatrix< float >::LogPosDefDet(), LogSub(), VectorBase< float >::LogSumExp(), MatrixBase< float >::LogSumExp(), main(), TransitionModel::MapUpdate(), TransitionModel::MapUpdateShared(), DiagGmm::Merge(), DiagGmm::merged_components_logdet(), MfccComputer::MfccComputer(), SoftmaxComponent::MixUp(), TransitionModel::MleUpdate(), TransitionModel::MleUpdateShared(), PushSpecialClass::ModifyFst(), PitchInterpolator::MultiplyObsProb(), OnlinePaSource::OnlinePaSource(), PlpComputer::PlpComputer(), ProcessPovFeatures(), ProcessWindow(), LogSoftmaxComponent::Propagate(), RandGauss(), SpectrogramComputer::SpectrogramComputer(), VectorBase< float >::SumLog(), TakeLogOfPitch(), PushSpecialClass::TestAccuracy(), UnitTestCuDiffXent(), UnitTestDeterminantSign(), UnitTestDiagGmm(), UnitTestEig(), UnitTestFullGmm(), UnitTestLogAddSub(), UnitTestLogSpeed(), UnitTestTrain(), MlltAccs::Update(), OnlineProcessPitch::UpdateNormalizationStats(), MleAmSgmm2Updater::UpdateSubstateWeights(), and VectorToPosteriorEntry().

100 { return log(x); }

◆ Log() [2/2]

float kaldi::Log ( float  x)
inline

Definition at line 101 of file kaldi-math.h.

101 { return logf(x); }

◆ Log1p() [1/2]

double kaldi::Log1p ( double  x)
inline

Definition at line 104 of file kaldi-math.h.

Referenced by Log1p(), LogAdd(), MatrixBase< float >::SoftHinge(), and UnitTestSoftHinge().

104 { return log1p(x); }

◆ Log1p() [2/2]

float kaldi::Log1p ( float  x)
inline

Definition at line 105 of file kaldi-math.h.

References Log(), and Log1p().

105 { return log1pf(x); }

◆ LogAdd() [1/2]

double kaldi::LogAdd ( double  x,
double  y 
)
inline

Definition at line 184 of file kaldi-math.h.

References Exp(), and Log1p().

Referenced by ComputeCompactLatticeAlphas(), ComputeCompactLatticeBetas(), MinimumBayesRisk::EditDistance(), FullGmm::GaussianSelection(), DiagGmm::GaussianSelection(), FullGmm::GaussianSelectionPreselect(), DiagGmm::GaussianSelectionPreselect(), GetLogLikeTest(), LogisticRegression::GetLogPosteriors(), fst::InputDeterminizeSingleState(), GrammarFstPreparer::InsertEpsilonsForState(), LatticeForwardBackward(), LatticeForwardBackwardMpeVariants(), LogAddOrMax(), and UnitTestLogAddSub().

184  {
185  double diff;
186 
187  if (x < y) {
188  diff = x - y;
189  x = y;
190  } else {
191  diff = y - x;
192  }
193  // diff is negative. x is now the larger one.
194 
195  if (diff >= kMinLogDiffDouble) {
196  double res;
197  res = x + Log1p(Exp(diff));
198  return res;
199  } else {
200  return x; // return the larger one.
201  }
202 }
float Log1p(float x)
Definition: kaldi-math.h:105
float Exp(float x)
Definition: kaldi-math.h:85
static const double kMinLogDiffDouble
Definition: kaldi-math.h:124

◆ LogAdd() [2/2]

float kaldi::LogAdd ( float  x,
float  y 
)
inline

Definition at line 206 of file kaldi-math.h.

References Exp(), and Log1p().

206  {
207  float diff;
208 
209  if (x < y) {
210  diff = x - y;
211  x = y;
212  } else {
213  diff = y - x;
214  }
215  // diff is negative. x is now the larger one.
216 
217  if (diff >= kMinLogDiffFloat) {
218  float res;
219  res = x + Log1p(Exp(diff));
220  return res;
221  } else {
222  return x; // return the larger one.
223  }
224 }
float Log1p(float x)
Definition: kaldi-math.h:105
float Exp(float x)
Definition: kaldi-math.h:85
static const float kMinLogDiffFloat
Definition: kaldi-math.h:125

◆ LogAddOrMax()

static double kaldi::LogAddOrMax ( bool  viterbi,
double  a,
double  b 
)
inlinestatic

Definition at line 444 of file lattice-functions.cc.

References LogAdd().

Referenced by ComputeLatticeAlphasAndBetas().

444  {
445  if (viterbi)
446  return std::max(a, b);
447  else
448  return LogAdd(a, b);
449 }
double LogAdd(double x, double y)
Definition: kaldi-math.h:184

◆ LogSub() [1/2]

double kaldi::LogSub ( double  x,
double  y 
)
inline

Definition at line 228 of file kaldi-math.h.

References Exp(), KALDI_ERR, KALDI_ISNAN, kLogZeroDouble, and Log().

Referenced by UnitTestLogAddSub().

228  {
229  if (y >= x) { // Throws exception if y>=x.
230  if (y == x)
231  return kLogZeroDouble;
232  else
233  KALDI_ERR << "Cannot subtract a larger from a smaller number.";
234  }
235 
236  double diff = y - x; // Will be negative.
237  double res = x + Log(1.0 - Exp(diff));
238 
239  // res might be NAN if diff ~0.0, and 1.0-exp(diff) == 0 to machine precision
240  if (KALDI_ISNAN(res))
241  return kLogZeroDouble;
242  return res;
243 }
float Exp(float x)
Definition: kaldi-math.h:85
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ISNAN
Definition: kaldi-math.h:72
float Log(float x)
Definition: kaldi-math.h:101
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ LogSub() [2/2]

float kaldi::LogSub ( float  x,
float  y 
)
inline

Definition at line 247 of file kaldi-math.h.

References Exp(), KALDI_ERR, KALDI_ISNAN, kLogZeroDouble, kLogZeroFloat, and Log().

247  {
248  if (y >= x) { // Throws exception if y>=x.
249  if (y == x)
250  return kLogZeroDouble;
251  else
252  KALDI_ERR << "Cannot subtract a larger from a smaller number.";
253  }
254 
255  float diff = y - x; // Will be negative.
256  float res = x + Log(1.0f - Exp(diff));
257 
258  // res might be NAN if diff ~0.0, and 1.0-exp(diff) == 0 to machine precision
259  if (KALDI_ISNAN(res))
260  return kLogZeroFloat;
261  return res;
262 }
float Exp(float x)
Definition: kaldi-math.h:85
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ISNAN
Definition: kaldi-math.h:72
const float kLogZeroFloat
Definition: kaldi-math.h:128
float Log(float x)
Definition: kaldi-math.h:101
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ LongestSentenceLength() [1/2]

int32 LongestSentenceLength ( const Lattice lat)

This function returns the number of words in the longest sentence in a CompactLattice (i.e.

the the maximum of any path, of the count of olabels on that path).

Definition at line 1452 of file lattice-functions.cc.

References KALDI_ASSERT, KALDI_ERR, and LatticeWeightTpl< BaseFloat >::Zero().

Referenced by LongestSentenceLength(), and SentenceLevelConfidence().

1452  {
1453  typedef Lattice::Arc Arc;
1454  typedef Arc::Label Label;
1455  typedef Arc::StateId StateId;
1456 
1457  if (lat.Properties(fst::kTopSorted, true) == 0) {
1458  Lattice lat_copy(lat);
1459  if (!TopSort(&lat_copy))
1460  KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
1461  return LongestSentenceLength(lat_copy);
1462  }
1463  std::vector<int32> max_length(lat.NumStates(), 0);
1464  int32 lattice_max_length = 0;
1465  for (StateId s = 0; s < lat.NumStates(); s++) {
1466  int32 this_max_length = max_length[s];
1467  for (fst::ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
1468  const Arc &arc = aiter.Value();
1469  bool arc_has_word = (arc.olabel != 0);
1470  StateId nextstate = arc.nextstate;
1471  KALDI_ASSERT(static_cast<size_t>(nextstate) < max_length.size());
1472  if (arc_has_word) {
1473  // A lattice should ideally not have cycles anyway; a cycle with a word
1474  // on is something very bad.
1475  KALDI_ASSERT(nextstate > s && "Lattice has cycles with words on.");
1476  max_length[nextstate] = std::max(max_length[nextstate],
1477  this_max_length + 1);
1478  } else {
1479  max_length[nextstate] = std::max(max_length[nextstate],
1480  this_max_length);
1481  }
1482  }
1483  if (lat.Final(s) != LatticeWeight::Zero())
1484  lattice_max_length = std::max(lattice_max_length, max_length[s]);
1485  }
1486  return lattice_max_length;
1487 }
fst::StdArc::StateId StateId
kaldi::int32 int32
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_ERR
Definition: kaldi-error.h:147
int32 LongestSentenceLength(const CompactLattice &clat)
This function returns the number of words in the longest sentence in a CompactLattice, i.e.
fst::StdArc::Label Label
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ LongestSentenceLength() [2/2]

int32 LongestSentenceLength ( const CompactLattice lat)

This function returns the number of words in the longest sentence in a CompactLattice, i.e.

the the maximum of any path, of the count of labels on that path... note, in CompactLattice, the ilabels and olabels are identical because it is an acceptor.

Definition at line 1489 of file lattice-functions.cc.

References KALDI_ASSERT, KALDI_ERR, LongestSentenceLength(), and CompactLatticeWeightTpl< WeightType, IntType >::Zero().

1489  {
1490  typedef CompactLattice::Arc Arc;
1491  typedef Arc::Label Label;
1492  typedef Arc::StateId StateId;
1493 
1494  if (clat.Properties(fst::kTopSorted, true) == 0) {
1495  CompactLattice clat_copy(clat);
1496  if (!TopSort(&clat_copy))
1497  KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
1498  return LongestSentenceLength(clat_copy);
1499  }
1500  std::vector<int32> max_length(clat.NumStates(), 0);
1501  int32 lattice_max_length = 0;
1502  for (StateId s = 0; s < clat.NumStates(); s++) {
1503  int32 this_max_length = max_length[s];
1504  for (fst::ArcIterator<CompactLattice> aiter(clat, s);
1505  !aiter.Done(); aiter.Next()) {
1506  const Arc &arc = aiter.Value();
1507  bool arc_has_word = (arc.ilabel != 0); // note: olabel == ilabel.
1508  // also note: for normal CompactLattice, e.g. as produced by
1509  // determinization, all arcs will have nonzero labels, but the user might
1510  // decide to remplace some of the labels with zero for some reason, and we
1511  // want to support this.
1512  StateId nextstate = arc.nextstate;
1513  KALDI_ASSERT(static_cast<size_t>(nextstate) < max_length.size());
1514  KALDI_ASSERT(nextstate > s && "CompactLattice has cycles");
1515  if (arc_has_word)
1516  max_length[nextstate] = std::max(max_length[nextstate],
1517  this_max_length + 1);
1518  else
1519  max_length[nextstate] = std::max(max_length[nextstate],
1520  this_max_length);
1521  }
1522  if (clat.Final(s) != CompactLatticeWeight::Zero())
1523  lattice_max_length = std::max(lattice_max_length, max_length[s]);
1524  }
1525  return lattice_max_length;
1526 }
fst::StdArc::StateId StateId
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
int32 LongestSentenceLength(const CompactLattice &clat)
This function returns the number of words in the longest sentence in a CompactLattice, i.e.
fst::StdArc::Label Label
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ MachineIsLittleEndian()

int kaldi::MachineIsLittleEndian ( )
inline

Definition at line 83 of file kaldi-utils.h.

References Sleep().

Referenced by SphinxMatrixHolder< kFeatDim >::Read(), ReadHtk(), SphinxMatrixHolder< kFeatDim >::Write(), WriteHtk(), and WriteSphinx().

83  {
84  int check = 1;
85  return (*reinterpret_cast<char*>(&check) != 0);
86 }

◆ MakeEventPair()

std::pair<EventKeyType, EventValueType> kaldi::MakeEventPair ( EventKeyType  k,
EventValueType  v 
)
inline

Definition at line 62 of file event-map.h.

References EventTypeToString(), ReadEventType(), and WriteEventType().

Referenced by ShareEventMapLeaves(), and TestShareEventMapLeaves().

62  {
63  return std::pair<EventKeyType, EventValueType>(k, v);
64 }

◆ MakeLatticeFromLinear()

void kaldi::MakeLatticeFromLinear ( const std::vector< int32 > &  ali,
const std::vector< int32 > &  words,
BaseFloat  lm_cost,
BaseFloat  ac_cost,
Lattice lat_out 
)

Definition at line 27 of file linear-to-nbest.cc.

References rnnlm::i.

Referenced by main().

31  {
33  typedef LatticeArc::Weight Weight;
34  typedef LatticeArc::Label Label;
35  lat_out->DeleteStates();
36  StateId cur_state = lat_out->AddState(); // will be 0.
37  lat_out->SetStart(cur_state);
38  for (size_t i = 0; i < ali.size() || i < words.size(); i++) {
39  Label ilabel = (i < ali.size() ? ali[i] : 0);
40  Label olabel = (i < words.size() ? words[i] : 0);
41  StateId next_state = lat_out->AddState();
42  lat_out->AddArc(cur_state,
43  LatticeArc(ilabel, olabel, Weight::One(), next_state));
44  cur_state = next_state;
45  }
46  lat_out->SetFinal(cur_state, Weight(lm_cost, ac_cost));
47 }
int32 words[kMaxOrder]
fst::StdArc::StateId StateId
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
fst::StdArc::Label Label
fst::StdArc::Weight Weight

◆ MakeTrivialAcceptor()

static fst::VectorFst<fst::StdArc>* kaldi::MakeTrivialAcceptor ( int32  label)
inlinestatic

This utility function, used in GetHTransducer(), creates an FSA (finite state acceptor, i.e.

an FST with ilabels equal to olabels) with a single successful path, with a single label on it.

Definition at line 239 of file hmm-utils.cc.

Referenced by GetHTransducer().

239  {
240  typedef fst::StdArc Arc;
241  typedef Arc::Weight Weight;
242  fst::VectorFst<Arc> *ans = new fst::VectorFst<Arc>;
243  ans->AddState();
244  ans->AddState();
245  ans->SetStart(0);
246  ans->SetFinal(1, Weight::One());
247  ans->AddArc(0, Arc(label, label, Weight::One(), 1));
248  return ans;
249 }
fst::StdArc StdArc
fst::StdArc::Weight Weight

◆ MapAmDiagGmmUpdate()

void MapAmDiagGmmUpdate ( const MapDiagGmmOptions config,
const AccumAmDiagGmm am_diag_gmm_acc,
GmmFlagsType  flags,
AmDiagGmm am_gmm,
BaseFloat obj_change_out,
BaseFloat count_out 
)

Maximum A Posteriori update.

Definition at line 237 of file mle-am-diag-gmm.cc.

References AmDiagGmm::Dim(), AccumAmDiagGmm::Dim(), AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), rnnlm::i, KALDI_ASSERT, MapDiagGmmUpdate(), AccumAmDiagGmm::NumAccs(), and AmDiagGmm::NumPdfs().

Referenced by main().

242  {
243  KALDI_ASSERT(am_gmm != NULL && am_diag_gmm_acc.Dim() == am_gmm->Dim() &&
244  am_diag_gmm_acc.NumAccs() == am_gmm->NumPdfs());
245  if (obj_change_out != NULL) *obj_change_out = 0.0;
246  if (count_out != NULL) *count_out = 0.0;
247  BaseFloat tmp_obj_change, tmp_count;
248  BaseFloat *p_obj = (obj_change_out != NULL) ? &tmp_obj_change : NULL,
249  *p_count = (count_out != NULL) ? &tmp_count : NULL;
250 
251  for (int32 i = 0; i < am_diag_gmm_acc.NumAccs(); i++) {
252  MapDiagGmmUpdate(config, am_diag_gmm_acc.GetAcc(i), flags,
253  &(am_gmm->GetPdf(i)), p_obj, p_count);
254 
255  if (obj_change_out != NULL) *obj_change_out += tmp_obj_change;
256  if (count_out != NULL) *count_out += tmp_count;
257  }
258 }
void MapDiagGmmUpdate(const MapDiagGmmOptions &config, const AccumDiagGmm &diag_gmm_acc, GmmFlagsType flags, DiagGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out)
Maximum A Posteriori estimation of the model.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ MapCygwinPath()

std::string kaldi::MapCygwinPath ( const std::string &  filename)

Definition at line 82 of file kaldi-cygwin-io-inl.h.

References KALDI_ERR, MapCygwinPathNoTmp(), and prefixp().

Referenced by UnitTestNativeFilename().

82  {
83  // /tmp[/....]
84  if (filename != "/tmp" && !prefixp("/tmp/", filename)) {
85  return MapCygwinPathNoTmp(filename);
86  }
87  char *tmpdir = std::getenv("TMP");
88  if (tmpdir == nullptr)
89  tmpdir = std::getenv("TEMP");
90  if (tmpdir == nullptr) {
91  KALDI_ERR << "Unable to resolve path '" << filename
92  << "' - unable to find temporary directory. Set TMP.";
93  return filename;
94  }
95  // Map the value of tmpdir again, as cygwin environment actually may contain
96  // unix-style paths.
97  return MapCygwinPathNoTmp(std::string(tmpdir) + filename.substr(4));
98 }
#define KALDI_ERR
Definition: kaldi-error.h:147
static std::string MapCygwinPathNoTmp(const std::string &filename)
static bool prefixp(const std::string &pfx, const std::string &str)

◆ MapCygwinPathNoTmp()

static std::string kaldi::MapCygwinPathNoTmp ( const std::string &  filename)
static

Definition at line 52 of file kaldi-cygwin-io-inl.h.

References KALDI_ERR, KALDI_WARN, and prefixp().

Referenced by MapCygwinPath().

52  {
53  // UNC(?), relative, native Windows and empty paths are ok already.
54  if (prefixp("//", filename) || !prefixp("/", filename))
55  return filename;
56 
57  // /dev/...
58  if (filename == "/dev/null")
59  return "\\\\.\\nul";
60  if (prefixp("/dev/", filename)) {
61  KALDI_ERR << "Unable to resolve path '" << filename
62  << "' - only have /dev/null here.";
63  return "\\\\.\\invalid";
64  }
65 
66  // /cygdrive/?[/....]
67  int preflen = cygprefix.size();
68  if (prefixp(cygprefix, filename)
69  && filename.size() >= preflen + 1 && isalpha(filename[preflen])
70  && (filename.size() == preflen + 1 || filename[preflen + 1] == '/')) {
71  return std::string() + filename[preflen] + ':' +
72  (filename.size() > preflen + 1 ? filename.substr(preflen + 1) : "/");
73  }
74 
75  KALDI_WARN << "Unable to resolve path '" << filename
76  << "' - cannot map unix prefix. "
77  << "Will go on, but breakage will likely ensue.";
78  return filename;
79 }
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
static std::string cygprefix("/cygdrive/")
static bool prefixp(const std::string &pfx, const std::string &str)

◆ MapDiagGmmUpdate()

void MapDiagGmmUpdate ( const MapDiagGmmOptions config,
const AccumDiagGmm diag_gmm_acc,
GmmFlagsType  flags,
DiagGmm gmm,
BaseFloat obj_change_out,
BaseFloat count_out 
)

Maximum A Posteriori estimation of the model.

Definition at line 410 of file mle-diag-gmm.cc.

References DiagGmm::ComputeGconsts(), MatrixBase< Real >::CopyRowFromVec(), DiagGmmNormal::CopyToDiagGmm(), DiagGmm::Dim(), AccumDiagGmm::Dim(), AccumDiagGmm::Flags(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, kGmmMeans, kGmmVariances, AccumDiagGmm::mean_accumulator(), MapDiagGmmOptions::mean_tau, DiagGmmNormal::means_, MlObjective(), DiagGmm::NumGauss(), AccumDiagGmm::NumGauss(), AccumDiagGmm::occupancy(), MatrixBase< Real >::Row(), VectorBase< Real >::Scale(), AccumDiagGmm::variance_accumulator(), MapDiagGmmOptions::variance_tau, DiagGmmNormal::vars_, MapDiagGmmOptions::weight_tau, and DiagGmmNormal::weights_.

Referenced by MapAmDiagGmmUpdate(), and AccumDiagGmm::Resize().

415  {
416  KALDI_ASSERT(gmm != NULL);
417 
418  if (flags & ~diag_gmm_acc.Flags())
419  KALDI_ERR << "Flags in argument do not match the active accumulators";
420 
421  KALDI_ASSERT(diag_gmm_acc.NumGauss() == gmm->NumGauss() &&
422  diag_gmm_acc.Dim() == gmm->Dim());
423 
424  int32 num_gauss = gmm->NumGauss();
425  double occ_sum = diag_gmm_acc.occupancy().Sum();
426 
427  // remember the old objective function value
428  gmm->ComputeGconsts();
429  BaseFloat obj_old = MlObjective(*gmm, diag_gmm_acc);
430 
431  // allocate the gmm in normal representation; all parameters of this will be
432  // updated, but only the flagged ones will be transferred back to gmm
433  DiagGmmNormal ngmm(*gmm);
434 
435  for (int32 i = 0; i < num_gauss; i++) {
436  double occ = diag_gmm_acc.occupancy()(i);
437 
438  // First update the weight. The weight_tau is a tau for the
439  // whole state.
440  ngmm.weights_(i) = (occ + ngmm.weights_(i) * config.weight_tau) /
441  (occ_sum + config.weight_tau);
442 
443 
444  if (occ > 0.0 && (flags & kGmmMeans)) {
445  // Update the Gaussian mean.
446  Vector<double> old_mean(ngmm.means_.Row(i));
447  Vector<double> mean(diag_gmm_acc.mean_accumulator().Row(i));
448  mean.Scale(1.0 / (occ + config.mean_tau));
449  mean.AddVec(config.mean_tau / (occ + config.mean_tau), old_mean);
450  ngmm.means_.CopyRowFromVec(mean, i);
451  }
452 
453  if (occ > 0.0 && (flags & kGmmVariances)) {
454  // Computing the variance around the updated mean; this is:
455  // E( (x - mu)^2 ) = E( x^2 - 2 x mu + mu^2 ) =
456  // E(x^2) + mu^2 - 2 mu E(x).
457  Vector<double> old_var(ngmm.vars_.Row(i));
458  Vector<double> var(diag_gmm_acc.variance_accumulator().Row(i));
459  var.Scale(1.0 / occ);
460  var.AddVec2(1.0, ngmm.means_.Row(i));
461  SubVector<double> mean_acc(diag_gmm_acc.mean_accumulator(), i),
462  mean(ngmm.means_, i);
463  var.AddVecVec(-2.0 / occ, mean_acc, mean, 1.0);
464  // now var is E(x^2) + m^2 - 2 mu E(x).
465  // Next we do the appropriate weighting usnig the tau value.
466  var.Scale(occ / (config.variance_tau + occ));
467  var.AddVec(config.variance_tau / (config.variance_tau + occ), old_var);
468  // Now write to the model.
469  ngmm.vars_.Row(i).CopyFromVec(var);
470  }
471  }
472 
473  // Copy to natural/exponential representation.
474  ngmm.CopyToDiagGmm(gmm, flags);
475 
476  gmm->ComputeGconsts(); // or MlObjective will fail.
477  BaseFloat obj_new = MlObjective(*gmm, diag_gmm_acc);
478 
479  if (obj_change_out)
480  *obj_change_out = (obj_new - obj_old);
481 
482  if (count_out) *count_out = occ_sum;
483 }
BaseFloat MlObjective(const DiagGmm &gmm, const AccumDiagGmm &diag_gmm_acc)
Calc using the DiagGMM exponential form.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ MapPhone()

static int32 kaldi::MapPhone ( const std::vector< int32 > &  phone_map,
int32  phone 
)
static

Definition at line 26 of file tree-accu.cc.

References KALDI_ERR.

Referenced by AccumulateTreeStats().

27  {
28  if (phone == 0 || phone_map.empty()) return phone;
29  else if (phone < 0 || phone >= phone_map.size()) {
30  KALDI_ERR << "Out-of-range phone " << phone << " bad --phone-map option?";
31  }
32  return phone_map[phone];
33 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ MapSymbols()

static void kaldi::MapSymbols ( const WordAlignLatticeLexiconInfo lexicon_info,
CompactLattice lat 
)
static

Testing code; map word symbols in the lattice "lat" using the equivalence-classes obtained from the lexicon, using the function EquivalenceClassOf in the lexicon_info object.

Definition at line 912 of file word-align-lattice-lexicon.cc.

References WordAlignLatticeLexiconInfo::EquivalenceClassOf(), and KALDI_ASSERT.

Referenced by TestWordAlignedLattice().

913  {
915  for (StateId s = 0; s < lat->NumStates(); s++) {
916  for (fst::MutableArcIterator<CompactLattice> aiter(lat, s);
917  !aiter.Done(); aiter.Next()) {
918  CompactLatticeArc arc (aiter.Value());
919  KALDI_ASSERT(arc.ilabel == arc.olabel);
920  arc.ilabel = lexicon_info.EquivalenceClassOf(arc.ilabel);
921  arc.olabel = arc.ilabel;
922  aiter.SetValue(arc);
923  }
924  }
925 }
fst::StdArc::StateId StateId
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ MatrixUnitSpeedTest()

static void kaldi::MatrixUnitSpeedTest ( )
static

Definition at line 257 of file matrix-lib-speed-test.cc.

257  {
258  UnitTestRealFftSpeed<Real>();
259  UnitTestSplitRadixRealFftSpeed<Real>();
260  UnitTestSvdSpeed<Real>();
261  UnitTestAddMatMatSpeed<Real>();
262  UnitTestAddRowSumMatSpeed<Real>();
263  UnitTestAddColSumMatSpeed<Real>();
264  UnitTestAddVecToRowsSpeed<Real>();
265  UnitTestAddVecToColsSpeed<Real>();
266 }

◆ MatrixUnitTest()

static void kaldi::MatrixUnitTest ( bool  full_test)
static

Definition at line 4592 of file matrix-lib-test.cc.

References KALDI_LOG, and UnitTestAddVecCross().

4592  {
4593  UnitTestLinearCgd<Real>();
4594  UnitTestGeneralMatrix<BaseFloat>();
4595  UnitTestTridiagonalize<Real>();
4596  UnitTestTridiagonalizeAndQr<Real>();
4597  UnitTestAddMatSmat<Real>();
4598  UnitTestFloorChol<Real>();
4599  UnitTestFloorUnit<Real>();
4600  UnitTestAddMat2Sp<Real>();
4601  UnitTestLbfgs<Real>();
4602  // UnitTestSvdBad<Real>(); // test bug in Jama SVD code.
4603  UnitTestCompressedMatrix<Real>();
4604  UnitTestCompressedMatrix2<Real>();
4605  UnitTestExtractCompressedMatrix<Real>();
4606  UnitTestResize<Real>();
4607  UnitTestResizeCopyDataDifferentStrideType<Real>();
4608  UnitTestNonsymmetricPower<Real>();
4609  UnitTestEigSymmetric<Real>();
4610  KALDI_LOG << " Point A";
4611  UnitTestComplexPower<Real>();
4612  UnitTestEig<Real>();
4613  UnitTestEigSp<Real>();
4614  // commenting these out for now-- they test the speed, but take a while.
4615  // UnitTestSplitRadixRealFftSpeed<Real>();
4616  // UnitTestRealFftSpeed<Real>(); // won't exit!/
4617  UnitTestComplexFt<Real>();
4618  KALDI_LOG << " Point B";
4619  UnitTestComplexFft2<Real>();
4620  UnitTestComplexFft<Real>();
4621  UnitTestSplitRadixComplexFft<Real>();
4622  UnitTestSplitRadixComplexFft2<Real>();
4623  UnitTestDct<Real>();
4624  UnitTestRealFft<Real>();
4625  KALDI_LOG << " Point C";
4626  UnitTestSplitRadixRealFft<Real>();
4627  UnitTestSvd<Real>();
4628  UnitTestSvdNodestroy<Real>();
4629  UnitTestSvdJustvec<Real>();
4630  UnitTestSpAddDiagVec<Real, float>();
4631  UnitTestSpAddDiagVec<Real, double>();
4632  UnitTestSpAddVecVec<Real>();
4633  UnitTestSpInvert<Real>();
4634  KALDI_LOG << " Point D";
4635  UnitTestTpInvert<Real>();
4636  UnitTestIo<Real>();
4637  UnitTestIoCross<Real>();
4638  UnitTestHtkIo<Real>();
4639  UnitTestScale<Real>();
4640  UnitTestTrace<Real>();
4641  KALDI_LOG << " Point E";
4642  CholeskyUnitTestTr<Real>();
4643  UnitTestAxpy<Real>();
4644  UnitTestSimple<Real>();
4645  UnitTestMmul<Real>();
4646  UnitTestMmulSym<Real>();
4647  UnitTestVecmul<Real>();
4648  UnitTestInverse<Real>();
4649  UnitTestMulElements<Real>();
4650  UnitTestDotprod<Real>();
4651  // UnitTestSvdVariants<Real>();
4652  UnitTestPower<Real>();
4653  UnitTestPowerAbs<Real>();
4654  UnitTestHeaviside<Real>();
4655  UnitTestCopySp<Real>();
4656  UnitTestDeterminant<Real>();
4657  KALDI_LOG << " Point F";
4658  UnitTestDeterminantSign<Real>();
4659  UnitTestSger<Real>();
4660  UnitTestAddOuterProductPlusMinus<Real>();
4661  UnitTestTraceProduct<Real>();
4662  UnitTestTransposeScatter<Real>();
4663  UnitTestRankNUpdate<Real>();
4664  UnitTestSpVec<Real>();
4665  UnitTestLimitCondInvert<Real>();
4666  KALDI_LOG << " Point G";
4667  UnitTestLimitCond<Real>();
4668  UnitTestMat2Vec<Real>();
4669  UnitTestFloorCeiling<Real>();
4670  KALDI_LOG << " Point H";
4671  UnitTestCopyRowsAndCols<Real>();
4672  UnitTestSpliceRows<Real>();
4673  UnitTestAddSp<Real>();
4674  UnitTestRemoveRow<Real>();
4675  UnitTestRow<Real>();
4676  UnitTestSubvector<Real>();
4677  UnitTestRange<Real>();
4678  UnitTestSimpleForVec<Real>();
4679  UnitTestSetRandn<Real>();
4680  UnitTestSetRandUniform<Real>();
4681  UnitTestVectorMax<Real>();
4682  UnitTestVectorMin<Real>();
4683  UnitTestSimpleForMat<Real>();
4684  UnitTestTanh<Real>();
4685  UnitTestSigmoid<Real>();
4686  UnitTestSoftHinge<Real>();
4687  UnitTestNorm<Real>();
4688  UnitTestCopyCols<Real>();
4689  UnitTestCopyRows<Real>();
4690  UnitTestCopyToRows<Real>();
4691  UnitTestAddRows<Real>();
4692  UnitTestAddToRows<Real>();
4693  UnitTestMul<Real>();
4694  KALDI_LOG << " Point I";
4695  UnitTestSolve<Real>();
4696  UnitTestAddMat2<Real>();
4697  UnitTestSymAddMat2<Real>();
4698  UnitTestAddMatSelf<Real>();
4699  UnitTestMaxMin<Real>();
4700  UnitTestInnerProd<Real>();
4701  UnitTestApplyExpSpecial<Real>();
4702  UnitTestScaleDiag<Real>();
4703  UnitTestSetDiag<Real>();
4704  UnitTestSetRandn<Real>();
4705  KALDI_LOG << " Point J";
4706  UnitTestTraceSpSpLower<Real>();
4707  UnitTestTranspose<Real>();
4708  UnitTestAddVec2Sp<Real>();
4709  UnitTestAddVecToRows<Real>();
4710  UnitTestAddVecToCols<Real>();
4712  UnitTestTp2Sp<Real>();
4713  UnitTestTp2<Real>();
4714  UnitTestAddDiagMat2<Real>();
4715  UnitTestAddDiagMatMat<Real>();
4716  // UnitTestOrthogonalizeRows<Real>();
4717  UnitTestTopEigs<Real>();
4718  UnitTestRandCategorical<Real>();
4719  UnitTestTridiag<Real>();
4720  UnitTestTridiag<Real>();
4721  // SlowMatMul<Real>();
4722  UnitTestAddDiagVecMat<Real>();
4723  UnitTestAddMatDiagVec<Real>();
4724  UnitTestAddMatMatElements<Real>();
4725  UnitTestAddMatMatNans<Real>();
4726  UnitTestAddToDiagMatrix<Real>();
4727  UnitTestAddToDiag<Real>();
4728  UnitTestMaxAbsEig<Real>();
4729  UnitTestMax2<Real>();
4730  UnitTestPca<Real>(full_test);
4731  UnitTestPca2<Real>(full_test);
4732  UnitTestAddVecVec<Real>();
4733  UnitTestReplaceValue<Real>();
4734  // The next one is slow. The upshot is that Eig is up to ten times faster
4735  // than SVD.
4736  // UnitTestSvdSpeed<Real>();
4737  KALDI_LOG << " Point K";
4738  UnitTestTriVecSolver<Real>();
4739 }
void UnitTestAddVecCross()
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ MaxAbsolute()

BaseFloat kaldi::MaxAbsolute ( const Vector< BaseFloat > &  vector)

Definition at line 52 of file wav-reverberate.cc.

References VectorBase< Real >::Max(), and VectorBase< Real >::Min().

52  {
53  return std::max(std::abs(vector.Max()), std::abs(vector.Min()));
54 }
Real Min() const
Returns the minimum value of any element, or +infinity for the empty vector.
Real Max() const
Returns the maximum value of any element, or -infinity for the empty vector.

◆ MaybeDoSanityCheck() [1/2]

void MaybeDoSanityCheck ( const KwsLexicographicFst index_transducer)

Definition at line 325 of file kws-functions.cc.

References DifferenceWrapper(), fst::GetLinearSymbolSequence(), GetVerboseLevel(), rnnlm::i, KALDI_VLOG, and KALDI_WARN.

Referenced by DoFactorMerging(), main(), and MaybeDoSanityCheck().

325  {
327  if (GetVerboseLevel() < 2) return;
328  KwsLexicographicFst temp_transducer;
329  ShortestPath(index_transducer, &temp_transducer);
330  std::vector<Label> isymbols, osymbols;
331  KwsLexicographicWeight weight;
332  GetLinearSymbolSequence(temp_transducer, &isymbols, &osymbols, &weight);
333  std::ostringstream os;
334  for (size_t i = 0; i < isymbols.size(); i++)
335  os << isymbols[i] << ' ';
336  BaseFloat best_cost = weight.Value1().Value();
337  KALDI_VLOG(3) << "Best path: " << isymbols.size() << " isymbols " << ", "
338  << osymbols.size() << " osymbols, isymbols are " << os.str()
339  << ", best cost is " << best_cost;
340 
341  // Now get second-best path. This will exclude the best path, which
342  // will generally correspond to the empty word sequence (there will
343  // be isymbols and osymbols anyway though, because of the utterance-id
344  // having been encoded as an osymbol (and later, the EncodeFst turning it
345  // into a transducer).
346  KwsLexicographicFst difference_transducer;
347  DifferenceWrapper(index_transducer, temp_transducer, &difference_transducer);
348  ShortestPath(difference_transducer, &temp_transducer);
349 
350  GetLinearSymbolSequence(temp_transducer, &isymbols, &osymbols, &weight);
351  std::ostringstream os2;
352  for (size_t i = 0; i < isymbols.size(); i++)
353  os2 << isymbols[i] << ' ';
354  BaseFloat second_best_cost = weight.Value1().Value();
355  KALDI_VLOG(3) << "Second-best path: " << isymbols.size()
356  << " isymbols " << ", "
357  << osymbols.size() << " osymbols, isymbols are " << os2.str()
358  << ", second-best cost is " << second_best_cost;
359  if (second_best_cost < -0.01) {
360  KALDI_WARN << "Negative second-best cost found " << second_best_cost;
361  }
362 }
int32 GetVerboseLevel()
Get verbosity level, usually set via command line &#39;–verbose=&#39; switch.
Definition: kaldi-error.h:60
static void DifferenceWrapper(const fst::VectorFst< Arc > &fst1, const fst::VectorFst< Arc > &fst2, fst::VectorFst< Arc > *difference)
bool GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
fst::VectorFst< KwsLexicographicArc > KwsLexicographicFst
Definition: kaldi-kws.h:46
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Label Label
StdLStdLStdWeight KwsLexicographicWeight
Definition: kaldi-kws.h:44
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ MaybeDoSanityCheck() [2/2]

void MaybeDoSanityCheck ( const KwsProductFst product_transducer)

Definition at line 365 of file kws-functions.cc.

References GetVerboseLevel(), and MaybeDoSanityCheck().

365  {
366  if (GetVerboseLevel() < 2) return;
367  KwsLexicographicFst index_transducer;
368 
369  Map(product_transducer,
370  &index_transducer,
371  KwsProductFstToKwsLexicographicFstMapper());
372 
373  MaybeDoSanityCheck(index_transducer);
374 }
void MaybeDoSanityCheck(const KwsProductFst &product_transducer)
int32 GetVerboseLevel()
Get verbosity level, usually set via command line &#39;–verbose=&#39; switch.
Definition: kaldi-error.h:60
fst::VectorFst< KwsLexicographicArc > KwsLexicographicFst
Definition: kaldi-kws.h:46

◆ MeanVariance() [1/2]

std::string kaldi::MeanVariance ( const CuMatrixBase< Real > &  m)

Definition at line 49 of file cu-rand-speed-test.cc.

References CuMatrixBase< Real >::Add(), CuMatrixBase< Real >::ApplyPow(), CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), CuMatrixBase< Real >::Sum(), and ToString().

Referenced by CuRandGaussianMatrixBaseSpeedTest(), CuRandGaussianMatrixSpeedTest(), CuRandGaussianVectorSpeedTest(), CuRandUniformMatrixBaseSpeedTest(), CuRandUniformMatrixSpeedTest(), and CuRandUniformVectorSpeedTest().

49  {
50  std::ostringstream os;
51  Real mean = m.Sum() / (m.NumRows()*m.NumCols());
52  CuMatrix<Real> tmp(m);
53  tmp.Add(-mean);
54  tmp.ApplyPow(2.0);
55  Real var = tmp.Sum() / (tmp.NumRows()*tmp.NumCols());
56  return std::string("mean ") + ToString(mean) + ", std-dev " + ToString(std::sqrt(var));
57 }
Real Sum() const
Definition: cu-matrix.cc:3012
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
MatrixIndexT NumCols() const
Definition: cu-matrix.h:216
std::string ToString(const T &t)
MatrixIndexT NumRows() const
Dimensions.
Definition: cu-matrix.h:215

◆ MeanVariance() [2/2]

std::string kaldi::MeanVariance ( const CuVectorBase< Real > &  v)

Definition at line 60 of file cu-rand-speed-test.cc.

References CuVectorBase< Real >::Add(), CuVectorBase< Real >::ApplyPow(), CuVectorBase< Real >::Dim(), CuVectorBase< Real >::Sum(), and ToString().

60  {
61  std::ostringstream os;
62  Real mean = v.Sum() / v.Dim();
63  CuVector<Real> tmp(v);
64  tmp.Add(-mean);
65  tmp.ApplyPow(2.0);
66  Real var = tmp.Sum() / tmp.Dim();
67  return std::string("mean ") + ToString(mean) + ", std-dev " + ToString(std::sqrt(var));
68 }
Real Sum() const
Definition: cu-vector.cc:297
std::string ToString(const T &t)
MatrixIndexT Dim() const
Dimensions.
Definition: cu-vector.h:69

◆ MergeFullGmm()

void kaldi::MergeFullGmm ( const FullGmm src,
FullGmm dst 
)

merges GMMs by appending Gaussians in "src" to "dst".

Renormalizes weights by allocating weight proportional to #Gauss.

Definition at line 28 of file fgmm-global-merge.cc.

References FullGmm::ComputeGconsts(), FullGmm::CopyFromFullGmm(), FullGmm::Dim(), rnnlm::i, FullGmm::inv_covars(), KALDI_ASSERT, FullGmm::means_invcovars(), FullGmm::NumGauss(), VectorBase< Real >::Range(), MatrixBase< Real >::Range(), FullGmm::Resize(), FullGmm::SetInvCovarsAndMeansInvCovars(), FullGmm::SetWeights(), and FullGmm::weights().

Referenced by main().

28  {
29  FullGmm dst_copy;
30  dst_copy.CopyFromFullGmm(*dst);
31  KALDI_ASSERT(src.NumGauss() != 0 && dst_copy.NumGauss() != 0
32  && src.Dim() == dst_copy.Dim());
33  int32 src_num_mix = src.NumGauss(), dst_num_mix = dst_copy.NumGauss(),
34  num_mix = src_num_mix + dst_num_mix, dim = src.Dim();
35  dst->Resize(num_mix, dim);
36 
37  std::vector<SpMatrix<BaseFloat> > invcovars(num_mix);
38  for(int32 i = 0; i < dst_num_mix; i++) {
39  invcovars[i].Resize(dim);
40  invcovars[i].CopyFromSp(dst_copy.inv_covars()[i]);
41  }
42  for(int32 i = 0; i < src_num_mix; i++) {
43  invcovars[i+dst_num_mix].Resize(dim);
44  invcovars[i+dst_num_mix].CopyFromSp(src.inv_covars()[i]);
45  }
46  Matrix<BaseFloat> means_invcovars(num_mix, dim);
47  means_invcovars.Range(0, dst_num_mix, 0, dim).CopyFromMat(dst_copy.means_invcovars());
48  means_invcovars.Range(dst_num_mix, src_num_mix, 0, dim).CopyFromMat(src.means_invcovars());
49  dst->SetInvCovarsAndMeansInvCovars(invcovars, means_invcovars);
50 
51  Vector<BaseFloat> weights(num_mix); // initialized to zero.
52  // weight proportional to #Gaussians, so that if we combine a number of
53  // models with same #Gaussians, they all get the same weight.
54  BaseFloat src_weight = src_num_mix / static_cast<BaseFloat>(num_mix),
55  dst_weight = dst_num_mix / static_cast<BaseFloat>(num_mix);
56  weights.Range(0, dst_num_mix).AddVec(dst_weight, dst_copy.weights());
57  weights.Range(dst_num_mix, src_num_mix).AddVec(src_weight, src.weights());
58  dst->SetWeights(weights);
59  dst->ComputeGconsts();
60 }
void SetWeights(const Vector< Real > &w)
Mutators for both float or double.
Definition: full-gmm-inl.h:31
const std::vector< SpMatrix< BaseFloat > > & inv_covars() const
Definition: full-gmm.h:146
int32 Dim() const
Returns the dimensionality of the Gaussian mean vectors.
Definition: full-gmm.h:60
int32 ComputeGconsts()
Sets the gconsts.
Definition: full-gmm.cc:92
Definition for Gaussian Mixture Model with full covariances.
Definition: full-gmm.h:40
kaldi::int32 int32
void CopyFromFullGmm(const FullGmm &fullgmm)
Copies from given FullGmm.
Definition: full-gmm.cc:65
float BaseFloat
Definition: kaldi-types.h:29
void Resize(int32 nMix, int32 dim)
Resizes arrays to this dim. Does not initialize data.
Definition: full-gmm.cc:41
int32 NumGauss() const
Returns the number of mixture components in the GMM.
Definition: full-gmm.h:58
const Vector< BaseFloat > & weights() const
Definition: full-gmm.h:144
void SetInvCovarsAndMeansInvCovars(const std::vector< SpMatrix< Real > > &invcovars, const Matrix< Real > &means_invcovars)
Use this if setting both, in the class&#39;s native format.
Definition: full-gmm-inl.h:67
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
const Matrix< BaseFloat > & means_invcovars() const
Definition: full-gmm.h:145

◆ MergePairVectorSumming()

void kaldi::MergePairVectorSumming ( std::vector< std::pair< I, F > > *  vec)
inline

For a vector of pair<I, F> where I is an integer and F a floating-point or integer type, this function sorts a vector of type vector<pair<I, F> > on the I value and then merges elements with equal I values, summing these over the F component and then removing any F component with zero value.

This is for where the vector of pairs represents a map from the integer to float component, with an "adding" type of semantics for combining the elements.

Definition at line 288 of file stl-utils.h.

References KALDI_ASSERT_IS_INTEGER_TYPE.

Referenced by LatticeForwardBackward(), LatticeForwardBackwardMpeVariants(), MergePosteriors(), TestMergePairVectorSumming(), and OnlineIvectorFeature::UpdateStatsForFrames().

288  {
290  CompareFirstMemberOfPair<I, F> c;
291  std::sort(vec->begin(), vec->end(), c); // sort on 1st element.
292  typename std::vector<std::pair<I, F> >::iterator out = vec->begin(),
293  in = vec->begin(), end = vec->end();
294  // special case: while there is nothing to be changed, skip over
295  // initial input (avoids unnecessary copying).
296  while (in + 1 < end && in[0].first != in[1].first && in[0].second != 0.0) {
297  in++;
298  out++;
299  }
300  while (in < end) {
301  // We reach this point only at the first element of
302  // each stretch of identical .first elements.
303  *out = *in;
304  ++in;
305  while (in < end && in->first == out->first) {
306  out->second += in->second; // this is the merge operation.
307  ++in;
308  }
309  if (out->second != static_cast<F>(0)) // Don't keep zero elements.
310  out++;
311  }
312  vec->erase(out, end);
313 }
#define KALDI_ASSERT_IS_INTEGER_TYPE(I)
Definition: kaldi-utils.h:133

◆ MleAmDiagGmmUpdate()

void MleAmDiagGmmUpdate ( const MleDiagGmmOptions config,
const AccumAmDiagGmm amdiaggmm_acc,
GmmFlagsType  flags,
AmDiagGmm am_gmm,
BaseFloat obj_change_out,
BaseFloat count_out 
)

for computing the maximum-likelihood estimates of the parameters of an acoustic model that uses diagonal Gaussian mixture models as emission densities.

Definition at line 187 of file mle-am-diag-gmm.cc.

References count, AmDiagGmm::Dim(), AccumAmDiagGmm::Dim(), AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, KALDI_WARN, MleDiagGmmOptions::min_gaussian_occupancy, MleDiagGmmUpdate(), AccumAmDiagGmm::NumAccs(), AmDiagGmm::NumGauss(), AmDiagGmm::NumPdfs(), MleDiagGmmOptions::remove_low_count_gaussians, and ResizeModel().

Referenced by main(), TestAmDiagGmmAccsIO(), and UnitTestRegtreeFmllrDiagGmm().

192  {
193  if (am_diag_gmm_acc.Dim() != am_gmm->Dim()) {
194  KALDI_ASSERT(am_diag_gmm_acc.Dim() != 0);
195  KALDI_WARN << "Dimensions of accumulator " << am_diag_gmm_acc.Dim()
196  << " and gmm " << am_gmm->Dim() << " do not match, resizing "
197  << " GMM and setting to zero-mean, unit-variance.";
198  ResizeModel(am_diag_gmm_acc.Dim(), am_gmm);
199  }
200 
201  KALDI_ASSERT(am_gmm != NULL);
202  KALDI_ASSERT(am_diag_gmm_acc.NumAccs() == am_gmm->NumPdfs());
203  if (obj_change_out != NULL) *obj_change_out = 0.0;
204  if (count_out != NULL) *count_out = 0.0;
205 
206  BaseFloat tot_obj_change = 0.0, tot_count = 0.0;
207  int32 tot_elems_floored = 0, tot_gauss_floored = 0,
208  tot_gauss_removed = 0;
209  for (int32 i = 0; i < am_diag_gmm_acc.NumAccs(); i++) {
210  BaseFloat obj_change, count;
211  int32 elems_floored, gauss_floored, gauss_removed;
212 
213  MleDiagGmmUpdate(config, am_diag_gmm_acc.GetAcc(i), flags,
214  &(am_gmm->GetPdf(i)),
215  &obj_change, &count, &elems_floored,
216  &gauss_floored, &gauss_removed);
217  tot_obj_change += obj_change;
218  tot_count += count;
219  tot_elems_floored += elems_floored;
220  tot_gauss_floored += gauss_floored;
221  tot_gauss_removed += gauss_removed;
222  }
223  if (obj_change_out != NULL) *obj_change_out = tot_obj_change;
224  if (count_out != NULL) *count_out = tot_count;
225  KALDI_LOG << tot_elems_floored << " variance elements floored in "
226  << tot_gauss_floored << " Gaussians, out of "
227  << am_gmm->NumGauss();
228  if (config.remove_low_count_gaussians) {
229  KALDI_LOG << "Removed " << tot_gauss_removed
230  << " Gaussians due to counts < --min-gaussian-occupancy="
231  << config.min_gaussian_occupancy
232  << " and --remove-low-count-gaussians=true";
233  }
234 }
void MleDiagGmmUpdate(const MleDiagGmmOptions &config, const AccumDiagGmm &diag_gmm_acc, GmmFlagsType flags, DiagGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out, int32 *floored_elements_out, int32 *floored_gaussians_out, int32 *removed_gaussians_out)
for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model...
kaldi::int32 int32
void ResizeModel(int32 dim, AmDiagGmm *am_gmm)
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ MleDiagGmmUpdate()

void MleDiagGmmUpdate ( const MleDiagGmmOptions config,
const AccumDiagGmm diag_gmm_acc,
GmmFlagsType  flags,
DiagGmm gmm,
BaseFloat obj_change_out,
BaseFloat count_out,
int32 floored_elements_out = NULL,
int32 floored_gauss_out = NULL,
int32 removed_gauss_out = NULL 
)

for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model.

Update using the DiagGmm: exponential form. Sets, does not increment, objf_change_out, floored_elements_out and floored_gauss_out.

Definition at line 275 of file mle-diag-gmm.cc.

References DiagGmm::ComputeGconsts(), MatrixBase< Real >::CopyRowFromVec(), DiagGmmNormal::CopyToDiagGmm(), VectorBase< Real >::Dim(), DiagGmm::Dim(), AccumDiagGmm::Dim(), AccumDiagGmm::Flags(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_VLOG, KALDI_WARN, kGmmMeans, kGmmVariances, AccumDiagGmm::mean_accumulator(), DiagGmmNormal::means_, MleDiagGmmOptions::min_gaussian_occupancy, MleDiagGmmOptions::min_gaussian_weight, MleDiagGmmOptions::min_variance, MlObjective(), DiagGmm::NumGauss(), AccumDiagGmm::NumGauss(), AccumDiagGmm::occupancy(), MleDiagGmmOptions::remove_low_count_gaussians, DiagGmm::RemoveComponents(), MatrixBase< Real >::Row(), VectorBase< Real >::Scale(), AccumDiagGmm::variance_accumulator(), MleDiagGmmOptions::variance_floor_vector, DiagGmmNormal::vars_, and DiagGmmNormal::weights_.

Referenced by main(), MleAmDiagGmmUpdate(), AccumDiagGmm::Resize(), test_flags_driven_update(), test_io(), TestComponentAcc(), TrainOneIter(), UnitTestDiagGmmGenerate(), and UnitTestEstimateDiagGmm().

283  {
284  KALDI_ASSERT(gmm != NULL);
285 
286  if (flags & ~diag_gmm_acc.Flags())
287  KALDI_ERR << "Flags in argument do not match the active accumulators";
288 
289  KALDI_ASSERT(diag_gmm_acc.NumGauss() == gmm->NumGauss() &&
290  diag_gmm_acc.Dim() == gmm->Dim());
291 
292  int32 num_gauss = gmm->NumGauss();
293  double occ_sum = diag_gmm_acc.occupancy().Sum();
294 
295  int32 elements_floored = 0, gauss_floored = 0;
296 
297  // remember old objective value
298  gmm->ComputeGconsts();
299  BaseFloat obj_old = MlObjective(*gmm, diag_gmm_acc);
300 
301  // First get the gmm in "normal" representation (not the exponential-model
302  // form).
303  DiagGmmNormal ngmm(*gmm);
304 
305  std::vector<int32> to_remove;
306  for (int32 i = 0; i < num_gauss; i++) {
307  double occ = diag_gmm_acc.occupancy()(i);
308  double prob;
309  if (occ_sum > 0.0)
310  prob = occ / occ_sum;
311  else
312  prob = 1.0 / num_gauss;
313 
314  if (occ > static_cast<double>(config.min_gaussian_occupancy)
315  && prob > static_cast<double>(config.min_gaussian_weight)) {
316 
317  ngmm.weights_(i) = prob;
318 
319  // copy old mean for later normalizations
320  Vector<double> old_mean(ngmm.means_.Row(i));
321 
322  // update mean, then variance, as far as there are accumulators
323  if (diag_gmm_acc.Flags() & (kGmmMeans|kGmmVariances)) {
324  Vector<double> mean(diag_gmm_acc.mean_accumulator().Row(i));
325  mean.Scale(1.0 / occ);
326  // transfer to estimate
327  ngmm.means_.CopyRowFromVec(mean, i);
328  }
329 
330  if (diag_gmm_acc.Flags() & kGmmVariances) {
331  KALDI_ASSERT(diag_gmm_acc.Flags() & kGmmMeans);
332  Vector<double> var(diag_gmm_acc.variance_accumulator().Row(i));
333  var.Scale(1.0 / occ);
334  var.AddVec2(-1.0, ngmm.means_.Row(i)); // subtract squared means.
335 
336  // if we intend to only update the variances, we need to compensate by
337  // adding the difference between the new and old mean
338  if (!(flags & kGmmMeans)) {
339  old_mean.AddVec(-1.0, ngmm.means_.Row(i));
340  var.AddVec2(1.0, old_mean);
341  }
342  int32 floored;
343  if (config.variance_floor_vector.Dim() != 0) {
344  floored = var.ApplyFloor(config.variance_floor_vector);
345  } else {
346  var.ApplyFloor(config.min_variance, &floored);
347  }
348  if (floored != 0) {
349  elements_floored += floored;
350  gauss_floored++;
351  }
352  // transfer to estimate
353  ngmm.vars_.CopyRowFromVec(var, i);
354  }
355  } else { // Insufficient occupancy.
356  if (config.remove_low_count_gaussians &&
357  static_cast<int32>(to_remove.size()) < num_gauss-1) {
358  // remove the component, unless it is the last one.
359  KALDI_WARN << "Too little data - removing Gaussian (weight "
360  << std::fixed << prob
361  << ", occupation count " << std::fixed << diag_gmm_acc.occupancy()(i)
362  << ", vector size " << gmm->Dim() << ")";
363  to_remove.push_back(i);
364  } else {
365  KALDI_WARN << "Gaussian has too little data but not removing it because"
366  << (config.remove_low_count_gaussians ?
367  " it is the last Gaussian: i = "
368  : " remove-low-count-gaussians == false: g = ") << i
369  << ", occ = " << diag_gmm_acc.occupancy()(i) << ", weight = " << prob;
370  ngmm.weights_(i) =
371  std::max(prob, static_cast<double>(config.min_gaussian_weight));
372  }
373  }
374  }
375 
376  // copy to natural representation according to flags
377  ngmm.CopyToDiagGmm(gmm, flags);
378 
379  gmm->ComputeGconsts(); // or MlObjective will fail.
380  BaseFloat obj_new = MlObjective(*gmm, diag_gmm_acc);
381 
382  if (obj_change_out)
383  *obj_change_out = (obj_new - obj_old);
384  if (count_out) *count_out = occ_sum;
385  if (floored_elements_out) *floored_elements_out = elements_floored;
386  if (floored_gaussians_out) *floored_gaussians_out = gauss_floored;
387 
388  if (to_remove.size() > 0) {
389  gmm->RemoveComponents(to_remove, true /*renormalize weights*/);
390  gmm->ComputeGconsts();
391  }
392  if (removed_gaussians_out != NULL) *removed_gaussians_out = to_remove.size();
393 
394  if (gauss_floored > 0)
395  KALDI_VLOG(2) << gauss_floored << " variances floored in " << gauss_floored
396  << " Gaussians.";
397 }
BaseFloat MlObjective(const DiagGmm &gmm, const AccumDiagGmm &diag_gmm_acc)
Calc using the DiagGMM exponential form.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ MleFullGmmUpdate()

void MleFullGmmUpdate ( const MleFullGmmOptions config,
const AccumFullGmm fullgmm_acc,
GmmFlagsType  flags,
FullGmm gmm,
BaseFloat obj_change_out,
BaseFloat count_out 
)

for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model.

Update using the FullGmm exponential form

Definition at line 282 of file mle-full-gmm.cc.

References FullGmm::ComputeGconsts(), MatrixBase< Real >::CopyRowFromVec(), FullGmmNormal::CopyToFullGmm(), AccumFullGmm::covariance_accumulator(), FullGmm::Dim(), AccumFullGmm::Flags(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_WARN, kGmmMeans, kGmmVariances, MleFullGmmOptions::max_condition, AccumFullGmm::mean_accumulator(), FullGmmNormal::means_, MleFullGmmOptions::min_gaussian_occupancy, MleFullGmmOptions::min_gaussian_weight, MlObjective(), FullGmm::NumGauss(), AccumFullGmm::occupancy(), MleFullGmmOptions::remove_low_count_gaussians, FullGmm::RemoveComponents(), MatrixBase< Real >::Row(), PackedMatrix< Real >::Scale(), VectorBase< Real >::Scale(), VectorBase< Real >::Sum(), MleFullGmmOptions::variance_floor, FullGmmNormal::vars_, and FullGmmNormal::weights_.

Referenced by main(), AccumFullGmm::Resize(), test_flags_driven_update(), test_io(), TestComponentAcc(), UnitTestEstimateFullGmm(), and UnitTestFullGmmEst().

287  {
288  KALDI_ASSERT(gmm != NULL);
289 
290  if (flags & ~fullgmm_acc.Flags())
291  KALDI_ERR << "Flags in argument do not match the active accumulators";
292 
293  gmm->ComputeGconsts();
294  BaseFloat obj_old = MlObjective(*gmm, fullgmm_acc);
295 
296  // Korbinian: I removed checks that validate if the referenced gmm matches
297  // the accumulator, as this should be responsibility of the caller.
298  // Furthermore, the re-estimation of the normal representation is done
299  // regardless of the flags, but the transfer to the natural form is
300  // done with respect to the flags.
301 
302  int32 num_gauss = gmm->NumGauss();
303  double occ_sum = fullgmm_acc.occupancy().Sum();
304 
305  int32 tot_floored = 0, gauss_floored = 0;
306 
307  // allocate the gmm in normal representation
308  FullGmmNormal ngmm(*gmm);
309 
310  std::vector<int32> to_remove;
311  for (int32 i = 0; i < num_gauss; i++) {
312  double occ = fullgmm_acc.occupancy()(i);
313  double prob;
314  if (occ_sum > 0.0)
315  prob = occ / occ_sum;
316  else
317  prob = 1.0 / num_gauss;
318 
319  if (occ > static_cast<double> (config.min_gaussian_occupancy)
320  && prob > static_cast<double> (config.min_gaussian_weight)) {
321 
322  ngmm.weights_(i) = prob;
323 
324  // copy old mean for later normalizations
325  Vector<double> oldmean(ngmm.means_.Row(i));
326 
327  // update mean, then variance, as far as there are accumulators
328  if (fullgmm_acc.Flags() & (kGmmMeans|kGmmVariances)) {
329  Vector<double> mean(fullgmm_acc.mean_accumulator().Row(i));
330  mean.Scale(1.0 / occ);
331 
332  // transfer to estimate
333  ngmm.means_.CopyRowFromVec(mean, i);
334  }
335 
336  if (fullgmm_acc.Flags() & kGmmVariances) {
337  KALDI_ASSERT(fullgmm_acc.Flags() & kGmmMeans);
338  SpMatrix<double> covar(fullgmm_acc.covariance_accumulator()[i]);
339  covar.Scale(1.0 / occ);
340  covar.AddVec2(-1.0, ngmm.means_.Row(i)); // subtract squared means.
341  // if we intend to only update the variances, we need to compensate by
342  // adding the difference between the new and old mean
343  if (!(flags & kGmmMeans)) {
344  oldmean.AddVec(-1.0, ngmm.means_.Row(i));
345  covar.AddVec2(1.0, oldmean);
346  }
347 
348  // Now flooring etc. of variance's eigenvalues.
349  BaseFloat floor = std::max(static_cast<double>(config.variance_floor),
350  covar.MaxAbsEig() / config.max_condition);
351 
352  int32 floored = covar.ApplyFloor(floor);
353 
354  if (floored) {
355  tot_floored += floored;
356  gauss_floored++;
357  }
358 
359  // transfer to estimate
360  ngmm.vars_[i].CopyFromSp(covar);
361  }
362  } else { // Insufficient occupancy
363  if (config.remove_low_count_gaussians &&
364  static_cast<int32>(to_remove.size()) < num_gauss-1) {
365  KALDI_WARN << "Too little data - removing Gaussian (weight "
366  << std::fixed << prob
367  << ", occupation count " << std::fixed << fullgmm_acc.occupancy()(i)
368  << ", vector size " << gmm->Dim() << ")";
369  to_remove.push_back(i);
370  } else {
371  KALDI_WARN << "Gaussian has too little data but not removing it because"
372  << (config.remove_low_count_gaussians ?
373  " it is the last Gaussian: i = "
374  : " remove-low-count-gaussians == false: i = ") << i
375  << ", occ = " << fullgmm_acc.occupancy()(i) << ", weight = " << prob;
376  ngmm.weights_(i) =
377  std::max(prob, static_cast<double>(config.min_gaussian_weight));
378  }
379  }
380  }
381 
382  // copy to natural representation according to flags
383  ngmm.CopyToFullGmm(gmm, flags);
384 
385  gmm->ComputeGconsts();
386  BaseFloat obj_new = MlObjective(*gmm, fullgmm_acc);
387 
388  if (obj_change_out)
389  *obj_change_out = obj_new - obj_old;
390 
391  if (count_out)
392  *count_out = occ_sum;
393 
394  if (to_remove.size() > 0) {
395  gmm->RemoveComponents(to_remove, true /* renorm weights */);
396  gmm->ComputeGconsts();
397  }
398 
399  if (tot_floored > 0)
400  KALDI_WARN << tot_floored << " variances floored in " << gauss_floored
401  << " Gaussians.";
402 
403 }
BaseFloat MlObjective(const FullGmm &gmm, const AccumFullGmm &fullgmm_acc)
Calc using the DiagGMM exponential form.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ MllrAuxFunction()

static BaseFloat kaldi::MllrAuxFunction ( const Matrix< BaseFloat > &  xform,
const AffineXformStats stats 
)
static

Definition at line 308 of file regtree-mllr-diag-gmm.cc.

References VectorBase< Real >::AddSpVec(), rnnlm::d, AffineXformStats::G_, AffineXformStats::K_, kTrans, MatrixBase< Real >::Row(), TraceMatMat(), and VecVec().

Referenced by RegtreeMllrDiagGmmAccs::Update().

309  {
310  int32 dim = stats.G_.size();
311  Matrix<double> xform_d(xform);
312  Vector<double> xform_row_g(dim + 1);
313  SubMatrix<double> A(xform_d, 0, dim, 0, dim);
314  double obj = TraceMatMat(xform_d, stats.K_, kTrans);
315  for (int32 d = 0; d < dim; d++) {
316  xform_row_g.AddSpVec(1.0, stats.G_[d], xform_d.Row(d), 0.0);
317  obj -= 0.5 * VecVec(xform_row_g, xform_d.Row(d));
318  }
319  return obj;
320 }
kaldi::int32 int32
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ MlObjective() [1/2]

BaseFloat MlObjective ( const DiagGmm gmm,
const AccumDiagGmm diag_gmm_acc 
)

Calc using the DiagGMM exponential form.

Definition at line 261 of file mle-diag-gmm.cc.

References AccumDiagGmm::Flags(), DiagGmm::gconsts(), DiagGmm::inv_vars(), kGmmMeans, kGmmVariances, kTrans, AccumDiagGmm::mean_accumulator(), DiagGmm::means_invvars(), AccumDiagGmm::occupancy(), TraceMatMat(), AccumDiagGmm::variance_accumulator(), and VecVec().

Referenced by MapDiagGmmUpdate(), MleDiagGmmUpdate(), MleFullGmmUpdate(), AccumFullGmm::Resize(), and AccumDiagGmm::Resize().

262  {
263  GmmFlagsType acc_flags = diag_gmm_acc.Flags();
264  Vector<BaseFloat> occ_bf(diag_gmm_acc.occupancy());
265  Matrix<BaseFloat> mean_accs_bf(diag_gmm_acc.mean_accumulator());
266  Matrix<BaseFloat> variance_accs_bf(diag_gmm_acc.variance_accumulator());
267  BaseFloat obj = VecVec(occ_bf, gmm.gconsts());
268  if (acc_flags & kGmmMeans)
269  obj += TraceMatMat(mean_accs_bf, gmm.means_invvars(), kTrans);
270  if (acc_flags & kGmmVariances)
271  obj -= 0.5 * TraceMatMat(variance_accs_bf, gmm.inv_vars(), kTrans);
272  return obj;
273 }
uint16 GmmFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:35
float BaseFloat
Definition: kaldi-types.h:29
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ MlObjective() [2/2]

BaseFloat MlObjective ( const FullGmm gmm,
const AccumFullGmm fullgmm_acc 
)

Calc using the DiagGMM exponential form.

Definition at line 261 of file mle-full-gmm.cc.

References AccumFullGmm::covariance_accumulator(), FullGmm::Dim(), AccumFullGmm::Flags(), FullGmm::gconsts(), rnnlm::i, FullGmm::inv_covars(), kGmmMeans, kGmmVariances, kTrans, AccumFullGmm::mean_accumulator(), FullGmm::means_invcovars(), FullGmm::NumGauss(), AccumFullGmm::occupancy(), TraceMatMat(), TraceSpSp(), and VecVec().

261  {
262  GmmFlagsType flags = fullgmm_acc.Flags();
263  Vector<BaseFloat> occ_bf(fullgmm_acc.occupancy());
264  Matrix<BaseFloat> mean_accs_bf(fullgmm_acc.mean_accumulator());
265  SpMatrix<BaseFloat> covar_accs_bf(gmm.Dim());
266 
267  BaseFloat obj = VecVec(occ_bf, gmm.gconsts());
268 
269  if (flags & kGmmMeans)
270  obj += TraceMatMat(mean_accs_bf, gmm.means_invcovars(), kTrans);
271 
272  if (flags & kGmmVariances) {
273  for (int32 i = 0; i < gmm.NumGauss(); i++) {
274  covar_accs_bf.CopyFromSp(fullgmm_acc.covariance_accumulator()[i]);
275  obj -= 0.5 * TraceSpSp(covar_accs_bf, gmm.inv_covars()[i]);
276  }
277  }
278 
279  return obj;
280 }
kaldi::int32 int32
uint16 GmmFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:35
float BaseFloat
Definition: kaldi-types.h:29
double TraceSpSp(const SpMatrix< double > &A, const SpMatrix< double > &B)
Definition: sp-matrix.cc:326
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ ModifyGraphForCarefulAlignment()

void ModifyGraphForCarefulAlignment ( fst::VectorFst< fst::StdArc > *  fst)

This function modifies the decoding graph for what we call "careful alignment".

The problem we are trying to solve is that if the decoding eats up the words in the graph too fast, it can get stuck at the end, and produce what looks like a valid alignment even though there was really a failure. So what we want to do is to introduce, after the final-states of the graph, a "blind alley" with no final-probs reachable, where the decoding can go to get lost. Our basic idea is to append the decoding-graph to itself using the fst Concat operation; but in order that there should be final-probs at the end of the first but not the second FST, we modify the right-hand argument to the Concat operation so that it has none of the original final-probs, and add a "pre-initial" state that is final.

Definition at line 546 of file decoder-wrappers.cc.

References KALDI_WARN.

Referenced by AlignUtteranceWrapper(), and AlignConfig::Register().

547  {
548  typedef fst::StdArc Arc;
549  typedef Arc::StateId StateId;
550  typedef Arc::Label Label;
551  typedef Arc::Weight Weight;
552  StateId num_states = fst->NumStates();
553  if (num_states == 0) {
554  KALDI_WARN << "Empty FST input.";
555  return;
556  }
557  Weight zero = Weight::Zero();
558  // fst_rhs will be the right hand side of the Concat operation.
559  fst::VectorFst<fst::StdArc> fst_rhs(*fst);
560  // first remove the final-probs from fst_rhs.
561  for (StateId state = 0; state < num_states; state++)
562  fst_rhs.SetFinal(state, zero);
563  StateId pre_initial = fst_rhs.AddState();
564  Arc to_initial(0, 0, Weight::One(), fst_rhs.Start());
565  fst_rhs.AddArc(pre_initial, to_initial);
566  fst_rhs.SetStart(pre_initial);
567  // make the pre_initial state final with probability one;
568  // this is equivalent to keeping the final-probs of the first
569  // FST when we do concat (otherwise they would get deleted).
570  fst_rhs.SetFinal(pre_initial, Weight::One());
571  fst::VectorFst<fst::StdArc> fst_concat;
572  fst::Concat(fst, fst_rhs);
573 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::StdArc StdArc
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Label Label
fst::StdArc::Weight Weight

◆ MonophoneContextDependency()

ContextDependency * MonophoneContextDependency ( const std::vector< int32 > &  phones,
const std::vector< int32 > &  phone2num_pdf_classes 
)

Definition at line 331 of file context-dep.cc.

References ContextDependency::ContextDependency(), GetStubMap(), and rnnlm::i.

Referenced by main(), TestConvertAlignment(), and TestMonophoneContextDependency().

332  {
333  std::vector<std::vector<int32> > phone_sets(phones.size());
334  for (size_t i = 0; i < phones.size(); i++) phone_sets[i].push_back(phones[i]);
335  std::vector<bool> share_roots(phones.size(), false); // don't share roots.
336  // N is context size, P = position of central phone (must be 0).
337  int32 num_leaves = 0, P = 0, N = 1;
338  EventMap *pdf_map = GetStubMap(P, phone_sets, phone2num_pdf_classes, share_roots, &num_leaves);
339  return new ContextDependency(N, P, pdf_map);
340 }
kaldi::int32 int32
EventMap * GetStubMap(int32 P, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, int32 *num_leaves_out)
GetStubMap is used in tree-building functions to get the initial to-states map, before the decision-t...

◆ MonophoneContextDependencyShared()

ContextDependency * MonophoneContextDependencyShared ( const std::vector< std::vector< int32 > > &  phone_sets,
const std::vector< int32 > &  phone2num_pdf_classes 
)

Definition at line 343 of file context-dep.cc.

References ContextDependency::ContextDependency(), and GetStubMap().

Referenced by main().

344  {
345  std::vector<bool> share_roots(phone_sets.size(), false); // don't share roots.
346  // N is context size, P = position of central phone (must be 0).
347  int32 num_leaves = 0, P = 0, N = 1;
348  EventMap *pdf_map = GetStubMap(P, phone_sets, phone2num_pdf_classes, share_roots, &num_leaves);
349  return new ContextDependency(N, P, pdf_map);
350 }
kaldi::int32 int32
EventMap * GetStubMap(int32 P, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, int32 *num_leaves_out)
GetStubMap is used in tree-building functions to get the initial to-states map, before the decision-t...

◆ mul_elements() [1/2]

void kaldi::mul_elements ( const MatrixIndexT  dim,
const double *  a,
double *  b 
)
inline

This is not really a wrapper for CBLAS as CBLAS does not have this; in future we could extend this somehow.

Definition at line 341 of file cblas-wrappers.h.

References rnnlm::i.

Referenced by MatrixBase< float >::MulElements().

344  { // does b *= a, elementwise.
345  double c1, c2, c3, c4;
346  MatrixIndexT i;
347  for (i = 0; i + 4 <= dim; i += 4) {
348  c1 = a[i] * b[i];
349  c2 = a[i+1] * b[i+1];
350  c3 = a[i+2] * b[i+2];
351  c4 = a[i+3] * b[i+3];
352  b[i] = c1;
353  b[i+1] = c2;
354  b[i+2] = c3;
355  b[i+3] = c4;
356  }
357  for (; i < dim; i++)
358  b[i] *= a[i];
359 }
int32 MatrixIndexT
Definition: matrix-common.h:98

◆ mul_elements() [2/2]

void kaldi::mul_elements ( const MatrixIndexT  dim,
const float a,
float b 
)
inline

Definition at line 361 of file cblas-wrappers.h.

References rnnlm::i.

364  { // does b *= a, elementwise.
365  float c1, c2, c3, c4;
366  MatrixIndexT i;
367  for (i = 0; i + 4 <= dim; i += 4) {
368  c1 = a[i] * b[i];
369  c2 = a[i+1] * b[i+1];
370  c3 = a[i+2] * b[i+2];
371  c4 = a[i+3] * b[i+3];
372  b[i] = c1;
373  b[i+1] = c2;
374  b[i+2] = c3;
375  b[i+3] = c4;
376  }
377  for (; i < dim; i++)
378  b[i] *= a[i];
379 }
int32 MatrixIndexT
Definition: matrix-common.h:98

◆ MustBeQuoted()

static bool kaldi::MustBeQuoted ( const std::string &  str,
ShellType  st 
)
static

Definition at line 224 of file parse-options.cc.

References rnnlm::d, KALDI_ASSERT, and kBash.

Referenced by ParseOptions::Escape().

224  {
225  // Only Bash is supported (for the moment).
226  KALDI_ASSERT(st == kBash && "Invalid shell type.");
227 
228  const char *c = str.c_str();
229  if (*c == '\0') {
230  return true; // Must quote empty string
231  } else {
232  const char *ok_chars[2];
233 
234  // These seem not to be interpreted as long as there are no other "bad"
235  // characters involved (e.g. "," would be interpreted as part of something
236  // like a{b,c}, but not on its own.
237  ok_chars[kBash] = "[]~#^_-+=:.,/";
238 
239  // Just want to make sure that a space character doesn't get automatically
240  // inserted here via an automated style-checking script, like it did before.
241  KALDI_ASSERT(!strchr(ok_chars[kBash], ' '));
242 
243  for (; *c != '\0'; c++) {
244  // For non-alphanumeric characters we have a list of characters which
245  // are OK. All others are forbidden (this is easier since the shell
246  // interprets most non-alphanumeric characters).
247  if (!isalnum(*c)) {
248  const char *d;
249  for (d = ok_chars[st]; *d != '\0'; d++) if (*c == *d) break;
250  // If not alphanumeric or one of the "ok_chars", it must be escaped.
251  if (*d == '\0') return true;
252  }
253  }
254  return false; // The string was OK. No quoting or escaping.
255  }
256 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ MyFunction1()

void kaldi::MyFunction1 ( )

Definition at line 27 of file kaldi-error-test.cc.

References MyFunction2().

Referenced by UnitTestError().

27 { MyFunction2(); }
void MyFunction2()

◆ MyFunction2()

void kaldi::MyFunction2 ( )

Definition at line 25 of file kaldi-error-test.cc.

References KALDI_ERR.

Referenced by MyFunction1().

25 { KALDI_ERR << "Ignore this error"; }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ NameOf()

std::string NameOf ( )

Definition at line 30 of file matrix-lib-speed-test.cc.

30  {
31  return (sizeof(Real) == 8 ? "<double>" : "<float>");
32 }

◆ NccfToPov()

BaseFloat kaldi::NccfToPov ( BaseFloat  n)

This function processes the NCCF n to a reasonably accurate probability of voicing p by applying the formula:

n' = fabs(n) r = -5.2 + 5.4 * exp(7.5 * (n' - 1.0)) + 4.8 * n' - 2.0 * exp(-10.0 * n') + 4.2 * exp(20.0 * (n' - 1.0)); p = 1.0 / (1 + exp(-1.0 * r));

How did we get this formula? We plotted the empirical log-prob-ratio of voicing r = log( p[voiced] / p[not-voiced] ) [on the Keele database where voicing is marked], as a function of the NCCF at the delay picked by our algorithm. This was done on intervals of the NCCF, so we had enough statistics to get that ratio. The NCCF covers [-1, 1]; almost all of the probability mass is on [0, 1] but the empirical POV seems fairly symmetric with a minimum near zero, so we chose to make it a function of n' = fabs(n).

Then we manually tuned a function (the one you see above) that approximated the log-prob-ratio of voicing fairly well as a function of the absolute-value NCCF n'; however, wasn't a very exact match since we were also trying to make the transformed NCCF fairly Gaussian distributed, with a view to using it as a feature– an idea we later abandoned after a simpler formula worked better.

Definition at line 78 of file pitch-functions.cc.

References Exp(), and KALDI_ASSERT.

Referenced by OnlineProcessPitch::UpdateNormalizationStats().

78  {
79  BaseFloat ndash = fabs(n);
80  if (ndash > 1.0) ndash = 1.0; // just in case it was slightly outside [-1, 1]
81 
82  BaseFloat r = -5.2 + 5.4 * Exp(7.5 * (ndash - 1.0)) + 4.8 * ndash -
83  2.0 * Exp(-10.0 * ndash) + 4.2 * Exp(20.0 * (ndash - 1.0));
84  // r is the approximate log-prob-ratio of voicing, log(p/(1-p)).
85  BaseFloat p = 1.0 / (1 + Exp(-1.0 * r));
86  KALDI_ASSERT(p - p == 0); // Check for NaN/inf
87  return p;
88 }
double Exp(double x)
Definition: kaldi-math.h:83
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ NccfToPovFeature()

BaseFloat kaldi::NccfToPovFeature ( BaseFloat  n)

This function processes the NCCF n to a POV feature f by applying the formula f = (1.0001 - n)^0.15 - 1.0 This is a nonlinear function designed to make the output reasonably Gaussian distributed.

Before doing this, the NCCF distribution is in the range [-1, 1] but has a strong peak just before 1.0, which this function smooths out.

Definition at line 44 of file pitch-functions.cc.

References KALDI_ASSERT.

Referenced by OnlineProcessPitch::GetPovFeature().

44  {
45  if (n > 1.0) {
46  n = 1.0;
47  } else if (n < -1.0) {
48  n = -1.0;
49  }
50  BaseFloat f = pow((1.0001 - n), 0.15) - 1.0;
51  KALDI_ASSERT(f - f == 0); // check for NaN,inf.
52  return f;
53 }
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ NewCuCompressedMatrix()

CuCompressedMatrixBase * NewCuCompressedMatrix ( CuCompressedMatrixType  t,
BaseFloat  range,
bool  truncate = true 
)

This function allocates a new CuCompressedMatrix with type determined by t, and with the 'range' and 'truncate' parameters provided to the constructor of class CuCompressedMatrix.

It will crash at runtime if called when CUDA is not compiled in, or not enabled.

Definition at line 119 of file cu-compressed-matrix.cc.

References KALDI_ASSERT, KALDI_ERR, kCompressedMatrixInt16, kCompressedMatrixInt8, kCompressedMatrixUint16, and kCompressedMatrixUint8.

Referenced by CuCompressedMatrixTestNonnegative(), CuCompressedMatrixTestSign(), CuCompressedMatrixTestSymmetric(), and NnetComputer::ExecuteCommand().

121  {
122  if (t == kCompressedMatrixUint8) {
123  KALDI_ASSERT(range >= 0);
124  return new CuCompressedMatrix<uint8>(range);
125  } else if (t == kCompressedMatrixInt8) {
126  KALDI_ASSERT(range >= 0);
127  return new CuCompressedMatrix<int8>(range);
128  } else if (t == kCompressedMatrixUint16) {
129  KALDI_ASSERT(range > 0);
130  return new CuCompressedMatrix<uint16>(range);
131  } else if (t == kCompressedMatrixInt16) {
132  KALDI_ASSERT(range > 0);
133  return new CuCompressedMatrix<int16>(range);
134  } else {
135  KALDI_ERR << "Unknown compressed-matrix type";
136  return NULL;
137  }
138 }
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ NonDiagonalness()

static Real kaldi::NonDiagonalness ( const SpMatrix< Real > &  S)
static

Definition at line 1550 of file matrix-lib-test.cc.

References rnnlm::i, rnnlm::j, and PackedMatrix< Real >::NumRows().

Referenced by UnitTestPca2().

1550  {
1551  Real max_diag = 0.0, max_offdiag = 0.0;
1552  for (MatrixIndexT i = 0; i < S.NumRows(); i++)
1553  for (MatrixIndexT j = 0; j <= i; j++) {
1554  if (i == j) { max_diag = std::max(max_diag, std::abs(S(i, j))); }
1555  else { max_offdiag = std::max(max_offdiag, std::abs(S(i, j))); }
1556  }
1557  if (max_diag == 0.0) {
1558  if (max_offdiag == 0.0) return 0.0; // perfectly diagonal.
1559  else return 1.0; // perfectly non-diagonal.
1560  } else {
1561  return max_offdiag / max_diag;
1562  }
1563 }
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98

◆ NonOrthogonality()

static Real kaldi::NonOrthogonality ( const MatrixBase< Real > &  M,
MatrixTransposeType  transM 
)
static

Definition at line 1538 of file matrix-lib-test.cc.

References rnnlm::i, rnnlm::j, kTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and PackedMatrix< Real >::SetUnit().

Referenced by UnitTestPca2().

1538  {
1539  SpMatrix<Real> S(transM == kTrans ? M.NumCols() : M.NumRows());
1540  S.SetUnit();
1541  S.AddMat2(-1.0, M, transM, 1.0);
1542  Real max = 0.0;
1543  for (MatrixIndexT i = 0; i < S.NumRows(); i++)
1544  for (MatrixIndexT j = 0; j <= i; j++)
1545  max = std::max(max, std::abs(S(i, j)));
1546  return max;
1547 }
Packed symetric matrix class.
Definition: matrix-common.h:62
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
void SetUnit()
< Set to zero
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ NonUnitness()

static Real kaldi::NonUnitness ( const SpMatrix< Real > &  S)
static

Definition at line 1567 of file matrix-lib-test.cc.

References rnnlm::i, rnnlm::j, PackedMatrix< Real >::NumRows(), and PackedMatrix< Real >::SetUnit().

Referenced by UnitTestPca(), UnitTestTopEigs(), UnitTestTridiagonalize(), and UnitTestTridiagonalizeAndQr().

1567  {
1568  SpMatrix<Real> tmp(S.NumRows());
1569  tmp.SetUnit();
1570  tmp.AddSp(-1.0, S);
1571  Real max = 0.0;
1572  for (MatrixIndexT i = 0; i < tmp.NumRows(); i++)
1573  for (MatrixIndexT j = 0; j <= i; j++)
1574  max = std::max(max, std::abs(tmp(i, j)));
1575  return max;
1576 }
Packed symetric matrix class.
Definition: matrix-common.h:62
void SetUnit()
< Set to zero
MatrixIndexT NumRows() const
int32 MatrixIndexT
Definition: matrix-common.h:98

◆ ObtainSetsOfPhones()

static void kaldi::ObtainSetsOfPhones ( const std::vector< std::vector< int32 > > &  phone_sets,
const std::vector< int32 > &  assignments,
const std::vector< int32 > &  clust_assignments,
int32  num_leaves,
std::vector< std::vector< int32 > > *  sets_out 
)
static

ObtainSetsOfPhones is called by AutomaticallyObtainQuestions.

It processes the output of ClusterTopDown to obtain the sets of phones corresponding to both the leaf-level clusters and all the non-leaf-level clusters.

Definition at line 557 of file build-tree.cc.

References rnnlm::i, IsSortedAndUniq(), rnnlm::j, KALDI_ASSERT, and RemoveDuplicates().

Referenced by AutomaticallyObtainQuestions().

562  {
563  KALDI_ASSERT(sets_out != NULL);
564  sets_out->clear();
565  std::vector<std::vector<int32> > raw_sets(clust_assignments.size());
566 
567  KALDI_ASSERT(num_leaves < static_cast<int32>(clust_assignments.size()));
568  KALDI_ASSERT(assignments.size() == phone_sets.size());
569  for (size_t i = 0; i < assignments.size(); i++) {
570  int32 clust = assignments[i]; // this is an index into phone_sets.
571  KALDI_ASSERT(clust>=0 && clust < num_leaves);
572  for (size_t j = 0; j < phone_sets[i].size(); j++) {
573  // and not just a hole.
574  raw_sets[clust].push_back(phone_sets[i][j]);
575  }
576  }
577  // for all clusters including the top-level cluster:
578  // [note that the top-level cluster contains all phones, but it may actually
579  // be useful because sometimes we cluster just the non-silence phones, so
580  // the list of all phones is a way of asking about silence in such a way
581  // that epsilon (end-or-begin-of-utterance) gets lumped with silence.
582  for (int32 j = 0; j < static_cast<int32>(clust_assignments.size()); j++) {
583  int32 parent = clust_assignments[j];
584  std::sort(raw_sets[j].begin(), raw_sets[j].end());
585  KALDI_ASSERT(IsSortedAndUniq(raw_sets[j])); // should be no dups.
586  if (parent < static_cast<int32>(clust_assignments.size())-1) { // parent is not out of range [i.e. not the top one]...
587  // add all j's phones to its parent.
588  raw_sets[parent].insert(raw_sets[parent].end(),
589  raw_sets[j].begin(),
590  raw_sets[j].end());
591  }
592  }
593  // Reverse the 'raw_sets' so the most important things (top-level questions)
594  // appear at the front... this will end up mattering because of the
595  // --truncate-leftmost-questions option to compile-questions.
596  std::reverse(raw_sets.begin(), raw_sets.end());
597 
598  // Now add the original sets-of-phones to the raw sets, to make sure all of
599  // these are present. (The main reason they might be absent is if the stats
600  // are empty, but we want to ensure they are all there regardless). note these
601  // will be actual singleton sets if the sets-of-phones each contain just one
602  // phone, which in some sense is the normal situation.
603  for (size_t i = 0; i < phone_sets.size(); i++) {
604  raw_sets.push_back(phone_sets[i]);
605  }
606  // Remove duplicate sets from "raw_sets".
607  RemoveDuplicates(&raw_sets);
608  sets_out->reserve(raw_sets.size());
609  for (size_t i = 0; i < raw_sets.size(); i++)
610  if (! raw_sets[i].empty()) // if the empty set is present, remove it...
611  sets_out->push_back(raw_sets[i]);
612 }
static void RemoveDuplicates(std::vector< std::vector< int32 > > *vecs)
Definition: build-tree.cc:533
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ OnlineSilenceWeighting::ComputeCurrentTraceback< fst::Fst< fst::StdArc > >() [1/2]

template void kaldi::OnlineSilenceWeighting::ComputeCurrentTraceback< fst::Fst< fst::StdArc > > ( const LatticeFasterOnlineDecoderTpl< fst::Fst< fst::StdArc > > &  decoder)

◆ OnlineSilenceWeighting::ComputeCurrentTraceback< fst::Fst< fst::StdArc > >() [2/2]

◆ OnlineSilenceWeighting::ComputeCurrentTraceback< fst::GrammarFst >() [1/2]

◆ OnlineSilenceWeighting::ComputeCurrentTraceback< fst::GrammarFst >() [2/2]

◆ operator<<() [1/15]

std::ostream & operator<< ( std::ostream &  out,
const CuBlockMatrix< Real > &  mat 
)

Print the matrix to stream.

Definition at line 318 of file cu-block-matrix.cc.

318  {
319  bool binary = false;
320  mat.Write(out, binary);
321  return out;
322 }

◆ operator<<() [2/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuBlockMatrix< float > &  mat 
)

◆ operator<<() [3/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuBlockMatrix< double > &  mat 
)

◆ operator<<() [4/15]

std::ostream & operator<< ( std::ostream &  out,
const CuArray< T > &  vec 
)

Print the vector to stream.

I/O.

Definition at line 329 of file cu-array-inl.h.

References rnnlm::i.

329  {
330  std::vector<T> tmp;
331  vec.CopyToVec(&tmp);
332  out << "[";
333  for(int32 i=0; i<tmp.size(); i++) {
334  out << " " << tmp[i];
335  }
336  out << " ]\n";
337  return out;
338 }
kaldi::int32 int32

◆ operator<<() [5/15]

std::ostream & operator<< ( std::ostream &  out,
const CuPackedMatrix< Real > &  mat 
)

Print the matrix to stream.

I/O.

Definition at line 386 of file cu-packed-matrix.cc.

386  {
387  PackedMatrix<Real> temp(mat.NumRows());
388  mat.CopyToPacked(&temp);
389  out << temp;
390  return out;
391 }

◆ operator<<() [6/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuPackedMatrix< float > &  mat 
)

◆ operator<<() [7/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuPackedMatrix< double > &  mat 
)

◆ operator<<() [8/15]

std::ostream & operator<< ( std::ostream &  os,
const kaldi::DiagGmm gmm 
)

ostream operator that calls DiagGMM::Write()

Definition at line 722 of file diag-gmm.cc.

References DiagGmm::Write().

723  {
724  gmm.Write(os, false);
725  return os;
726 }
void Write(std::ostream &os, bool binary) const
Definition: diag-gmm.cc:705

◆ operator<<() [9/15]

std::ostream & operator<< ( std::ostream &  out_stream,
const kaldi::FullGmm gmm 
)

ostream operator that calls FullGmm::Write()

Definition at line 777 of file full-gmm.cc.

References FullGmm::Write().

778  {
779  gmm.Write(out_stream, false);
780  return out_stream;
781 }
void Write(std::ostream &os, bool binary) const
Definition: full-gmm.cc:758

◆ operator<<() [10/15]

std::ostream & operator<< ( std::ostream &  out,
const CuVectorBase< Real > &  vec 
)

Print the vector to stream.

I/O.

Definition at line 1119 of file cu-vector.cc.

1119  {
1120  Vector<Real> temp(vec.Dim());
1121  vec.CopyToVec(&temp);
1122  out << temp;
1123  return out;
1124 }

◆ operator<<() [11/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuVectorBase< float > &  vec 
)

◆ operator<<() [12/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuVectorBase< double > &  vec 
)

◆ operator<<() [13/15]

std::ostream & operator<< ( std::ostream &  out,
const CuMatrixBase< Real > &  mat 
)

Print the matrix to stream.

I/O.

Definition at line 3464 of file cu-matrix.cc.

References CuMatrixBase< Real >::CopyToMat(), CuMatrixBase< Real >::NumCols(), and CuMatrixBase< Real >::NumRows().

3464  {
3465  Matrix<Real> temp(mat.NumRows(), mat.NumCols());
3466  mat.CopyToMat(&temp);
3467  out << temp;
3468  return out;
3469 }

◆ operator<<() [14/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuMatrixBase< float > &  mat 
)

◆ operator<<() [15/15]

template std::ostream& kaldi::operator<< ( std::ostream &  out,
const CuMatrixBase< double > &  mat 
)

◆ operator>()

bool kaldi::operator> ( const CompBotClustElem a,
const CompBotClustElem b 
)

Definition at line 438 of file cluster-utils.cc.

References CompBotClustElem::dist.

438  {
439  return a.dist > b.dist;
440 }

◆ operator>>() [1/2]

std::istream & operator>> ( std::istream &  is,
kaldi::DiagGmm gmm 
)

istream operator that calls DiagGMM::Read()

Definition at line 758 of file diag-gmm.cc.

References DiagGmm::Read().

758  {
759  gmm.Read(is, false); // false == non-binary.
760  return is;
761 }
void Read(std::istream &in, bool binary)
Definition: diag-gmm.cc:728

◆ operator>>() [2/2]

std::istream & operator>> ( std::istream &  in_stream,
kaldi::FullGmm gmm 
)

istream operator that calls FullGmm::Read()

Definition at line 848 of file full-gmm.cc.

References FullGmm::Read().

848  {
849  gmm.Read(in_stream, false); // false == non-binary.
850  return in_stream;
851 }
void Read(std::istream &is, bool binary)
Definition: full-gmm.cc:813

◆ OptimizeFactorTransducer()

void OptimizeFactorTransducer ( KwsLexicographicFst index_transducer,
int32  max_states,
bool  allow_partial 
)

Definition at line 116 of file kws-functions2.cc.

References fst::DeterminizeStar(), KALDI_VLOG, and KALDI_WARN.

Referenced by main().

118  {
119  using namespace fst;
120  KwsLexicographicFst ifst = *index_transducer;
121  EncodeMapper<KwsLexicographicArc> encoder(kEncodeLabels, ENCODE);
122  Encode(&ifst, &encoder);
123  KALDI_VLOG(2) << "OptimizeFactorTransducer: determinization...";
124  if (allow_partial) {
125  DeterminizeStar(ifst, index_transducer, kDelta, NULL, max_states, true);
126  } else {
127  try {
128  DeterminizeStar(ifst, index_transducer, kDelta, NULL, max_states,
129  false);
130  } catch(const std::exception &e) {
131  KALDI_WARN << e.what();
132  *index_transducer = ifst;
133  }
134  }
135  KALDI_VLOG(2) << "OptimizeFactorTransducer: minimization...";
136  Minimize(index_transducer, static_cast<KwsLexicographicFst *>(NULL), fst::kDelta, true);
137  Decode(index_transducer, encoder);
138 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::VectorFst< KwsLexicographicArc > KwsLexicographicFst
Definition: kaldi-kws.h:46
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
bool DeterminizeStar(F &ifst, MutableFst< typename F::Arc > *ofst, float delta, bool *debug_ptr, int max_states, bool allow_partial)
This function implements the normal version of DeterminizeStar, in which the output strings are repre...

◆ PaCallback()

int PaCallback ( const void *  input,
void *  output,
long unsigned  frame_count,
const PaStreamCallbackTimeInfo *  time_info,
PaStreamCallbackFlags  status_flags,
void *  user_data 
)

Definition at line 39 of file online-audio-source.cc.

References OnlinePaSource::Callback().

43  {
44  OnlinePaSource *pa_src = reinterpret_cast<OnlinePaSource*>(user_data);
45  return pa_src->Callback(input, output, frame_count, time_info, status_flags);
46 }

◆ ParseConfigLines()

void ParseConfigLines ( const std::vector< std::string > &  lines,
std::vector< ConfigLine > *  config_lines 
)

This function converts config-lines from a simple sequence of strings as output by ReadConfigLines(), into a sequence of first-tokens and name-value pairs.

The general format is: "command-type bar=baz xx=yyy" etc., although there are subtleties as to what exactly is allowed, see documentation for class ConfigLine for details. This function will die if there was a parsing failure.

Definition at line 579 of file text-utils.cc.

References rnnlm::i, and KALDI_ERR.

580  {
581  config_lines->resize(lines.size());
582  for (size_t i = 0; i < lines.size(); i++) {
583  bool ret = (*config_lines)[i].ParseLine(lines[i]);
584  if (!ret) {
585  KALDI_ERR << "Error parsing config line: " << lines[i];
586  }
587  }
588 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ ParseMatrixRangeSpecifier()

bool kaldi::ParseMatrixRangeSpecifier ( const std::string &  range,
const int  rows,
const int  cols,
std::vector< int32 > *  row_range,
std::vector< int32 > *  col_range 
)

Definition at line 33 of file kaldi-holder.cc.

References KALDI_ERR, KALDI_WARN, SplitStringToIntegers(), and SplitStringToVector().

Referenced by ExtractObjectRange().

36  {
37  if (range.empty()) {
38  KALDI_ERR << "Empty range specifier.";
39  return false;
40  }
41  std::vector<std::string> splits;
42  SplitStringToVector(range, ",", false, &splits);
43  if (!((splits.size() == 1 && !splits[0].empty()) ||
44  (splits.size() == 2 && !splits[0].empty() && !splits[1].empty()))) {
45  KALDI_ERR << "Invalid range specifier for matrix: " << range;
46  return false;
47  }
48 
49  bool status = true;
50 
51  if (splits[0] != ":")
52  status = SplitStringToIntegers(splits[0], ":", false, row_range);
53 
54  if (splits.size() == 2 && splits[1] != ":") {
55  status = status && SplitStringToIntegers(splits[1], ":", false, col_range);
56  }
57  if (row_range->size() == 0) {
58  row_range->push_back(0);
59  row_range->push_back(rows - 1);
60  }
61  if (col_range->size() == 0) {
62  col_range->push_back(0);
63  col_range->push_back(cols - 1);
64  }
65 
66  // Length tolerance of 3 -- 2 to account for edge effects when
67  // frame-length is 25ms and frame-shift is 10ms, and 1 for rounding effects
68  // since segments are usually retained up to 2 decimal places.
69  int32 length_tolerance = 3;
70  if (!(status && row_range->size() == 2 && col_range->size() == 2 &&
71  row_range->at(0) >= 0 && row_range->at(0) <= row_range->at(1) &&
72  row_range->at(1) < rows + length_tolerance &&
73  col_range->at(0) >=0 &&
74  col_range->at(0) <= col_range->at(1) && col_range->at(1) < cols)) {
75  KALDI_ERR << "Invalid range specifier: " << range
76  << " for matrix of size " << rows
77  << "x" << cols;
78  return false;
79  }
80 
81  if (row_range->at(1) >= rows)
82  KALDI_WARN << "Row range " << row_range->at(0) << ":" << row_range->at(1)
83  << " goes beyond the number of rows of the "
84  << "matrix " << rows;
85  return status;
86 }
bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
Split a string (e.g.
Definition: text-utils.h:68
kaldi::int32 int32
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ PhoneAlignLattice()

bool PhoneAlignLattice ( const CompactLattice lat,
const TransitionModel tmodel,
const PhoneAlignLatticeOptions opts,
CompactLattice lat_out 
)

Outputs a lattice in which the arcs correspond exactly to sequences of phones, so the boundaries between the arcs correspond to the boundaries between phones If remove-epsilon == false and replace-output-symbols == false, but an arc may have >1 phone on it, but the boundaries will still correspond with the boundaries between phones.

Note: it's possible to have arcs with words on them but no transition-ids at all. Returns true if everything was OK, false if some kind of error was detected (e.g. the "reorder" option was incorrectly specified.)

Definition at line 413 of file phone-align-lattice.cc.

References LatticePhoneAligner::AlignLattice().

Referenced by main(), PhoneAlignLatticeOptions::Register(), and WordAlignLatticeLexicon().

416  {
417  LatticePhoneAligner aligner(lat, tmodel, opts, lat_out);
418  return aligner.AlignLattice();
419 }

◆ PlaceNansInGaps()

void kaldi::PlaceNansInGaps ( Matrix< Real > *  mat)

Definition at line 1858 of file matrix-lib-test.cc.

References rnnlm::j, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), RandGauss(), RandInt(), MatrixBase< Real >::RowData(), and MatrixBase< Real >::Stride().

Referenced by UnitTestAddMatMatNans(), and UnitTestResizeCopyDataDifferentStrideType().

1858  {
1859  int32 num_rows = mat->NumRows(), num_cols = mat->NumCols(),
1860  stride = mat->Stride();
1861  BaseFloat not_a_number = nan(" "); // nan is from <cmath>
1862  for (int32 r = 0; r + 1 < num_rows; r++) {
1863  for (int32 j = num_cols; j < stride; j++) {
1864  if (RandInt(0, 1) == 0)
1865  (mat->RowData(r))[j] = not_a_number;
1866  else
1867  (mat->RowData(r))[j] = RandGauss() * 1.5e+31;
1868  }
1869  }
1870 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
Real * RowData(MatrixIndexT i)
Returns pointer to data for one row (non-const)
Definition: kaldi-matrix.h:87
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
MatrixIndexT Stride() const
Stride (distance in memory between each row). Will be >= NumCols.
Definition: kaldi-matrix.h:70
float BaseFloat
Definition: kaldi-types.h:29
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ PosteriorToMatrix< double >()

template void kaldi::PosteriorToMatrix< double > ( const Posterior post,
const int32  post_dim,
Matrix< double > *  mat 
)

Referenced by PosteriorToMatrix().

◆ PosteriorToMatrix< float >()

template void kaldi::PosteriorToMatrix< float > ( const Posterior post,
const int32  post_dim,
Matrix< float > *  mat 
)

Referenced by PosteriorToMatrix().

◆ PosteriorToPdfMatrix< double >()

template void kaldi::PosteriorToPdfMatrix< double > ( const Posterior post,
const TransitionModel model,
Matrix< double > *  mat 
)

Referenced by PosteriorToPdfMatrix().

◆ PosteriorToPdfMatrix< float >()

template void kaldi::PosteriorToPdfMatrix< float > ( const Posterior post,
const TransitionModel model,
Matrix< float > *  mat 
)

Referenced by PosteriorToPdfMatrix().

◆ prefixp()

static bool kaldi::prefixp ( const std::string &  pfx,
const std::string &  str 
)
static

Definition at line 45 of file kaldi-cygwin-io-inl.h.

References cygprefix().

Referenced by MapCygwinPath(), and MapCygwinPathNoTmp().

45  {
46  return pfx.length() <= str.length() &&
47  std::equal(pfx.begin(), pfx.end(), str.begin());
48 }

◆ PrepareMap() [1/2]

void kaldi::PrepareMap ( const std::string &  map_rxfilename,
int32  num_classes,
unordered_map< int32, int32 > *  map 
)

PrepareMap creates a map that specifies the mapping between the input and output class labels.

If the string map_rxfilename is empty, then the mapping is the identity map (e.g., 0 maps to 0, 1 maps to 1, etc), based on the number of classes num_classes. If map_rxfilename is not empty, the mapping is created from that file. The file is expected to be two columns of integers with up to num_classes rows. If an input class is not specified in the file, then the output class label is the same as the input. The first column is the input class and the second column is the output class. For example: 0 0 1 1 2 0

Definition at line 42 of file compute-vad-from-frame-likes.cc.

References rnnlm::i, KALDI_ASSERT, KALDI_ERR, SplitStringToVector(), and Input::Stream().

Referenced by main().

43  {
44  Input map_input(map_rxfilename);
45  for (int32 i = 0; i < num_classes; i++)
46  (*map)[i] = i;
47 
48  if (!map_rxfilename.empty()) {
49  std::string line;
50  while (std::getline(map_input.Stream(), line)) {
51  if (line.size() == 0) continue;
52  int32 start = line.find_first_not_of(" \t");
53  int32 end = line.find_first_of('#'); // Ignore trailing comments
54  if (start == std::string::npos || start == end) continue;
55  end = line.find_last_not_of(" \t", end - 1);
56  KALDI_ASSERT(end >= start);
57  std::vector<std::string> fields;
58  SplitStringToVector(line.substr(start, end - start + 1),
59  " \t\n\r", true, &fields);
60  if (fields.size() != 2) {
61  KALDI_ERR << "Bad line. Expected two fields, got: "
62  << line;
63  }
64  (*map)[std::atoi(fields[0].c_str())] = std::atoi(fields[1].c_str());
65  }
66  }
67 
68  if (map->size() > num_classes)
69  KALDI_ERR << "Map table has " << map->size() << " classes. "
70  << "Expected " << num_classes << " or fewer";
71 }
kaldi::int32 int32
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ PrepareMap() [2/2]

void kaldi::PrepareMap ( const std::string  map_rxfilename,
unordered_map< std::pair< int32, int32 >, int32, PairHasher< int32 > > *  map 
)

PrepareMap creates a mapping between the pairs of VAD decisions and the output label.

If map_rxfilename is empty, we create a mapping in which a frame is only classified as speech (represented as "1") if both VAD decisions agree on speech, and nonspeech (represented as "0") otherwise. If map_rxfilename is not empty, then that table provides the mapping. If the first set of VAD decisions has N classes and the second has M classes, then the table needs to have NxM rows, and three columns. The first two columns correspond to the labels in the first and second VAD decisions respectively, and the last column is the resultant output label. For example: 0 0 0 0 1 0 0 2 0 1 0 0 1 1 1 1 2 1

Definition at line 45 of file merge-vads.cc.

References KALDI_ASSERT, KALDI_ERR, SplitStringToVector(), and Input::Stream().

46  {
47  Input map_input(map_rxfilename);
48 
49  // If a map file isn't specified, provide an obvious mapping. The
50  // following mapping assumes "0" corresponds to nonspeech and "1"
51  // corresponds to speech. The combination of two VAD decisions only
52  // results in a decision of speech if both input frames are
53  // classified as speech.
54  if (map_rxfilename.empty()) {
55  (*map)[std::pair<int32, int32>(0, 0)] = 0;
56  (*map)[std::pair<int32, int32>(0, 1)] = 0;
57  (*map)[std::pair<int32, int32>(1, 0)] = 0;
58  (*map)[std::pair<int32, int32>(1, 1)] = 1;
59  } else {
60  std::string line;
61  while (std::getline(map_input.Stream(), line)) {
62  if (line.size() == 0) continue;
63  int32 start = line.find_first_not_of(" \t");
64  int32 end = line.find_first_of('#');
65  if (start == std::string::npos || start == end) continue;
66  end = line.find_last_not_of(" \t", end - 1);
67  KALDI_ASSERT(end >= start);
68  std::vector<std::string> fields;
69  SplitStringToVector(line.substr(start, end - start + 1),
70  " \t\n\r", true, &fields);
71  if (fields.size() != 3) {
72  KALDI_ERR << "Bad line. Expected three fields, got: "
73  << line;
74  }
75  int32 label1 = std::atoi(fields[0].c_str()),
76  label2 = std::atoi(fields[1].c_str()),
77  result_label = std::atoi(fields[2].c_str());
78  (*map)[std::pair<int32, int32>(label1, label2)] = result_label;
79  }
80  }
81 }
kaldi::int32 int32
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ PreparePriors()

void kaldi::PreparePriors ( const std::string &  priors_str,
int32  num_classes,
std::vector< BaseFloat > *  priors 
)

PreparePriors creates a table specifying the priors for each class.

If priors_str is empty, uniform priors are assumed. If priors_str is nonempty, the comma-separated floats are parsed out. If present, the input of priors_str is of the form: 0.5,0.25,0.25

Definition at line 80 of file compute-vad-from-frame-likes.cc.

References rnnlm::i, KALDI_ERR, and SplitStringToFloats().

Referenced by main().

81  {
82  if (priors_str.empty()) {
83  for (int32 i = 0; i < num_classes; i++)
84  priors->push_back(log(1.0/num_classes)); // Uniform priors
85  } else {
86  SplitStringToFloats(priors_str, ",", false, priors);
87  for (int32 i = 0; i < priors->size(); i++)
88  (*priors)[i] = log((*priors)[i]);
89  }
90 
91  if (priors->size() != num_classes)
92  KALDI_ERR << priors->size() << " priors specified. Expected "
93  << num_classes;
94 }
bool SplitStringToFloats(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< F > *out)
Definition: text-utils.cc:30
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ PrintLexicon()

static void kaldi::PrintLexicon ( const std::vector< std::vector< int32 > > &  lexicon)
static

Definition at line 83 of file word-align-lattice-lexicon-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, and KALDI_LOG.

Referenced by TestWordAlignLatticeLexicon().

83  {
84  KALDI_LOG << "Lexicon is: ";
85  for (size_t i = 0; i < lexicon.size(); i++) {
86  KALDI_ASSERT(lexicon[i].size() >= 2);
87  const std::vector<int32> &entry = lexicon[i];
88  std::cerr << entry[0] << "\t" << entry[1] << "\t";
89  for (size_t j = 2; j < entry.size(); j++)
90  std::cerr << entry[j] << " ";
91  std::cerr << "\n";
92  }
93 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ PrintPartialResult()

void PrintPartialResult ( const std::vector< int32 > &  words,
const fst::SymbolTable *  word_syms,
bool  line_break 
)

Definition at line 60 of file onlinebin-util.cc.

References rnnlm::i, KALDI_ASSERT, and KALDI_ERR.

Referenced by main().

62  {
63  KALDI_ASSERT(word_syms != NULL);
64  for (size_t i = 0; i < words.size(); i++) {
65  std::string word = word_syms->Find(words[i]);
66  if (word == "")
67  KALDI_ERR << "Word-id " << words[i] <<" not in symbol table.";
68  std::cout << word << ' ';
69  }
70  if (line_break)
71  std::cout << "\n\n";
72  else
73  std::cout.flush();
74 }
int32 words[kMaxOrder]
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ PrintWordsAndPhones()

static void kaldi::PrintWordsAndPhones ( const std::vector< int32 > &  words,
const std::vector< int32 > &  phones 
)
static

Definition at line 95 of file word-align-lattice-lexicon-test.cc.

References rnnlm::i, and KALDI_LOG.

Referenced by TestWordAlignLatticeLexicon().

96  {
97  std::ostringstream word_str, phone_str;
98  for (size_t i = 0; i < words.size(); i++)
99  word_str << words[i] << " ";
100  for (size_t i = 0; i < phones.size(); i++)
101  phone_str << phones[i] << " ";
102  KALDI_LOG << "Word-sequence is: " << word_str.str();
103  KALDI_LOG << "Phone-sequence is: " << phone_str.str();
104 }
int32 words[kMaxOrder]
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ ProcessPovFeatures()

void kaldi::ProcessPovFeatures ( Matrix< BaseFloat > *  mat)

Definition at line 30 of file process-pitch-feats.cc.

References rnnlm::i, KALDI_ASSERT, Log(), and MatrixBase< Real >::NumRows().

Referenced by main().

30  {
31  int32 num_frames = mat->NumRows();
32  for (int32 i = 0; i < num_frames; i++) {
33  BaseFloat p = (*mat)(i, 0);
34  KALDI_ASSERT(p >= 0.0 && p <= 1.0);
35  (*mat)(i, 0) = Log((p + 0.0001) / (1.0001 - p));
36  }
37 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ProcessTopo()

int32 kaldi::ProcessTopo ( const HmmTopology topo,
const std::vector< std::vector< int32 > > &  questions 
)

Definition at line 27 of file compile-questions.cc.

References HmmTopology::GetPhones(), rnnlm::i, rnnlm::j, KALDI_ERR, KALDI_LOG, KALDI_WARN, HmmTopology::NumPdfClasses(), SortAndUniq(), and WriteIntegerVector().

Referenced by main().

27  {
28  std::vector<int32> seen_phones; // ids of phones seen in questions.
29  for (size_t i = 0; i < questions.size(); i++)
30  for (size_t j= 0; j < questions[i].size(); j++) seen_phones.push_back(questions[i][j]);
31  SortAndUniq(&seen_phones);
32  // topo_phones is also sorted and uniq; a list of phones defined in the topology.
33  const std::vector<int32> &topo_phones = topo.GetPhones();
34  if (seen_phones != topo_phones) {
35  std::ostringstream ss_seen, ss_topo;
36  WriteIntegerVector(ss_seen, false, seen_phones);
37  WriteIntegerVector(ss_topo, false, topo_phones);
38  KALDI_WARN << "ProcessTopo: phones seen in questions differ from those in topology: "
39  << ss_seen.str() << " vs. " << ss_topo.str();
40  if (seen_phones.size() > topo_phones.size()) {
41  KALDI_ERR << "ProcessTopo: phones are asked about that are undefined in the topology.";
42  } // we accept the reverse (not asking about all phones), even though it's very bad.
43  }
44 
45  int32 max_num_pdf_classes = 0;
46  for (size_t i = 0; i < topo_phones.size(); i++) {
47  int32 p = topo_phones[i];
48  int32 num_pdf_classes = topo.NumPdfClasses(p);
49  max_num_pdf_classes = std::max(num_pdf_classes, max_num_pdf_classes);
50  }
51  KALDI_LOG << "Max # pdf classes is " << max_num_pdf_classes;
52  return max_num_pdf_classes;
53 }
kaldi::int32 int32
void SortAndUniq(std::vector< T > *vec)
Sorts and uniq&#39;s (removes duplicates) from a vector.
Definition: stl-utils.h:39
int32 NumPdfClasses(int32 phone) const
Returns the number of pdf-classes for this phone; throws exception if phone not covered by this topol...
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
const std::vector< int32 > & GetPhones() const
Returns a reference to a sorted, unique list of phones covered by the topology (these phones will be ...
Definition: hmm-topology.h:163
void WriteIntegerVector(std::ostream &os, bool binary, const std::vector< T > &v)
Function for writing STL vectors of integer types.
Definition: io-funcs-inl.h:198
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ ProcessUtterance() [1/2]

bool kaldi::ProcessUtterance ( LatticeFasterDecoder decoder,
const AmSgmm2 am_sgmm,
const TransitionModel trans_model,
double  log_prune,
double  acoustic_scale,
const Matrix< BaseFloat > &  features,
RandomAccessInt32VectorVectorReader gselect_reader,
RandomAccessBaseFloatVectorReaderMapped spkvecs_reader,
const fst::SymbolTable *  word_syms,
const std::string &  utt,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignments_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
double *  like_ptr 
)

Definition at line 38 of file sgmm2-latgen-faster.cc.

References AmSgmm2::ComputePerSpkDerivedVars(), DecodeUtteranceLatticeFaster(), RandomAccessTableReader< Holder >::HasKey(), RandomAccessTableReaderMapped< Holder >::HasKey(), RandomAccessTableReaderMapped< Holder >::IsOpen(), KALDI_WARN, MatrixBase< Real >::NumRows(), Sgmm2PerSpkDerivedVars::SetSpeakerVector(), RandomAccessTableReader< Holder >::Value(), and RandomAccessTableReaderMapped< Holder >::Value().

54  { // puts utterance's like in like_ptr on success.
55  using fst::Fst;
56 
57  Sgmm2PerSpkDerivedVars spk_vars;
58  if (spkvecs_reader.IsOpen()) {
59  if (spkvecs_reader.HasKey(utt)) {
60  spk_vars.SetSpeakerVector(spkvecs_reader.Value(utt));
61  am_sgmm.ComputePerSpkDerivedVars(&spk_vars);
62  } else {
63  KALDI_WARN << "Cannot find speaker vector for " << utt << ", not decoding this utterance";
64  return false; // We could use zero, but probably the user would want to know about this
65  // (this would normally be a script error or some kind of failure).
66  }
67  }
68  if (!gselect_reader.HasKey(utt) ||
69  gselect_reader.Value(utt).size() != features.NumRows()) {
70  KALDI_WARN << "No Gaussian-selection info available for utterance "
71  << utt << " (or wrong size)";
72  }
73 
74  const std::vector<std::vector<int32> > &gselect =
75  gselect_reader.Value(utt);
76 
77  DecodableAmSgmm2Scaled sgmm_decodable(am_sgmm, trans_model, features, gselect,
78  log_prune, acoustic_scale, &spk_vars);
79 
81  decoder, sgmm_decodable, trans_model, word_syms, utt, acoustic_scale,
82  determinize, allow_partial, alignments_writer, words_writer,
83  compact_lattice_writer, lattice_writer, like_ptr);
84 }
bool DecodeUtteranceLatticeFaster(LatticeFasterDecoderTpl< FST > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
This function DecodeUtteranceLatticeFaster is used in several decoders, and we have moved it here...
void ComputePerSpkDerivedVars(Sgmm2PerSpkDerivedVars *vars) const
Computes the per-speaker derived vars; assumes vars->v_s is already set up.
Definition: am-sgmm2.cc:1369
const T & Value(const std::string &key)
#define KALDI_WARN
Definition: kaldi-error.h:150
bool HasKey(const std::string &key)
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
const T & Value(const std::string &key)
void SetSpeakerVector(const Vector< BaseFloat > &v_s_in)
Definition: am-sgmm2.h:180

◆ ProcessUtterance() [2/2]

void kaldi::ProcessUtterance ( const AmSgmm2 am_sgmm,
const TransitionModel trans_model,
double  log_prune,
double  acoustic_scale,
const Matrix< BaseFloat > &  features,
RandomAccessInt32VectorVectorReader gselect_reader,
RandomAccessBaseFloatVectorReaderMapped spkvecs_reader,
const fst::SymbolTable *  word_syms,
const std::string &  utt,
bool  determinize,
bool  allow_partial,
Int32VectorWriter alignments_writer,
Int32VectorWriter words_writer,
CompactLatticeWriter compact_lattice_writer,
LatticeWriter lattice_writer,
LatticeFasterDecoder decoder,
double *  like_sum,
int64 *  frame_sum,
int32 num_done,
int32 num_err,
TaskSequencer< DecodeUtteranceLatticeFasterClass > *  sequencer 
)

Definition at line 39 of file sgmm2-latgen-faster-parallel.cc.

References AmSgmm2::ComputePerSpkDerivedVars(), RandomAccessTableReader< Holder >::HasKey(), RandomAccessTableReaderMapped< Holder >::HasKey(), RandomAccessTableReaderMapped< Holder >::IsOpen(), KALDI_WARN, MatrixBase< Real >::NumRows(), TaskSequencer< C >::Run(), Sgmm2PerSpkDerivedVars::SetSpeakerVector(), RandomAccessTableReader< Holder >::Value(), and RandomAccessTableReaderMapped< Holder >::Value().

Referenced by main().

59  {
60  using fst::Fst;
61  using std::vector;
62 
63  Sgmm2PerSpkDerivedVars *spk_vars = new Sgmm2PerSpkDerivedVars; // decodable
64  // will take ownership.
65  if (spkvecs_reader.IsOpen()) {
66  if (spkvecs_reader.HasKey(utt)) {
67  spk_vars->SetSpeakerVector(spkvecs_reader.Value(utt));
68  am_sgmm.ComputePerSpkDerivedVars(spk_vars);
69  } else {
70  KALDI_WARN << "Cannot find speaker vector for " << utt << ", not decoding this utterance";
71  delete spk_vars;
72  (*num_err)++;
73  return;
74  }
75  }
76  if (!gselect_reader.HasKey(utt) ||
77  gselect_reader.Value(utt).size() != features.NumRows()) {
78  KALDI_WARN << "No Gaussian-selection info available for utterance "
79  << utt << " (or wrong size)";
80  }
81 
82  // decodable will take ownership.
83  vector<vector<int32> > *gselect = new std::vector<vector<int32> >(
84  gselect_reader.Value(utt));
85 
86  Matrix<BaseFloat> *new_feats = new Matrix<BaseFloat>(features); // decodable
87  // will take ownership of this.
88 
89  // This takes ownership of new_feats, gselect, and spk_vars
90  DecodableAmSgmm2Scaled *sgmm_decodable = new DecodableAmSgmm2Scaled(
91  am_sgmm, trans_model, new_feats, gselect,
92  spk_vars, log_prune, acoustic_scale);
93 
94  // takes ownership of decoder and sgmm_decodable.
97  decoder, sgmm_decodable, trans_model, word_syms, utt, acoustic_scale,
98  determinize, allow_partial, alignments_writer, words_writer,
99  compact_lattice_writer, lattice_writer, like_sum, frame_sum, num_done,
100  num_err, NULL);
101 
102  sequencer->Run(task); // takes ownership.
103 }
void Run(C *c)
This function takes ownership of the pointer "c", and will delete it in the same sequence as Run was ...
Definition: kaldi-thread.h:190
void ComputePerSpkDerivedVars(Sgmm2PerSpkDerivedVars *vars) const
Computes the per-speaker derived vars; assumes vars->v_s is already set up.
Definition: am-sgmm2.cc:1369
This class basically does the same job as the function DecodeUtteranceLatticeFaster, but in a way that allows us to build a multi-threaded command line program more easily.
const T & Value(const std::string &key)
#define KALDI_WARN
Definition: kaldi-error.h:150
bool HasKey(const std::string &key)
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
const T & Value(const std::string &key)
void SetSpeakerVector(const Vector< BaseFloat > &v_s_in)
Definition: am-sgmm2.h:180

◆ PruneLattice() [1/4]

bool kaldi::PruneLattice ( BaseFloat  beam,
LatticeType *  lat 
)

Prunes a lattice or compact lattice.

Returns true on success, false if there was some kind of failure.

◆ PruneLattice() [2/4]

bool kaldi::PruneLattice ( BaseFloat  beam,
LatType *  lat 
)

Definition at line 229 of file lattice-functions.cc.

References fst::ConvertToCost(), KALDI_ASSERT, and KALDI_WARN.

Referenced by fst::DeterminizeLatticePruned(), DeterminizeLatticeWrapper(), SingleUtteranceGmmDecoder::GetGaussianPosteriors(), SingleUtteranceGmmDecoder::GetLattice(), main(), and fst::TestDeterminizeLatticePruned().

229  {
230  typedef typename LatType::Arc Arc;
231  typedef typename Arc::Weight Weight;
232  typedef typename Arc::StateId StateId;
233 
234  KALDI_ASSERT(beam > 0.0);
235  if (!lat->Properties(fst::kTopSorted, true)) {
236  if (fst::TopSort(lat) == false) {
237  KALDI_WARN << "Cycles detected in lattice";
238  return false;
239  }
240  }
241  // We assume states before "start" are not reachable, since
242  // the lattice is topologically sorted.
243  int32 start = lat->Start();
244  int32 num_states = lat->NumStates();
245  if (num_states == 0) return false;
246  std::vector<double> forward_cost(num_states,
247  std::numeric_limits<double>::infinity()); // viterbi forward.
248  forward_cost[start] = 0.0; // lattice can't have cycles so couldn't be
249  // less than this.
250  double best_final_cost = std::numeric_limits<double>::infinity();
251  // Update the forward probs.
252  // Thanks to Jing Zheng for finding a bug here.
253  for (int32 state = 0; state < num_states; state++) {
254  double this_forward_cost = forward_cost[state];
255  for (fst::ArcIterator<LatType> aiter(*lat, state);
256  !aiter.Done();
257  aiter.Next()) {
258  const Arc &arc(aiter.Value());
259  StateId nextstate = arc.nextstate;
260  KALDI_ASSERT(nextstate > state && nextstate < num_states);
261  double next_forward_cost = this_forward_cost +
262  ConvertToCost(arc.weight);
263  if (forward_cost[nextstate] > next_forward_cost)
264  forward_cost[nextstate] = next_forward_cost;
265  }
266  Weight final_weight = lat->Final(state);
267  double this_final_cost = this_forward_cost +
268  ConvertToCost(final_weight);
269  if (this_final_cost < best_final_cost)
270  best_final_cost = this_final_cost;
271  }
272  int32 bad_state = lat->AddState(); // this state is not final.
273  double cutoff = best_final_cost + beam;
274 
275  // Go backwards updating the backward probs (which share memory with the
276  // forward probs), and pruning arcs and deleting final-probs. We prune arcs
277  // by making them point to the non-final state "bad_state". We'll then use
278  // Trim() to remove unnecessary arcs and states. [this is just easier than
279  // doing it ourselves.]
280  std::vector<double> &backward_cost(forward_cost);
281  for (int32 state = num_states - 1; state >= 0; state--) {
282  double this_forward_cost = forward_cost[state];
283  double this_backward_cost = ConvertToCost(lat->Final(state));
284  if (this_backward_cost + this_forward_cost > cutoff
285  && this_backward_cost != std::numeric_limits<double>::infinity())
286  lat->SetFinal(state, Weight::Zero());
287  for (fst::MutableArcIterator<LatType> aiter(lat, state);
288  !aiter.Done();
289  aiter.Next()) {
290  Arc arc(aiter.Value());
291  StateId nextstate = arc.nextstate;
292  KALDI_ASSERT(nextstate > state && nextstate < num_states);
293  double arc_cost = ConvertToCost(arc.weight),
294  arc_backward_cost = arc_cost + backward_cost[nextstate],
295  this_fb_cost = this_forward_cost + arc_backward_cost;
296  if (arc_backward_cost < this_backward_cost)
297  this_backward_cost = arc_backward_cost;
298  if (this_fb_cost > cutoff) { // Prune the arc.
299  arc.nextstate = bad_state;
300  aiter.SetValue(arc);
301  }
302  }
303  backward_cost[state] = this_backward_cost;
304  }
305  fst::Connect(lat);
306  return (lat->NumStates() > 0);
307 }
fst::StdArc::StateId StateId
kaldi::int32 int32
double ConvertToCost(const LatticeWeightTpl< Float > &w)
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ PruneLattice() [3/4]

template bool kaldi::PruneLattice ( BaseFloat  beam,
Lattice lat 
)

◆ PruneLattice() [4/4]

template bool kaldi::PruneLattice ( BaseFloat  beam,
CompactLattice lat 
)

◆ QrInternal()

void kaldi::QrInternal ( MatrixIndexT  n,
Real *  diag,
Real *  off_diag,
MatrixBase< Real > *  Q 
)

Definition at line 331 of file qr.cc.

References rnnlm::d, rnnlm::i, KALDI_ASSERT, KALDI_WARN, rnnlm::n, MatrixBase< Real >::NumCols(), and QrStep().

Referenced by SpMatrix< float >::Qr().

334  {
335  KALDI_ASSERT(Q == NULL || Q->NumCols() == n); // We may
336  // later relax the condition that Q->NumCols() == n.
337 
338  MatrixIndexT counter = 0, max_iters = 500 + 4*n, // Should never take this many iters.
339  large_iters = 100 + 2*n;
340  Real epsilon = (pow(2.0, sizeof(Real) == 4 ? -23.0 : -52.0));
341 
342  for (; counter < max_iters; counter++) { // this takes the place of "until
343  // q=n"... we'll break out of the
344  // loop when we converge.
345  if (counter == large_iters ||
346  (counter > large_iters && (counter - large_iters) % 50 == 0)) {
347  KALDI_WARN << "Took " << counter
348  << " iterations in QR (dim is " << n << "), doubling epsilon.";
349  SubVector<Real> d(diag, n), o(off_diag, n-1);
350  KALDI_WARN << "Diag, off-diag are " << d << " and " << o;
351  epsilon *= 2.0;
352  }
353  for (MatrixIndexT i = 0; i+1 < n; i++) {
354  if (std::abs(off_diag[i]) <= epsilon *
355  (std::abs(diag[i]) + std::abs(diag[i+1])))
356  off_diag[i] = 0.0;
357  }
358  // The next code works out p, q, and npq which is n - p - q.
359  // For the definitions of q and p, see Golub and Van Loan; we
360  // partition the n dims into pieces of size (p, n-p-q, q) where
361  // the part of size q is diagonal and the part of size n-p-p is
362  // "unreduced", i.e. has no zero off-diagonal elements.
363  MatrixIndexT q = 0;
364  // Note: below, "n-q < 2" should more clearly be "n-2-q < 0", but that
365  // causes problems if MatrixIndexT is unsigned.
366  while (q < n && (n-q < 2 || off_diag[n-2-q] == 0.0))
367  q++;
368  if (q == n) break; // we're done. It's diagonal.
369  KALDI_ASSERT(n - q >= 2);
370  MatrixIndexT npq = 2; // Value of n - p - q, where n - p - q must be
371  // unreduced. This is the size of "middle" band of elements. If q != n,
372  // we must have hit a nonzero off-diag element, so the size of this
373  // band must be at least two.
374  while (npq + q < n && (n-q-npq-1 < 0 || off_diag[n-q-npq-1] != 0.0))
375  npq++;
376  MatrixIndexT p = n - q - npq;
377  { // Checks.
378  for (MatrixIndexT i = 0; i+1 < npq; i++)
379  KALDI_ASSERT(off_diag[p + i] != 0.0);
380  for (MatrixIndexT i = 0; i+1 < q; i++)
381  KALDI_ASSERT(off_diag[p + npq - 1 + i] == 0.0);
382  if (p > 1) // Something must have stopped npq from growing further..
383  KALDI_ASSERT(off_diag[p-1] == 0.0); // so last off-diag elem in
384  // group of size p must be zero.
385  }
386 
387  if (Q != NULL) {
388  // Do one QR step on the middle part of Q only.
389  // Qpart will be a subset of the rows of Q.
390  SubMatrix<Real> Qpart(*Q, p, npq, 0, Q->NumCols());
391  QrStep(npq, diag + p, off_diag + p, &Qpart);
392  } else {
393  QrStep(npq, diag + p, off_diag + p,
394  static_cast<MatrixBase<Real>*>(NULL));
395  }
396  }
397  if (counter == max_iters) {
398  KALDI_WARN << "Failure to converge in QR algorithm. "
399  << "Exiting with partial output.";
400  }
401 }
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void QrStep(MatrixIndexT n, Real *diag, Real *off_diag, MatrixBase< Real > *Q)
Definition: qr.cc:245

◆ QrStep()

void kaldi::QrStep ( MatrixIndexT  n,
Real *  diag,
Real *  off_diag,
MatrixBase< Real > *  Q 
)

Definition at line 245 of file qr.cc.

References cblas_Xrot(), rnnlm::d, MatrixBase< Real >::Data(), Givens(), KALDI_ASSERT, KALDI_ISFINITE, MatrixBase< Real >::NumCols(), and MatrixBase< Real >::Stride().

Referenced by QrInternal().

248  {
249  KALDI_ASSERT(n >= 2);
250  // below, "scale" could be any number; we introduce it to keep the
251  // floating point quantities within a good range.
252  Real d = (diag[n-2] - diag[n-1]) / 2.0,
253  t = off_diag[n-2],
254  inv_scale = std::max(std::max(std::abs(d), std::abs(t)),
255  std::numeric_limits<Real>::min()),
256  scale = 1.0 / inv_scale,
257  d_scaled = d * scale,
258  off_diag_n2_scaled = off_diag[n-2] * scale,
259  t2_n_n1_scaled = off_diag_n2_scaled * off_diag_n2_scaled,
260  sgn_d = (d > 0.0 ? 1.0 : -1.0),
261  mu = diag[n-1] - inv_scale * t2_n_n1_scaled /
262  (d_scaled + sgn_d * std::sqrt(d_scaled * d_scaled + t2_n_n1_scaled)),
263  x = diag[0] - mu,
264  z = off_diag[0];
266  Real *Qdata = (Q == NULL ? NULL : Q->Data());
267  MatrixIndexT Qstride = (Q == NULL ? 0 : Q->Stride()),
268  Qcols = (Q == NULL ? 0 : Q->NumCols());
269  for (MatrixIndexT k = 0; k < n-1; k++) {
270  Real c, s;
271  Givens(x, z, &c, &s);
272  // Rotate dimensions k and k+1 with the Givens matrix G, as
273  // T <== G^T T G.
274  // In 2d, a Givens matrix is [ c s; -s c ]. Forget about
275  // the dimension-indexing issues and assume we have a 2x2
276  // symmetric matrix [ p q ; q r ]
277  // We ask our friends at Wolfram Alpha about
278  // { { c, -s}, {s, c} } * { {p, q}, {q, r} } * { { c, s}, {-s, c} }
279  // Interpreting the result as [ p', q' ; q', r ]
280  // p' = c (c p - s q) - s (c q - s r)
281  // q' = s (c p - s q) + c (c q - s r)
282  // r' = s (s p + c q) + c (s q + c r)
283  Real p = diag[k], q = off_diag[k], r = diag[k+1];
284  // p is element k,k; r is element k+1,k+1; q is element k,k+1 or k+1,k.
285  // We'll let the compiler optimize this.
286  diag[k] = c * (c*p - s*q) - s * (c*q - s*r);
287  off_diag[k] = s * (c*p - s*q) + c * (c*q - s*r);
288  diag[k+1] = s * (s*p + c*q) + c * (s*q + c*r);
289 
290  // We also have some other elements to think of that
291  // got rotated in a simpler way: if k>0,
292  // then element (k, k-1) and (k+1, k-1) get rotated. Here,
293  // element k+1, k-1 will be present as z; it's the out-of-band
294  // element that we remembered from last time. This is
295  // on the left as it's the row indexes that differ, so think of
296  // this as being premultiplied by G^T. In fact we're multiplying
297  // T by in some sense the opposite/transpose of the Givens rotation.
298  if (k > 0) { // Note, in rotations, going backward, (x,y) -> ((cx - sy), (sx + cy))
299  Real &elem_k_km1 = off_diag[k-1],
300  elem_kp1_km1 = z; // , tmp = elem_k_km1;
301  elem_k_km1 = c*elem_k_km1 - s*elem_kp1_km1;
302  // The next line will set elem_kp1_km1 to zero and we'll never access this
303  // value, so we comment it out.
304  // elem_kp1_km1 = s*tmp + c*elem_kp1_km1;
305  }
306  if (Q != NULL)
307  cblas_Xrot(Qcols, Qdata + k*Qstride, 1,
308  Qdata + (k+1)*Qstride, 1, c, -s);
309  if (k < n-2) {
310  // Next is the elements (k+2, k) and (k+2, k-1), to be rotated, again
311  // backwards.
312  Real &elem_kp2_k = z,
313  &elem_kp2_kp1 = off_diag[k+1];
314  // Note: elem_kp2_k == z would start off as zero because it's
315  // two off the diagonal, and not been touched yet. Therefore
316  // we eliminate it in expressions below, commenting it out.
317  // If we didn't do this we should set it to zero first.
318  elem_kp2_k = - s * elem_kp2_kp1; // + c*elem_kp2_k
319  elem_kp2_kp1 = c * elem_kp2_kp1; // + s*elem_kp2_k (original value).
320  // The next part is from the algorithm they describe: x = t_{k+1,k}
321  x = off_diag[k];
322  }
323  }
324 }
void Givens(Real a, Real b, Real *c, Real *s)
Create Givens rotations, as in Golub and Van Loan 3rd ed., page 216.
Definition: qr.cc:221
#define KALDI_ISFINITE(x)
Definition: kaldi-math.h:74
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void cblas_Xrot(const int N, float *X, const int incX, float *Y, const int incY, const float c, const float s)

◆ QuoteAndEscape()

static std::string kaldi::QuoteAndEscape ( const std::string &  str,
ShellType  st 
)
static

Definition at line 263 of file parse-options.cc.

References KALDI_ASSERT, and kBash.

Referenced by ParseOptions::Escape().

263  {
264  // Only Bash is supported (for the moment).
265  KALDI_ASSERT(st == kBash && "Invalid shell type.");
266 
267  // For now we use the following rules:
268  // In the normal case, we quote with single-quote "'", and to escape
269  // a single-quote we use the string: '\'' (interpreted as closing the
270  // single-quote, putting an escaped single-quote from the shell, and
271  // then reopening the single quote).
272  char quote_char = '\'';
273  const char *escape_str = "'\\''"; // e.g. echo 'a'\''b' returns a'b
274 
275  // If the string contains single-quotes that would need escaping this
276  // way, and we determine that the string could be safely double-quoted
277  // without requiring any escaping, then we double-quote the string.
278  // This is the case if the characters "`$\ do not appear in the string.
279  // e.g. see http://www.redhat.com/mirrors/LDP/LDP/abs/html/quotingvar.html
280  const char *c_str = str.c_str();
281  if (strchr(c_str, '\'') && !strpbrk(c_str, "\"`$\\")) {
282  quote_char = '"';
283  escape_str = "\\\""; // should never be accessed.
284  }
285 
286  char buf[2];
287  buf[1] = '\0';
288 
289  buf[0] = quote_char;
290  std::string ans = buf;
291  const char *c = str.c_str();
292  for (;*c != '\0'; c++) {
293  if (*c == quote_char) {
294  ans += escape_str;
295  } else {
296  buf[0] = *c;
297  ans += buf;
298  }
299  }
300  buf[0] = quote_char;
301  ans += buf;
302  return ans;
303 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ Rand()

int Rand ( struct RandomState state)

Definition at line 45 of file kaldi-math.cc.

References RandomState::seed.

Referenced by CholeskyUnitTestTr(), ClusterKMeansOnce(), OnlineMatrixInput::Compute(), kaldi::nnet3::ComputeExampleComputationRequestSimple(), CuVectorUnitTestAddColSumMat(), CuVectorUnitTestAddDiagMat2(), CuVectorUnitTestAddDiagMatMat(), CuVectorUnitTestAddMatVec(), CuVectorUnitTestAddRowSumMat(), CuVectorUnitTestAddSpVec(), CuVectorUnitTestAddVec(), CuVectorUnitTestAddVecCross(), CuVectorUnitTestAddVecExtra(), CuVectorUnitTestAddVecVec(), CuVectorUnitTestApplyCeiling(), CuVectorUnitTestApplyCeilingNoCount(), CuVectorUnitTestApplyFloor(), CuVectorUnitTestApplyFloorNoCount(), CuVectorUnitTestApplyPow(), CuVectorUnitTestApplySoftMax(), CuVectorUnitTestApproxEqual(), CuVectorUnitTestCopyCross(), CuVectorUnitTestCopyCross2(), CuVectorUnitTestCopyDiagFromMat(), CuVectorUnitTestCopyDiagFromPacked(), CuVectorUnitTestCopyElements(), CuVectorUnitTestCopyFromMat(), CuVectorUnitTestInvertElements(), CuVectorUnitTestMax(), CuVectorUnitTestMin(), CuVectorUnitTestScale(), CuVectorUnitTestSum(), CuVectorUnitTestVecVec(), fst::GenAcceptorFromSequence(), kaldi::nnet3::GenerateConfigSequenceCnn(), kaldi::nnet3::GenerateConfigSequenceLstm(), kaldi::nnet3::GenerateConfigSequenceLstmType2(), kaldi::nnet3::GenerateConfigSequenceLstmWithTruncation(), kaldi::nnet3::GenerateConfigSequenceRnn(), kaldi::nnet3::GenerateConfigSequenceRnnClockwork(), kaldi::nnet3::GenerateConfigSequenceSimple(), kaldi::nnet3::GenerateConfigSequenceSimpleContext(), kaldi::nnet3::GenerateConfigSequenceSimplest(), kaldi::nnet3::GenerateRandomComponentConfig(), GenRandContextDependency(), GenRandContextDependencyLarge(), kaldi::nnet3::GenRandDescriptor(), kaldi::nnet3::GenRandForwardingDescriptor(), fst::GenRandPhoneSeq(), GenRandStats(), kaldi::nnet3::GenRandSumDescriptor(), GetOutput(), GetRandChar(), GetRandDelim(), InitRandomGmm(), AmSgmm2::LogLikelihood(), main(), MyTaskClass::operator()(), kaldi::nnet2::PreconditionDirections(), fst::RandFst(), RandFstOptions::RandFstOptions(), RandInt(), fst::RandomCompactLatticeWeight(), RandomEventMap(), RandomizeVector(), fst::RandomLatticeWeight(), RandomState::RandomState(), fst::RandPairFst(), RandPosdefSpMatrix(), RandUniform(), kaldi::nnet1::RandUniform(), fst::TestAcceptorMinimize(), fst::TestAddSelfLoops(), TestAddToClustersOptimized(), TestBuildTree(), TestBuildTreeStatsIo(), TestClusterBottomUp(), TestClusterEventMap(), TestClusterEventMapGetMappingAndRenumberEventMap(), TestClusterEventMapGetMappingAndRenumberEventMap2(), TestClusterEventMapRestricted(), TestClusterKMeans(), TestClusterKMeansVector(), TestClusterTopDown(), TestClusterUtils(), TestClusterUtilsVector(), TestContainsNullPointers(), TestContextDep(), fst::TestContextFst(), fst::TestConvert(), fst::TestConvert2(), fst::TestConvertPair(), TestCopyMapKeysToSet(), TestCopyMapKeysToVector(), TestCopyMapToVector(), TestCopyMapValuesToSet(), TestCopyMapValuesToVector(), TestCopySetToVector(), TestCuFindRowMaxId(), TestCuMatrixCompObjfAndDeriv(), TestCuMatrixLookup(), TestCuSparseMatrixTraceMatSmat(), fst::TestDeterminize(), fst::TestDeterminize2(), fst::TestDeterminizeGeneral(), fst::TestDeterminizeLattice(), fst::TestDeterminizeLatticePruned(), TestEditDistance2(), TestEditDistance2String(), fst::TestEnsureEpsilonProperty(), fst::TestEqualAlign(), WordAlignedLatticeTester::TestEquivalent(), TestEventMap(), TestEventMapIo(), TestEventMapMapValues(), TestEventMapPrune(), TestEventTypeIo(), fst::TestFactor(), TestFmpe(), TestGenRandContextDependency(), TestGenRandStats(), TestHashList(), TestHmmTopology(), TestIsSorted(), TestIsSortedAndUniq(), TestIvectorExtractorIO(), TestIvectorExtractorStatsIO(), fst::TestLatticeStringRepository(), TestLatticeTableCross(), TestLevenshteinAlignment(), fst::TestMakeLinearAcceptor(), fst::TestMakeLoopFst(), fst::TestMakeSymbolsSame(), fst::TestMakeSymbolsSameClass(), TestMergePairVectorSumming(), fst::TestMinimize(), TestMinimizeCompactLattice(), TestMonophoneContextDependency(), kaldi::nnet3::TestNnetComponentIo(), TestOnlineCmnInput(), TestOnlineDeltaInput(), TestOnlineFeatureMatrix(), TestOnlineLdaInput(), TestOnlineMatrixInput(), fst::TestPreDeterminize(), fst::TestPruneSpecial(), fst::TestPush(), TestPushCompactLatticeStrings(), TestPushCompactLatticeWeights(), fst::TestPushInLog(), fst::TestPushSpecial(), TestQuestionsInitRand(), TestRefineClusters(), fst::TestRemoveEpsLocal(), fst::TestRemoveEpsLocalSpecial(), TestReverseVector(), fst::TestSafeDeterminizeWrapper(), fst::TestScalePair(), TestSetOfNumbers(), TestShareEventMapLeaves(), kaldi::nnet3::TestSimpleComponentDataDerivative(), kaldi::nnet3::TestSimpleComponentPropagateProperties(), TestSortAndUniq(), TestSplitDecisionTree(), TestSplitStatsByKey(), TestSplitStringToVector(), fst::TestStringRepository(), fst::TestTableMatcher(), fst::TestTableMatcherCacheLeft(), fst::TestTableMatcherCacheRight(), TestTaskSequencer(), TestTreeCluster(), TestUniq(), TestWordAlignedLattice(), UnitTestAddDiagMat2(), UnitTestAddDiagMatMat(), UnitTestAddDiagVecMat(), kaldi::nnet2::UnitTestAdditiveNoiseComponent(), UnitTestAddMat2(), UnitTestAddMat2Sp(), UnitTestAddMatDiagVec(), UnitTestAddMatMatElements(), UnitTestAddMatSelf(), UnitTestAddMatSmat(), UnitTestAddOuterProductPlusMinus(), UnitTestAddRows(), UnitTestAddSp(), UnitTestAddToDiag(), UnitTestAddToDiagMatrix(), UnitTestAddToRows(), UnitTestAddVec2Sp(), UnitTestAddVecToCols(), UnitTestAddVecToRows(), UnitTestAddVecVec(), kaldi::nnet2::UnitTestAffineComponent(), kaldi::nnet2::UnitTestAffineComponentPreconditioned(), kaldi::nnet2::UnitTestAffineComponentPreconditionedOnline(), UnitTestAssertFunc(), UnitTestAxpy(), UnitTestBackpropLstmNonlinearity(), kaldi::nnet2::UnitTestBlockAffineComponent(), kaldi::nnet2::UnitTestBlockAffineComponentPreconditioned(), UnitTestCholesky(), UnitTestComplexFft(), UnitTestComplexFt(), UnitTestCompressedMatrix(), kaldi::nnet3::UnitTestComputationRequestIo(), kaldi::nnet2::UnitTestConvolutional1dComponent(), UnitTestCopyCols(), UnitTestCopyRows(), UnitTestCopyRowsAndCols(), UnitTestCopySp(), UnitTestCopyToRows(), UnitTestCuApproxEqual(), UnitTestCuArray(), UnitTestCuBlockMatrixAddMatBlock(), UnitTestCuBlockMatrixAddMatMat(), UnitTestCuBlockMatrixIO(), UnitTestCuCholesky(), UnitTestCuCopy(), UnitTestCuDiffNormalizePerRow(), UnitTestCuDiffXent(), UnitTestCuFindRowMaxId(), UnitTestCuLogSoftmax(), UnitTestCuMathComputeLstmNonlinearity(), UnitTestCuMathCopy(), UnitTestCuMathNormalizePerRow(), UnitTestCuMathRandomize(), UnitTestCuMathSplice(), UnitTestCuMatrixAdd(), UnitTestCuMatrixAdd2(), UnitTestCuMatrixAddCols(), UnitTestCuMatrixAddDiagVecMat(), UnitTestCuMatrixAddElements(), UnitTestCuMatrixAddMat(), UnitTestCuMatrixAddMatDiagVec(), UnitTestCuMatrixAddMatMatElements(), UnitTestCuMatrixAddMatTp(), UnitTestCuMatrixAddRowRanges(), UnitTestCuMatrixAddRows(), UnitTestCuMatrixAddToDiag(), UnitTestCuMatrixAddToElements(), UnitTestCuMatrixAddToRows(), UnitTestCuMatrixAddTpMat(), UnitTestCuMatrixApplyCeiling(), UnitTestCuMatrixApplyExp(), UnitTestCuMatrixApplyExpLimited(), UnitTestCuMatrixApplyExpSpecial(), UnitTestCuMatrixApplyFloor(), UnitTestCuMatrixApplyHeaviside(), UnitTestCuMatrixApplyLog(), UnitTestCuMatrixApplyPow(), UnitTestCuMatrixApplyPowAbs(), UnitTestCuMatrixCopyCols(), UnitTestCuMatrixCopyColsFromVec(), UnitTestCuMatrixCopyCross(), UnitTestCuMatrixCopyCross2(), UnitTestCuMatrixCopyFromMat(), UnitTestCuMatrixCopyFromTp(), UnitTestCuMatrixCopyLowerToUpper(), UnitTestCuMatrixCopyRows(), UnitTestCuMatrixCopyRowsFromVec(), UnitTestCuMatrixCopyToRows(), UnitTestCuMatrixCopyUpperToLower(), UnitTestCuMatrixDiffGroupPnorm(), UnitTestCuMatrixDivElements(), UnitTestCuMatrixGroupMax(), UnitTestCuMatrixGroupMaxDeriv(), UnitTestCuMatrixGroupPnorm(), UnitTestCuMatrixHeaviside(), UnitTestCuMatrixIO(), UnitTestCuMatrixLookup(), UnitTestCuMatrixMulElements(), UnitTestCuMatrixMulRows(), UnitTestCuMatrixMulRowsGroupMat(), UnitTestCuMatrixMulRowsVec(), UnitTestCuMatrixObjfDeriv(), UnitTestCuMatrixReduceMax(), UnitTestCuMatrixReduceMin(), UnitTestCuMatrixReduceSum(), UnitTestCuMatrixScale(), UnitTestCuMatrixSet(), UnitTestCuMatrixSetMatMatDivMat(), UnitTestCuMatrixSetRandn(), UnitTestCuMatrixSetRandUniform(), UnitTestCuMatrixSetZeroAboveDiag(), UnitTestCuMatrixSigmoid(), UnitTestCuMatrixSoftHinge(), UnitTestCuMatrixSumColumnRanges(), UnitTestCuMatrixSymAddMat2(), UnitTestCuMatrixSymInvertPosDef(), UnitTestCuMatrixTraceMatMat(), UnitTestCuMatrixTranspose(), UnitTestCuPackedMatrixAddToDiag(), UnitTestCuPackedMatrixScale(), UnitTestCuPackedMatrixScaleDiag(), UnitTestCuPackedMatrixSetUnit(), UnitTestCuPackedMatrixTrace(), UnitTestCuSoftmax(), UnitTestCuSparseMatrixConstructFromIndexes(), UnitTestCuSparseMatrixCopyToSmat(), UnitTestCuSparseMatrixFrobeniusNorm(), UnitTestCuSparseMatrixSelectRowsAndTranspose(), UnitTestCuSparseMatrixSum(), UnitTestCuSparseMatrixSwap(), UnitTestCuSparseMatrixTraceMatSmat(), UnitTestCuSpMatrixAddMat2(), UnitTestCuSpMatrixAddSp(), UnitTestCuSpMatrixAddVec2(), UnitTestCuSpMatrixApproxEqual(), UnitTestCuSpMatrixCopyFromMat(), UnitTestCuSpMatrixInvert(), UnitTestCuSpMatrixIO(), UnitTestCuSpMatrixSetUnit(), UnitTestCuSpMatrixTraceSpSp(), UnitTestCuSubMatrix(), UnitTestCuSubVector(), UnitTestCuTpMatrixCholesky(), UnitTestCuTpMatrixCopyFromMat(), UnitTestCuTpMatrixCopyFromTp(), UnitTestCuTpMatrixInvert(), UnitTestCuTpMatrixIO(), UnitTestCuVectorIO(), UnitTestCuVectorReplaceValue(), UnitTestDct(), kaldi::nnet2::UnitTestDctComponent(), kaldi::nnet3::UnitTestDescriptorIo(), UnitTestDeterminant(), UnitTestDeterminantSign(), UnitTestDotprod(), kaldi::nnet2::UnitTestDropoutComponent(), UnitTestEigSp(), UnitTestEigSymmetric(), UnitTestEnsureNonzero(), UnitTestEstimateDiagGmm(), UnitTestEstimateMmieDiagGmm(), UnitTestExtractCompressedMatrix(), UnitTestFactorizeTpl(), UnitTestFFTbasedBlockConvolution(), UnitTestFFTbasedConvolution(), kaldi::nnet2::UnitTestFixedAffineComponent(), kaldi::nnet2::UnitTestFixedBiasComponent(), kaldi::nnet2::UnitTestFixedLinearComponent(), kaldi::nnet2::UnitTestFixedScaleComponent(), UnitTestFloorCeiling(), UnitTestFloorChol(), UnitTestFloorUnit(), UnitTestFmllrRaw(), UnitTestFullGmmEst(), UnitTestGcdLcmTpl(), kaldi::nnet3::UnitTestGeneralDescriptor(), UnitTestGeneralMatrix(), kaldi::nnet2::UnitTestGenericComponent(), kaldi::nnet2::UnitTestGenericComponentInternal(), UnitTestHeaviside(), UnitTestHtkIo(), UnitTestInnerProd(), UnitTestInverse(), UnitTestInvert(), UnitTestIo(), UnitTestIoCross(), UnitTestIoNew(), UnitTestIoPipe(), UnitTestIvectorExtractor(), UnitTestLbfgs(), UnitTestLimitCond(), UnitTestLimitCondInvert(), UnitTestLinearCgd(), UnitTestLogAddSub(), UnitTestMat2Vec(), UnitTestMatrix(), UnitTestMax2(), UnitTestMaxMin(), kaldi::nnet2::UnitTestMaxoutComponent(), kaldi::nnet2::UnitTestMaxpoolingComponent(), UnitTestMmul(), UnitTestMmulSym(), UnitTestMul(), UnitTestMulElements(), UnitTestMulTp(), kaldi::nnet3::UnitTestNnetComputationIo(), kaldi::nnet3::UnitTestNnetIo(), UnitTestNonsymmetricPower(), UnitTestNorm(), UnitTestOnlineCmvn(), UnitTestOrthogonalizeRows(), UnitTestPca(), UnitTestPldaEstimation(), kaldi::nnet2::UnitTestPnormComponent(), UnitTestPosteriors(), UnitTestPower(), UnitTestPowerAbs(), kaldi::nnet2::UnitTestPreconditionDirections(), kaldi::nnet2::UnitTestPreconditionDirectionsOnline(), kaldi::nnet3::UnitTestPreconditionDirectionsOnline(), UnitTestRand(), UnitTestRandCategorical(), UnitTestRange(), UnitTestRankNUpdate(), UnitTestRealFft(), UnitTestRegressionTree(), UnitTestRegtreeFmllrDiagGmm(), UnitTestRemoveRow(), UnitTestReplaceValue(), UnitTestResize(), UnitTestResizeCopyDataDifferentStrideType(), UnitTestRow(), UnitTestScale(), kaldi::nnet2::UnitTestScaleComponent(), UnitTestScaleDiag(), UnitTestSetDiag(), UnitTestSetRandn(), UnitTestSetRandUniform(), UnitTestSger(), UnitTestSigmoid(), kaldi::nnet2::UnitTestSigmoidComponent(), UnitTestSimple(), UnitTestSimpleForMat(), UnitTestSimpleForVec(), UnitTestSoftHinge(), UnitTestSolve(), kaldi::nnet2::UnitTestSolvePackingProblem(), UnitTestSpAddDiagVec(), UnitTestSpAddVecVec(), UnitTestSparseMatrixAddToMat(), UnitTestSparseMatrixFrobeniusNorm(), UnitTestSparseMatrixSum(), UnitTestSparseMatrixTraceMatSmat(), UnitTestSparseVectorAddToVec(), UnitTestSparseVectorMax(), UnitTestSparseVectorSum(), UnitTestSparseVectorVecSvec(), UnitTestSpInvert(), UnitTestSpliceRows(), kaldi::nnet3::UnitTestSplitLocations(), kaldi::nnet3::UnitTestSplitLocationsBackward(), UnitTestSplitRadixComplexFft(), UnitTestSplitRadixComplexFft2(), UnitTestSplitRadixRealFft(), kaldi::nnet2::UnitTestSumGroupComponent(), UnitTestSvd(), UnitTestSvdJustvec(), UnitTestSvdNodestroy(), UnitTestSvdZero(), UnitTestSymAddMat2(), UnitTestTableRandomBothDouble(), UnitTestTableRandomBothDoubleMatrix(), UnitTestTableSequentialBaseFloatVectorBoth(), UnitTestTableSequentialBool(), UnitTestTableSequentialDouble(), UnitTestTableSequentialDoubleBoth(), UnitTestTableSequentialDoubleMatrixBoth(), UnitTestTableSequentialInt32(), UnitTestTableSequentialInt32PairVectorBoth(), UnitTestTableSequentialInt32Script(), UnitTestTableSequentialInt32VectorBoth(), UnitTestTableSequentialInt32VectorVectorBoth(), UnitTestTanh(), UnitTestTp2(), UnitTestTp2Sp(), UnitTestTpInvert(), UnitTestTrace(), UnitTestTraceProduct(), UnitTestTraceSpSpLower(), UnitTestTrain(), UnitTestTranspose(), UnitTestTransposeScatter(), UnitTestTridiagonalize(), UnitTestTridiagonalizeAndQr(), UnitTestTriVecSolver(), UnitTestVecMatVec(), UnitTestVecmul(), UnitTestVector(), UnitTestVectorMax(), UnitTestVectorMin(), UnitTextCuMatrixAddMatSmat(), UnitTextCuMatrixAddSmat(), UnitTextCuMatrixAddSmatMat(), and WithProb().

45  {
46 #if !defined(_POSIX_THREAD_SAFE_FUNCTIONS)
47  // On Windows and Cygwin, just call Rand()
48  return rand();
49 #else
50  if (state) {
51  return rand_r(&(state->seed));
52  } else {
53  std::lock_guard<std::mutex> lock(_RandMutex);
54  return rand();
55  }
56 #endif
57 }
static std::mutex _RandMutex
Definition: kaldi-math.cc:43

◆ RandCompactLattice()

CompactLattice * RandCompactLattice ( )

Definition at line 28 of file kaldi-lattice-test.cc.

References fst::ConvertLattice().

Referenced by TestCompactLatticeTable(), TestCompactLatticeTableCross(), TestPushCompactLatticeStrings(), and TestPushCompactLatticeWeights().

28  {
29  Lattice *fst = fst::RandPairFst<LatticeArc>();
30  CompactLattice *cfst = new CompactLattice;
31  ConvertLattice(*fst, cfst);
32  delete fst;
33  return cfst;
34 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46

◆ RandDeterministicCompactLattice()

CompactLattice* kaldi::RandDeterministicCompactLattice ( )

Definition at line 30 of file minimize-lattice-test.cc.

References RandFstOptions::acyclic, fst::DeterminizeLattice(), and KALDI_WARN.

Referenced by TestMinimizeCompactLattice().

30  {
31  RandFstOptions opts;
32  opts.acyclic = true;
33  while (1) {
34  Lattice *fst = fst::RandPairFst<LatticeArc>(opts);
35  CompactLattice *cfst = new CompactLattice;
36  if (!DeterminizeLattice(*fst, cfst)) {
37  delete fst;
38  delete cfst;
39  KALDI_WARN << "Determinization failed, trying again.";
40  } else {
41  delete fst;
42  return cfst;
43  }
44  }
45 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
bool DeterminizeLattice(const Fst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< Weight > > *ofst, DeterminizeLatticeOptions opts, bool *debug_ptr)
This function implements the normal version of DeterminizeLattice, in which the output strings are re...

◆ RandFullCova()

static void kaldi::RandFullCova ( Matrix< BaseFloat > *  matrix)
static

Definition at line 30 of file regtree-fmllr-diag-gmm-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::Cond(), MatrixBase< Real >::CopyFromSp(), KALDI_ASSERT, KALDI_ERR, kNoTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and MatrixBase< Real >::SetRandn().

Referenced by generate_features().

30  {
31  size_t dim = matrix->NumCols();
32  KALDI_ASSERT(matrix->NumCols() == matrix->NumRows());
33 
34  size_t iter = 0;
35  size_t max_iter = 10000;
36  // generate random (non-singular) matrix
37  // until condition
38  Matrix<BaseFloat> tmp(dim, dim);
39  SpMatrix<BaseFloat> tmp2(dim);
40  while (iter < max_iter) {
41  tmp.SetRandn();
42  if (tmp.Cond() < 100) break;
43  iter++;
44  }
45  if (iter >= max_iter) {
46  KALDI_ERR << "Internal error: found no random covariance matrix.";
47  }
48  // tmp * tmp^T will give positive definite matrix
49  tmp2.AddMat2(1.0, tmp, kNoTrans, 0.0);
50  matrix->CopyFromSp(tmp2);
51 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
void CopyFromSp(const SpMatrix< OtherReal > &M)
Copy given spmatrix. (no resize is done).
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ RandGauss()

float kaldi::RandGauss ( struct RandomState state = NULL)
inline

Definition at line 155 of file kaldi-math.h.

References Log(), M_PI, RandGauss2(), RandPoisson(), and RandUniform().

Referenced by _RandGauss(), Dither(), DiagGmm::Generate(), generate_features(), GenRandStats(), OnlineProcessPitch::GetDeltaPitchFeature(), init_rand_diag_gmm(), InitRand(), kaldi::unittest::InitRandDiagGmm(), kaldi::unittest::InitRandFullGmm(), InitRandNonsingular(), InitRandomGmm(), DiagGmm::Perturb(), PlaceNansInGaps(), rand_diag_gmm(), kaldi::unittest::RandDiagGaussFeatures(), kaldi::unittest::RandFullGaussFeatures(), fst::RandomLatticeWeight(), VectorBase< float >::SetRandn(), PackedMatrix< float >::SetRandn(), SparseVector< Real >::SetRandn(), MatrixBase< float >::SetRandn(), DiagGmm::Split(), TestAddToClustersOptimized(), TestAmDiagGmmIO(), TestClusterEventMapRestricted(), TestClustering(), TestClusterUtils(), TestContextDep(), TestFmpe(), TestSgmm2Fmllr(), TestSgmm2IncreaseDim(), TestSgmm2Init(), TestSgmm2IO(), TestSgmm2Substates(), TestShareEventMapLeaves(), TestSplitDecisionTree(), TestSplitStates(), UnitTestComplexPower(), UnitTestCompressedMatrix(), UnitTestCuSpMatrixAddVec2(), UnitTestDelay(), UnitTestDiagGmm(), UnitTestEstimateDiagGmm(), UnitTestEstimateFullGmm(), UnitTestEstimateLda(), UnitTestEstimateMmieDiagGmm(), UnitTestEstimateSgmm2(), UnitTestFullGmm(), UnitTestGeneralMatrix(), UnitTestMleAmDiagGmm(), UnitTestNorm(), UnitTestPieces(), UnitTestRand(), UnitTestSearch(), UnitTestSparseMatrixConstructor(), UnitTestSpInvert(), UnitTestTableSequentialBaseFloatVectorBoth(), UnitTestTableSequentialDoubleMatrixBoth(), UnitTestTopEigs(), UnitTestTpInvert(), and UnitTestTransposeScatter().

155  {
156  return static_cast<float>(sqrtf (-2 * Log(RandUniform(state)))
157  * cosf(2*M_PI*RandUniform(state)));
158 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
#define M_PI
Definition: kaldi-math.h:44
float Log(float x)
Definition: kaldi-math.h:101

◆ RandGauss2() [1/2]

void RandGauss2 ( float a,
float b,
RandomState state 
)

Definition at line 139 of file kaldi-math.cc.

References KALDI_ASSERT, M_PI, and RandUniform().

Referenced by RandGauss(), RandGauss2(), VectorBase< float >::SetRandn(), MatrixBase< float >::SetRandn(), and UnitTestRand().

139  {
140  KALDI_ASSERT(a);
141  KALDI_ASSERT(b);
142  float u1 = RandUniform(state);
143  float u2 = RandUniform(state);
144  u1 = sqrtf(-2.0f * logf(u1));
145  u2 = 2.0f * M_PI * u2;
146  *a = u1 * cosf(u2);
147  *b = u1 * sinf(u2);
148 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
#define M_PI
Definition: kaldi-math.h:44
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RandGauss2() [2/2]

void RandGauss2 ( double *  a,
double *  b,
RandomState state 
)

Definition at line 150 of file kaldi-math.cc.

References KALDI_ASSERT, and RandGauss2().

150  {
151  KALDI_ASSERT(a);
152  KALDI_ASSERT(b);
153  float a_float, b_float;
154  // Just because we're using doubles doesn't mean we need super-high-quality
155  // random numbers, so we just use the floating-point version internally.
156  RandGauss2(&a_float, &b_float, state);
157  *a = a_float;
158  *b = b_float;
159 }
void RandGauss2(double *a, double *b, RandomState *state)
Definition: kaldi-math.cc:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RandInt()

int32 RandInt ( int32  min_val,
int32  max_val,
struct RandomState state 
)

Definition at line 95 of file kaldi-math.cc.

References KALDI_ASSERT, KALDI_ERR, and Rand().

Referenced by ComputationGraphBuilder::Check(), kaldi::nnet3::time_height_convolution::CheckModelAndIo(), ComputationGraphBuilder::Compute(), kaldi::nnet3::ConstrainOrthonormal(), CuCompressedMatrixTestNonnegative(), CuCompressedMatrixTestSign(), CuCompressedMatrixTestSymmetric(), fst::EqualAlign(), kaldi::nnet3::FindNStride(), GenerateCompactLatticeRandomly(), kaldi::nnet3::GenerateConfigSequence(), kaldi::nnet3::GenerateConfigSequenceCnnNew(), kaldi::nnet3::GenerateConfigSequenceCompositeBlock(), kaldi::nnet3::GenerateConfigSequenceDistribute(), kaldi::nnet3::GenerateConfigSequenceLstmType2(), kaldi::nnet3::GenerateConfigSequenceLstmWithTruncation(), kaldi::nnet3::GenerateConfigSequenceRestrictedAttention(), kaldi::nnet3::GenerateConfigSequenceRnn(), kaldi::nnet3::GenerateConfigSequenceSimple(), kaldi::nnet3::GenerateConfigSequenceSimpleContext(), kaldi::nnet3::GenerateConfigSequenceStatistics(), GenerateLexicon(), GeneratePathThroughHmm(), kaldi::nnet3::GenerateRandomComponentConfig(), kaldi::nnet3::GenerateSimpleNnetTrainingExample(), GenerateWordAndPhoneSequence(), GenRandTopology(), GetBootstrapWERInterval(), GetBootstrapWERTwoSystemComparison(), UtteranceSplitter::GetChunkSizesForUtterance(), GeneralDropoutComponent::GetMemo(), SpecAugmentTimeMaskComponent::GetMemo(), kaldi::nnet3::GetNumNvalues(), NnetComputer::GetPointers(), kaldi::nnet3::time_height_convolution::GetRandomConvolutionIndexes(), kaldi::nnet3::time_height_convolution::GetRandomConvolutionModel(), InitGmmFromRandomFrames(), Questions::InitRand(), kaldi::nnet3::InsertCommands(), main(), PlaceNansInGaps(), TdnnComponent::PrecomputeIndexes(), kaldi::nnet3::ProcessFile(), kaldi::nnet3::SelectFromExample(), kaldi::nnet3::SetDerivTimesOptions(), NonlinearComponent::StoreBackpropStats(), RestrictedAttentionComponent::StoreStats(), SigmoidComponent::StoreStats(), TanhComponent::StoreStats(), RectifiedLinearComponent::StoreStats(), NnetDiscriminativeSupervision::Swap(), NnetChainSupervision::Swap(), TestAccumulateTreeStatsOptions(), TestAmDiagGmmAccsIO(), kaldi::nnet3::attention::TestAttentionForwardBackward(), kaldi::nnet3::time_height_convolution::TestComputationIo(), TestConvertAlignment(), TestCuMatrixResize(), TestCuVectorApplyCeiling(), TestCuVectorApplyCeilingNoCount(), TestCuVectorApplyFloor(), TestCuVectorApplyFloorNoCount(), TestDoTableSplit(), TestFindAllKeys(), TestHmmTopology(), TestMllrAccsIO(), kaldi::nnet3::TestNnetDecodable(), TestOnlineMfcc(), kaldi::nnet3::time_height_convolution::TestParamsBackprop(), TestPossibleValues(), TestPosteriorIo(), TestSgmm2Fmllr(), kaldi::nnet3::TestSimpleComponentDataDerivative(), kaldi::nnet3::TestSimpleComponentModelDerivative(), kaldi::nnet3::TestSimpleComponentPropagateProperties(), TestSplitToPhones(), TestWordAlignLatticeLexicon(), UnitTestAddMatMatNans(), UnitTestAmDiagGmm(), UnitTestApplyExpSpecial(), kaldi::nnet3::attention::UnitTestAttentionDotProductAndAddScales(), UnitTestBackpropLstmNonlinearity(), kaldi::nnet3::UnitTestCindexIo(), UnitTestCompressedMatrix(), UnitTestCompressedMatrix2(), UnitTestCuDiffLogSoftmax(), UnitTestCuDiffSoftmax(), UnitTestCuMathComputeLstmNonlinearity(), UnitTestCuMatrixAddMatBlocks1(), UnitTestCuMatrixAddMatBlocks1Trans(), UnitTestCuMatrixAddMatBlocks2(), UnitTestCuVectorSum(), UnitTestDiagGmm(), UnitTestDivideRoundingDown(), kaldi::nnet3::UnitTestEnsureContiguousProperty(), UnitTestEnsureNonzero(), UnitTestEstimateLda(), UnitTestEstimateMmieDiagGmm(), UnitTestEstimateSgmm2(), UnitTestFullGmm(), UnitTestGeneralMatrix(), kaldi::nnet3::UnitTestHasContiguousProperty(), kaldi::nnet3::UnitTestIndexIo(), UnitTestIo(), UnitTestLstmNonlinearity(), UnitTestMatrixAddMatSmat(), UnitTestMatrixAddSmatMat(), UnitTestMleAmDiagGmm(), kaldi::nnet3::UnitTestNnetAnalyze(), kaldi::nnet3::UnitTestNnetCompileLooped(), kaldi::nnet3::UnitTestNnetCompute(), kaldi::nnet3::UnitTestNnetExample(), kaldi::nnet3::UnitTestNnetInputDerivatives(), kaldi::nnet3::UnitTestNnetMergeExamples(), kaldi::nnet3::UnitTestNnetModelDerivatives(), kaldi::nnet3::UnitTestNnetOptimizeInternal(), kaldi::nnet3::UnitTestNnetOptimizeWithOptions(), kaldi::nnet2::UnitTestPreconditionDirectionsOnline(), kaldi::nnet3::UnitTestPreconditionDirectionsOnline(), UnitTestRand(), UnitTestRangesMatrix(), UnitTestRegressionTree(), UnitTestRegtreeMllrDiagGmm(), UnitTestSgmm2(), UnitTestSparseMatrixConstructor(), UnitTestSparseVectorMax(), kaldi::nnet2::UnitTestSpliceComponent(), UnitTestTableSequentialBaseFloatVectorBoth(), UnitTestTableSequentialBool(), UnitTestTableSequentialDouble(), UnitTestTableSequentialDoubleBoth(), UnitTestTableSequentialInt32(), UnitTestTableSequentialInt32PairVectorBoth(), UnitTestTableSequentialInt32Script(), UnitTestTableSequentialInt32VectorBoth(), and kaldi::nnet3::time_height_convolution::UnitTestTimeHeightConvolutionIo().

95  {
96  // This is not exact.
97  KALDI_ASSERT(max_val >= min_val);
98  if (max_val == min_val) return min_val;
99 
100 #ifdef _MSC_VER
101  // RAND_MAX is quite small on Windows -> may need to handle larger numbers.
102  if (RAND_MAX > (max_val-min_val)*8) {
103  // *8 to avoid large inaccuracies in probability, from the modulus...
104  return min_val +
105  ((unsigned int)Rand(state) % (unsigned int)(max_val+1-min_val));
106  } else {
107  if ((unsigned int)(RAND_MAX*RAND_MAX) >
108  (unsigned int)((max_val+1-min_val)*8)) {
109  // *8 to avoid inaccuracies in probability, from the modulus...
110  return min_val + ( (unsigned int)( (Rand(state)+RAND_MAX*Rand(state)))
111  % (unsigned int)(max_val+1-min_val));
112  } else {
113  KALDI_ERR << "rand_int failed because we do not support such large "
114  "random numbers. (Extend this function).";
115  }
116  }
117 #else
118  return min_val +
119  (static_cast<int32>(Rand(state)) % static_cast<int32>(max_val+1-min_val));
120 #endif
121 }
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RandLattice()

Lattice* kaldi::RandLattice ( )

Definition at line 36 of file kaldi-lattice-test.cc.

Referenced by TestLatticeTable(), and TestLatticeTableCross().

36  {
37  Lattice *fst = fst::RandPairFst<LatticeArc>();
38  return fst;
39 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44

◆ RandomEventMap()

EventMap* kaldi::RandomEventMap ( const std::vector< EventKeyType > &  keys)

Definition at line 145 of file event-map-test.cc.

References CopySetToVector(), rnnlm::i, KALDI_ASSERT, kMaxVal, Rand(), RandPoisson(), and RandUniform().

Referenced by TestEventMapIo(), TestEventMapMapValues(), and TestEventMapPrune().

145  {
146  // Do not mess with the probabilities inside this routine or there
147  // is a danger this function will blow up.
148  int32 max_val = kMaxVal;
149  KALDI_ASSERT(keys.size() != 0);
150  float f = RandUniform();
151  if (f < 0.333) { // w.p. 0.333, return ConstantEventMap.
152  return new ConstantEventMap(Rand() % max_val);
153  } else if (f < 0.666) { // w.p. 0.333, return TableEventMap.
154  float nonnull_prob = 0.3; // prob of a non-NULL pointer.
155  float expected_table_size = 3.0;
156  int32 table_size = RandPoisson(expected_table_size);
157  // fertility from this branch is 0.333 * 3.0 * 0.2333 = 0.3.
158  EventKeyType key = keys[Rand() % keys.size()];
159  std::vector<EventMap*> table(table_size);
160  for (size_t t = 0; t < (size_t)table_size; t++) {
161  if (RandUniform() < nonnull_prob) table[t] = RandomEventMap(keys);
162  else table[t] = NULL;
163  }
164  return new TableEventMap(key, table);
165  } else { // w.p. 0.333, return SplitEventMap.
166  // Fertility of this stage is 0.333 * 2 = 0.666.
167  EventKeyType key = keys[Rand() % keys.size()];
168  std::set<EventValueType> yes_set;
169  for (size_t i = 0; i < 5; i++) yes_set.insert(Rand() % max_val);
170  std::vector<EventValueType> yes_vec;
171  CopySetToVector(yes_set, &yes_vec);
172  EventMap *yes = RandomEventMap(keys), *no = RandomEventMap(keys);
173  return new SplitEventMap(key, yes_vec, yes, no);
174  }
175  // total fertility is 0.3 + 0.666 = 0.9666, hence this will terminate with finite memory (w.p.1)
176 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
const int32 kMaxVal
kaldi::int32 int32
int32 RandPoisson(float lambda, struct RandomState *state)
Definition: kaldi-math.cc:126
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
EventMap * RandomEventMap(const std::vector< EventKeyType > &keys)

◆ RandomizeVector()

void kaldi::RandomizeVector ( std::vector< T > *  v)

Definition at line 754 of file kaldi-table-test.cc.

References rnnlm::i, rnnlm::j, Rand(), and swap().

Referenced by UnitTestTableRandomBothDouble(), and UnitTestTableRandomBothDoubleMatrix().

754  {
755  if (v->size() > 1) {
756  for (size_t i = 0; i < 10; i++) {
757  size_t j = Rand() % v->size(),
758  k = Rand() % v->size();
759  if (j != k)
760  std::swap((*v)[j], (*v)[k]);
761  }
762  }
763 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ RandomSplit()

bool kaldi::RandomSplit ( int32  wav_dim,
std::vector< int32 > *  piece_dim,
int32  num_pieces,
int32  trials = 5 
)

Definition at line 57 of file online-feature-test.cc.

References rnnlm::i.

Referenced by TestOnlineAppendFeature(), TestOnlineMfcc(), and TestOnlinePlp().

60  {
61  piece_dim->clear();
62  piece_dim->resize(num_pieces, 0);
63 
64  int32 dim_mean = wav_dim / (num_pieces * 2);
65  int32 cnt = 0;
66  while (true) {
67  int32 dim_total = 0;
68  for (int32 i = 0; i < num_pieces - 1; i++) {
69  (*piece_dim)[i] = dim_mean + rand() % dim_mean;
70  dim_total += (*piece_dim)[i];
71  }
72  (*piece_dim)[num_pieces - 1] = wav_dim - dim_total;
73 
74  if (dim_total > 0 && dim_total < wav_dim)
75  break;
76  if (++cnt > trials)
77  return false;
78  }
79  return true;
80 }
kaldi::int32 int32

◆ RandPoisson()

int32 RandPoisson ( float  lambda,
struct RandomState state 
)

Definition at line 126 of file kaldi-math.cc.

References KALDI_ASSERT, and RandUniform().

Referenced by RandGauss(), RandomEventMap(), and UnitTestRand().

126  {
127  // Knuth's algorithm.
128  KALDI_ASSERT(lambda >= 0);
129  float L = expf(-lambda), p = 1.0;
130  int32 k = 0;
131  do {
132  k++;
133  float u = RandUniform(state);
134  p *= u;
135  } while (p > L);
136  return k-1;
137 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RandPosdefSpMatrix()

void kaldi::RandPosdefSpMatrix ( MatrixIndexT  dim,
SpMatrix< Real > *  matrix 
)

Definition at line 36 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), TpMatrix< Real >::Cholesky(), KALDI_LOG, kNoTrans, and Rand().

Referenced by UnitTestFullGmm(), UnitTestLbfgs(), UnitTestLinearCgd(), and UnitTestSolve().

36  {
37  MatrixIndexT dim2 = dim + (Rand() % 3); // slightly higher-dim.
38  // generate random (non-singular) matrix
39  Matrix<Real> tmp(dim, dim2);
40  while (1) {
41  tmp.SetRandn();
42  if (tmp.Cond() < 100) break;
43  KALDI_LOG << "Condition number of random matrix large "
44  << static_cast<float>(tmp.Cond())
45  << ", trying again (this is normal)";
46  }
47  // tmp * tmp^T will give positive definite matrix
48  matrix->AddMat2(1.0, tmp, kNoTrans, 0.0);
49 
50  // Checks that the matrix is indeed pos-def
51  TpMatrix<Real> sqrt(dim);
52  sqrt.Cholesky(*matrix);
53 }
void AddMat2(const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transM, const Real beta)
rank-N update: if (transM == kNoTrans) (*this) = beta*(*this) + alpha * M * M^T, or (if transM == kTr...
Definition: sp-matrix.cc:1110
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ RandPrune()

Float kaldi::RandPrune ( Float  post,
BaseFloat  prune_thresh,
struct RandomState state = NULL 
)
inline

Definition at line 174 of file kaldi-math.h.

References KALDI_ASSERT, and RandUniform().

Referenced by NnetLdaStatsAccumulator::AccStatsFromOutput(), MlltAccs::AccumulateFromPosteriors(), MleAmSgmm2Accs::AccumulateFromPosteriors(), MleSgmm2SpeakerAccs::AccumulateFromPosteriors(), main(), and UnitTestRand().

175  {
176  KALDI_ASSERT(prune_thresh >= 0.0);
177  if (post == 0.0 || std::abs(post) >= prune_thresh)
178  return post;
179  return (post >= 0 ? 1.0 : -1.0) *
180  (RandUniform(state) <= fabs(post)/prune_thresh ? prune_thresh : 0.0);
181 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RandUniform()

float kaldi::RandUniform ( struct RandomState state = NULL)
inline

Returns a random number strictly between 0 and 1.

Definition at line 151 of file kaldi-math.h.

References Rand().

Referenced by CuRand< float >::BinarizeProbs(), LstmNonlinearityComponent::ConsolidateMemory(), DiagGmm::Generate(), kaldi::nnet3::GenerateRandomComponentConfig(), kaldi::nnet3::GenerateSimpleNnetTrainingExample(), GenRandContextDependency(), GenRandContextDependencyLarge(), fst::GenRandPhoneSeq(), GenRandStats(), GeneralDropoutComponent::GetMemo(), init_rand_diag_gmm(), kaldi::unittest::InitRandFullGmm(), InitRandomGmm(), PitchInterpolator::InitValues(), main(), kaldi::nnet3::PerturbImage(), DropoutMaskComponent::Propagate(), DropoutComponent::Propagate(), AdditiveNoiseComponent::Propagate(), rand_diag_gmm(), VectorBase< float >::RandCategorical(), RandGauss(), RandGauss2(), RandomEventMap(), RandPoisson(), RandPrune(), RandZeroToOneMatrix(), SigmoidComponent::RepairGradients(), TanhComponent::RepairGradients(), RectifiedLinearComponent::RepairGradients(), ClipGradientComponent::RepairGradients(), VectorBase< float >::SetRandUniform(), MatrixBase< float >::SetRandUniform(), TestBuildTree(), TestClusterBottomUp(), TestClusterEventMap(), TestClusterEventMapGetMappingAndRenumberEventMap(), TestClusterEventMapGetMappingAndRenumberEventMap2(), TestClusterEventMapRestricted(), TestClustering(), TestClusterKMeans(), TestClusterTopDown(), TestClusterUtilsVector(), fst::TestContextFst(), TestCuMatrixCompObjfAndDeriv(), fst::TestFactor(), TestGenRandStats(), TestPosteriorIo(), TestRefineClusters(), fst::TestRemoveEpsLocal(), TestSgmm2AccsIO(), TestSgmm2Substates(), TestShareEventMapLeaves(), TestSplitStates(), TestTreeCluster(), TestVectorToPosteriorEntry(), UnitTestArbitraryResample(), UnitTestCuMatrixObjfDeriv(), UnitTestDiagGmm(), UnitTestFullGmm(), UnitTestIo(), UnitTestIoNew(), UnitTestIoPipe(), UnitTestLinearResample(), UnitTestRand(), UnitTestRegtreeFmllrDiagGmm(), UnitTestSimpleForVec(), and UnitTestVtln().

151  {
152  return static_cast<float>((Rand(state) + 1.0) / (RAND_MAX+2.0));
153 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ RandZeroToOneMatrix()

static void kaldi::RandZeroToOneMatrix ( MatrixBase< Real > *  mat)
static

Definition at line 64 of file cu-matrix-test.cc.

References MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and RandUniform().

Referenced by UnitTestCuDiffLogSoftmax(), UnitTestCuDiffSigmoid(), UnitTestCuDiffSoftmax(), UnitTestCuDiffTanh(), and UnitTestCuDiffXent().

64  {
65  for(int32 r=0; r<mat->NumRows(); r++)
66  for(int32 c=0; c<mat->NumCols(); c++)
67  (*mat)(r,c) = RandUniform();
68 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ReadCommaSeparatedCommand()

void kaldi::ReadCommaSeparatedCommand ( const std::string &  s,
std::vector< BaseFloat > *  v 
)

Definition at line 119 of file wav-reverberate.cc.

References ConvertStringToReal(), rnnlm::i, and SplitStringToVector().

Referenced by main().

120  {
121  std::vector<std::string> split_string;
122  SplitStringToVector(s, ",", true, &split_string);
123  for (size_t i = 0; i < split_string.size(); i++) {
124  float ret;
125  ConvertStringToReal(split_string[i], &ret);
126  v->push_back(ret);
127  }
128 }
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
bool ConvertStringToReal(const std::string &str, T *out)
ConvertStringToReal converts a string into either float or double and returns false if there was any ...
Definition: text-utils.cc:238

◆ ReadCompactLattice()

bool ReadCompactLattice ( std::istream &  is,
bool  binary,
CompactLattice **  clat 
)

Definition at line 304 of file kaldi-lattice.cc.

References ConvertToCompactLattice(), KALDI_ASSERT, KALDI_WARN, and ReadCompactLatticeText().

Referenced by CompactLatticeHolder::Read(), and DiscriminativeNnetExample::Read().

305  {
306  KALDI_ASSERT(*clat == NULL);
307  if (binary) {
308  fst::FstHeader hdr;
309  if (!hdr.Read(is, "<unknown>")) {
310  KALDI_WARN << "Reading compact lattice: error reading FST header.";
311  return false;
312  }
313  if (hdr.FstType() != "vector") {
314  KALDI_WARN << "Reading compact lattice: unsupported FST type: "
315  << hdr.FstType();
316  return false;
317  }
318  fst::FstReadOptions ropts("<unspecified>",
319  &hdr);
320 
323  typedef fst::LatticeWeightTpl<float> T3;
325  typedef fst::VectorFst<fst::ArcTpl<T1> > F1;
326  typedef fst::VectorFst<fst::ArcTpl<T2> > F2;
327  typedef fst::VectorFst<fst::ArcTpl<T3> > F3;
328  typedef fst::VectorFst<fst::ArcTpl<T4> > F4;
329 
330  CompactLattice *ans = NULL;
331  if (hdr.ArcType() == T1::Type()) {
332  ans = ConvertToCompactLattice(F1::Read(is, ropts));
333  } else if (hdr.ArcType() == T2::Type()) {
334  ans = ConvertToCompactLattice(F2::Read(is, ropts));
335  } else if (hdr.ArcType() == T3::Type()) {
336  ans = ConvertToCompactLattice(F3::Read(is, ropts));
337  } else if (hdr.ArcType() == T4::Type()) {
338  ans = ConvertToCompactLattice(F4::Read(is, ropts));
339  } else {
340  KALDI_WARN << "FST with arc type " << hdr.ArcType()
341  << " cannot be converted to CompactLattice.\n";
342  return false;
343  }
344  if (ans == NULL) {
345  KALDI_WARN << "Error reading compact lattice (after reading header).";
346  return false;
347  }
348  *clat = ans;
349  return true;
350  } else {
351  // The next line would normally consume the \r on Windows, plus any
352  // extra spaces that might have got in there somehow.
353  while (std::isspace(is.peek()) && is.peek() != '\n') is.get();
354  if (is.peek() == '\n') is.get(); // consume the newline.
355  else { // saw spaces but no newline.. this is not expected.
356  KALDI_WARN << "Reading compact lattice: unexpected sequence of spaces "
357  << " at file position " << is.tellg();
358  return false;
359  }
360  *clat = ReadCompactLatticeText(is); // that routine will warn on error.
361  return (*clat != NULL);
362  }
363 }
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
CompactLattice * ReadCompactLatticeText(std::istream &is)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
CompactLattice * ConvertToCompactLattice(CompactLattice *ifst)

◆ ReadCompactLatticeText()

CompactLattice* kaldi::ReadCompactLatticeText ( std::istream &  is)

Definition at line 277 of file kaldi-lattice.cc.

References ConvertToCompactLattice(), and LatticeReader::ReadText().

Referenced by ReadCompactLattice().

277  {
278  std::pair<Lattice*, CompactLattice*> lat_pair = LatticeReader::ReadText(is);
279  if (lat_pair.second != NULL) {
280  delete lat_pair.first;
281  return lat_pair.second;
282  } else if (lat_pair.first != NULL) {
283  // note: ConvertToCompactLattice frees its input.
284  return ConvertToCompactLattice(lat_pair.first);
285  } else {
286  return NULL;
287  }
288 }
CompactLattice * ConvertToCompactLattice(CompactLattice *ifst)

◆ ReadConfigFromFile()

void kaldi::ReadConfigFromFile ( const std::string &  config_filename,
C *  c 
)

This template is provided for convenience in reading config classes from files; this is not the standard way to read configuration options, but may occasionally be needed.

This function assumes the config has a function "void Register(OptionsItf *opts)" which it can call to register the ParseOptions object.

Definition at line 237 of file parse-options.h.

References ParseOptions::Register().

Referenced by OnlineIvectorExtractionInfo::Init(), OnlineFeaturePipelineConfig::OnlineFeaturePipelineConfig(), and OnlineNnet2FeaturePipelineInfo::OnlineNnet2FeaturePipelineInfo().

238  {
239  std::ostringstream usage_str;
240  usage_str << "Parsing config from "
241  << "from '" << config_filename << "'";
242  ParseOptions po(usage_str.str().c_str());
243  c->Register(&po);
244  po.ReadConfigFile(config_filename);
245 }

◆ ReadConfigLines()

void ReadConfigLines ( std::istream &  is,
std::vector< std::string > *  lines 
)

This function reads in a config file and *appends* its contents to a vector of lines; it is responsible for removing comments (anything after '#') and stripping out any lines that contain only whitespace after comment removal.

Definition at line 564 of file text-utils.cc.

References KALDI_ASSERT.

Referenced by Nnet::ReadConfig(), kaldi::nnet3::ReadEditConfig(), and UnitTestReadConfig().

565  {
566  KALDI_ASSERT(lines != NULL);
567  std::string line;
568  while (std::getline(is, line)) {
569  if (line.size() == 0) continue;
570  size_t start = line.find_first_not_of(" \t");
571  size_t end = line.find_first_of('#');
572  if (start == std::string::npos || start == end) continue;
573  end = line.find_last_not_of(" \t", end - 1);
574  KALDI_ASSERT(end >= start);
575  lines->push_back(line.substr(start, end - start + 1));
576  }
577 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ReadConfigsFromFile()

void kaldi::ReadConfigsFromFile ( const std::string &  conf,
C1 *  c1,
C2 *  c2 
)

This variant of the template ReadConfigFromFile is for if you need to read two config classes from the same file.

Definition at line 249 of file parse-options.h.

References ParseOptions::Register().

Referenced by OnlineNnet2FeaturePipelineInfo::OnlineNnet2FeaturePipelineInfo().

250  {
251  std::ostringstream usage_str;
252  usage_str << "Parsing config from "
253  << "from '" << conf << "'";
254  ParseOptions po(usage_str.str().c_str());
255  c1->Register(&po);
256  c2->Register(&po);
257  po.ReadConfigFile(conf);
258 }

◆ ReadData()

bool kaldi::ReadData ( SequentialBaseFloatMatrixReader feature_reader,
RandomAccessPosteriorReader target_reader,
RandomAccessBaseFloatVectorReader weights_reader,
int32  length_tolerance,
Matrix< BaseFloat > *  feats,
Posterior targets,
Vector< BaseFloat > *  weights,
int32 num_no_tgt_mat,
int32 num_other_error 
)

Definition at line 35 of file nnet-train-multistream.cc.

References VectorBase< Real >::Dim(), SequentialTableReader< Holder >::Done(), RandomAccessTableReader< Holder >::HasKey(), RandomAccessTableReader< Holder >::IsOpen(), KALDI_VLOG, KALDI_WARN, kCopyData, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Vector< Real >::Resize(), Matrix< Real >::Resize(), VectorBase< Real >::Set(), RandomAccessTableReader< Holder >::Value(), and SequentialTableReader< Holder >::Value().

Referenced by main().

43  {
44 
45  // We're looking for the 1st valid utterance...
46  for ( ; !feature_reader.Done(); feature_reader.Next()) {
47  // Do we have targets?
48  const std::string& utt = feature_reader.Key();
49  KALDI_VLOG(3) << "Reading: " << utt;
50  if (!target_reader.HasKey(utt)) {
51  KALDI_WARN << utt << ", missing targets";
52  (*num_no_tgt_mat)++;
53  continue;
54  }
55  // Do we have frame-weights?
56  if (weights_reader.IsOpen() && !weights_reader.HasKey(utt)) {
57  KALDI_WARN << utt << ", missing frame-weights";
58  (*num_other_error)++;
59  continue;
60  }
61 
62  // get the (feature,target) pair,
63  (*feats) = feature_reader.Value();
64  (*targets) = target_reader.Value(utt);
65 
66  // getting per-frame weights,
67  if (weights_reader.IsOpen()) {
68  (*weights) = weights_reader.Value(utt);
69  } else { // all per-frame weights are 1.0
70  weights->Resize(feats->NumRows());
71  weights->Set(1.0);
72  }
73 
74  // correct small length mismatch ... or drop sentence
75  {
76  // add lengths to vector
77  std::vector<int32> length;
78  length.push_back(feats->NumRows());
79  length.push_back(targets->size());
80  length.push_back(weights->Dim());
81  // find min, max
82  int32 min = *std::min_element(length.begin(), length.end());
83  int32 max = *std::max_element(length.begin(), length.end());
84  // fix or drop ?
85  if (max - min < length_tolerance) {
86  if (feats->NumRows() != min) feats->Resize(min, feats->NumCols(), kCopyData);
87  if (targets->size() != min) targets->resize(min);
88  if (weights->Dim() != min) weights->Resize(min, kCopyData);
89  } else {
90  KALDI_WARN << "Length mismatch! Targets " << targets->size()
91  << ", features " << feats->NumRows() << ", " << utt;
92  num_other_error++;
93  continue;
94  }
95  }
96 
97  // By getting here we got a valid utterance,
98  feature_reader.Next();
99  return true;
100  }
101 
102  // No more data,
103  return false;
104 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
const T & Value(const std::string &key)
#define KALDI_WARN
Definition: kaldi-error.h:150
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
bool HasKey(const std::string &key)
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Set(Real f)
Set all members of a vector to a specified value.
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ ReadDecodeGraph()

fst::Fst< fst::StdArc > * ReadDecodeGraph ( const std::string &  filename)

Definition at line 27 of file onlinebin-util.cc.

References KALDI_ERR, and Input::Stream().

Referenced by main().

27  {
28  // read decoding network FST
29  Input ki(filename); // use ki.Stream() instead of is.
30  if (!ki.Stream().good()) KALDI_ERR << "Could not open decoding-graph FST "
31  << filename;
32 
33  fst::FstHeader hdr;
34  if (!hdr.Read(ki.Stream(), "<unknown>")) {
35  KALDI_ERR << "Reading FST: error reading FST header.";
36  }
37  if (hdr.ArcType() != fst::StdArc::Type()) {
38  KALDI_ERR << "FST with arc type " << hdr.ArcType() << " not supported.";
39  }
40  fst::FstReadOptions ropts("<unspecified>", &hdr);
41 
42  fst::Fst<fst::StdArc> *decode_fst = NULL;
43 
44  if (hdr.FstType() == "vector") {
45  decode_fst = fst::VectorFst<fst::StdArc>::Read(ki.Stream(), ropts);
46  } else if (hdr.FstType() == "const") {
47  decode_fst = fst::ConstFst<fst::StdArc>::Read(ki.Stream(), ropts);
48  } else {
49  KALDI_ERR << "Reading FST: unsupported FST type: " << hdr.FstType();
50  }
51  if (decode_fst == NULL) { // fst code will warn.
52  KALDI_ERR << "Error reading FST (after reading header).";
53  return NULL;
54  } else {
55  return decode_fst;
56  }
57 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ ReadEventType()

void ReadEventType ( std::istream &  is,
bool  binary,
EventType evec 
)

Definition at line 239 of file event-map.cc.

References ExpectToken(), rnnlm::i, KALDI_ASSERT, and ReadBasicType().

Referenced by MakeEventPair(), ReadBuildTreeStats(), and TestEventTypeIo().

239  {
240  KALDI_ASSERT(evec != NULL);
241  ExpectToken(is, binary, "EV");
242  uint32 size;
243  ReadBasicType(is, binary, &size);
244  evec->resize(size);
245  for (size_t i = 0; i < size; i++) {
246  ReadBasicType(is, binary, &( (*evec)[i].first ));
247  ReadBasicType(is, binary, &( (*evec)[i].second ));
248  }
249 }
void ReadBasicType(std::istream &is, bool binary, T *t)
ReadBasicType is the name of the read function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:55
void ExpectToken(std::istream &is, bool binary, const char *token)
ExpectToken tries to read in the given token, and throws an exception on failure. ...
Definition: io-funcs.cc:191
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ReadHtk() [1/2]

template bool kaldi::ReadHtk ( std::istream &  is,
Matrix< float > *  M,
HtkHeader header_ptr 
)

◆ ReadHtk() [2/2]

template bool kaldi::ReadHtk ( std::istream &  is,
Matrix< double > *  M,
HtkHeader header_ptr 
)

Referenced by ReadHtk().

◆ ReadIntegerVectorSimple()

bool ReadIntegerVectorSimple ( const std::string &  rxfilename,
std::vector< int32 > *  v 
)

ReadFromList attempts to read this list of integers, one per line, from the given file, in text format.

returns true if succeeded.

Definition at line 33 of file simple-io-funcs.cc.

References rnnlm::i, Input::OpenTextMode(), and Input::Stream().

Referenced by main().

34  {
35  kaldi::Input ki;
36  if (!ki.OpenTextMode(rxfilename)) return false;
37  std::istream &is = ki.Stream();
38  int32 i;
39  list->clear();
40  while ( !(is >> i).fail() )
41  list->push_back(i);
42  is >> std::ws;
43  return is.eof(); // should be eof, or junk at end of file.
44 }
kaldi::int32 int32
bool OpenTextMode(const std::string &rxfilename)
Definition: kaldi-io-inl.h:30
std::istream & Stream()
Definition: kaldi-io.cc:826

◆ ReadIntegerVectorVectorSimple()

bool ReadIntegerVectorVectorSimple ( const std::string &  rxfilename,
std::vector< std::vector< int32 > > *  list 
)

Definition at line 62 of file simple-io-funcs.cc.

References Input::OpenTextMode(), SplitStringToIntegers(), and Input::Stream().

Referenced by main(), and ReadPhoneMap().

63  {
64  kaldi::Input ki;
65  if (!ki.OpenTextMode(rxfilename)) return false;
66  std::istream &is = ki.Stream();
67  list->clear();
68  std::string line;
69  while (std::getline(is, line)) {
70  std::vector<int32> v;
71  if (!SplitStringToIntegers(line, " \t\r", true, &v)) {
72  list->clear();
73  return false;
74  }
75  list->push_back(v);
76  }
77  return is.eof(); // if we're not at EOF, something weird happened.
78 }
bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
Split a string (e.g.
Definition: text-utils.h:68
bool OpenTextMode(const std::string &rxfilename)
Definition: kaldi-io-inl.h:30
std::istream & Stream()
Definition: kaldi-io.cc:826

◆ ReadLattice()

bool ReadLattice ( std::istream &  is,
bool  binary,
Lattice **  lat 
)

Definition at line 417 of file kaldi-lattice.cc.

References ConvertToLattice(), KALDI_ASSERT, KALDI_WARN, and ReadLatticeText().

Referenced by LatticeHolder::Read(), and DiscriminativeSupervision::Read().

418  {
419  KALDI_ASSERT(*lat == NULL);
420  if (binary) {
421  fst::FstHeader hdr;
422  if (!hdr.Read(is, "<unknown>")) {
423  KALDI_WARN << "Reading lattice: error reading FST header.";
424  return false;
425  }
426  if (hdr.FstType() != "vector") {
427  KALDI_WARN << "Reading lattice: unsupported FST type: "
428  << hdr.FstType();
429  return false;
430  }
431  fst::FstReadOptions ropts("<unspecified>",
432  &hdr);
433 
436  typedef fst::LatticeWeightTpl<float> T3;
438  typedef fst::VectorFst<fst::ArcTpl<T1> > F1;
439  typedef fst::VectorFst<fst::ArcTpl<T2> > F2;
440  typedef fst::VectorFst<fst::ArcTpl<T3> > F3;
441  typedef fst::VectorFst<fst::ArcTpl<T4> > F4;
442 
443  Lattice *ans = NULL;
444  if (hdr.ArcType() == T1::Type()) {
445  ans = ConvertToLattice(F1::Read(is, ropts));
446  } else if (hdr.ArcType() == T2::Type()) {
447  ans = ConvertToLattice(F2::Read(is, ropts));
448  } else if (hdr.ArcType() == T3::Type()) {
449  ans = ConvertToLattice(F3::Read(is, ropts));
450  } else if (hdr.ArcType() == T4::Type()) {
451  ans = ConvertToLattice(F4::Read(is, ropts));
452  } else {
453  KALDI_WARN << "FST with arc type " << hdr.ArcType()
454  << " cannot be converted to Lattice.\n";
455  return false;
456  }
457  if (ans == NULL) {
458  KALDI_WARN << "Error reading lattice (after reading header).";
459  return false;
460  }
461  *lat = ans;
462  return true;
463  } else {
464  // The next line would normally consume the \r on Windows, plus any
465  // extra spaces that might have got in there somehow.
466  while (std::isspace(is.peek()) && is.peek() != '\n') is.get();
467  if (is.peek() == '\n') is.get(); // consume the newline.
468  else { // saw spaces but no newline.. this is not expected.
469  KALDI_WARN << "Reading compact lattice: unexpected sequence of spaces "
470  << " at file position " << is.tellg();
471  return false;
472  }
473  *lat = ReadLatticeText(is); // that routine will warn on error.
474  return (*lat != NULL);
475  }
476 }
Lattice * ConvertToLattice(Lattice *ifst)
kaldi::int32 int32
Lattice * ReadLatticeText(std::istream &is)
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ReadLatticeText()

Lattice* kaldi::ReadLatticeText ( std::istream &  is)

Definition at line 291 of file kaldi-lattice.cc.

References ConvertToLattice(), and LatticeReader::ReadText().

Referenced by ReadLattice().

291  {
292  std::pair<Lattice*, CompactLattice*> lat_pair = LatticeReader::ReadText(is);
293  if (lat_pair.first != NULL) {
294  delete lat_pair.second;
295  return lat_pair.first;
296  } else if (lat_pair.second != NULL) {
297  // note: ConvertToLattice frees its input.
298  return ConvertToLattice(lat_pair.second);
299  } else {
300  return NULL;
301  }
302 }
Lattice * ConvertToLattice(Lattice *ifst)

◆ ReadLexiconForWordAlign()

bool ReadLexiconForWordAlign ( std::istream &  is,
std::vector< std::vector< int32 > > *  lexicon 
)

Read the lexicon in the special format required for word alignment.

Each line has a series of integers on it (at least two on each line), representing:

<old-word-id> <new-word-id> [<phone-id-1> [<phone-id-2> ... ] ]

Here, <old-word-id> is the word-id that appears in the lattice before alignment, and <new-word-id> is the word-is that should appear in the lattice after alignment. This is mainly useful when the lattice may have no symbol for the optional-silence arcs (so <old-word-id> would equal zero), but we want it to be output with a symbol on those arcs (so <new-word-id> would be nonzero). If the silence should not be added to the lattice, both <old-word-id> and <new-word-id> may be zero.

This function is very simple: it just reads in a series of lines from a text file, each with at least two integers on them.

Definition at line 1051 of file word-align-lattice-lexicon.cc.

References KALDI_WARN, and SplitStringToIntegers().

Referenced by main().

1052  {
1053  lexicon->clear();
1054  std::string line;
1055  while (std::getline(is, line)) {
1056  std::vector<int32> this_entry;
1057  if (!SplitStringToIntegers(line, " \t\r", false, &this_entry) ||
1058  this_entry.size() < 2) {
1059  KALDI_WARN << "Lexicon line '" << line << "' is invalid";
1060  return false;
1061  }
1062  lexicon->push_back(this_entry);
1063  }
1064  return (!lexicon->empty());
1065 }
bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
Split a string (e.g.
Definition: text-utils.h:68
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ ReadLine()

bool ReadLine ( int32  desc,
std::string *  str 
)

Definition at line 359 of file online-audio-client.cc.

References buffer_fill, buffer_offset, and rnnlm::i.

Referenced by main().

359  {
360  *str = "";
361 
362  while (true) {
363  if (buffer_offset >= buffer_fill) {
364  buffer_fill = read(desc, read_buffer, 1024);
365 
366  if (buffer_fill <= 0)
367  break;
368 
369  buffer_offset = 0;
370  }
371 
372  for (int32 i = buffer_offset; i < buffer_fill; i++) {
373  if (read_buffer[i] == '\r' || read_buffer[i] == '\n') {
374  read_buffer[i] = 0;
375  *str += (read_buffer + buffer_offset);
376 
377  buffer_offset = i + 1;
378 
379  if (i < buffer_fill) {
380  if (read_buffer[i] == '\n' && read_buffer[i + 1] == '\r') {
381  read_buffer[i + 1] = 0;
382  buffer_offset = i + 2;
383  }
384  if (read_buffer[i] == '\r' && read_buffer[i + 1] == '\n') {
385  read_buffer[i + 1] = 0;
386  buffer_offset = i + 2;
387  }
388  }
389 
390  return true;
391  }
392  }
393 
395  *str += (read_buffer + buffer_offset);
397  }
398 
399  return false;
400 }
kaldi::int32 int32
int32 buffer_offset
char read_buffer[1025]

◆ ReadModels()

void kaldi::ReadModels ( std::vector< std::pair< std::string, BaseFloat > >  models_and_weights,
nnet3::Nnet output_nnet,
int32 success 
)

Definition at line 57 of file nnet3-average.cc.

References kaldi::nnet3::AddNnet(), rnnlm::i, rnnlm::n, ReadKaldiObject(), and kaldi::nnet3::ScaleNnet().

Referenced by main().

59  {
60  using namespace nnet3;
61  try {
62  int32 n = models_and_weights.size();
63  ReadKaldiObject(models_and_weights[0].first, output_nnet);
64  ScaleNnet(models_and_weights[0].second, output_nnet);
65  for (int32 i = 1; i < n; i++) {
66  Nnet nnet;
67  ReadKaldiObject(models_and_weights[i].first, &nnet);
68  AddNnet(nnet, models_and_weights[i].second, output_nnet);
69  }
70  *success = 1;
71  } catch (...) {
72  *success = 0;
73  }
74 }
void ScaleNnet(BaseFloat scale, Nnet *nnet)
Scales the nnet parameters and stats by this scale.
Definition: nnet-utils.cc:312
kaldi::int32 int32
void ReadKaldiObject(const std::string &filename, Matrix< float > *m)
Definition: kaldi-io.cc:832
struct rnnlm::@11::@12 n
void AddNnet(const Nnet &src, BaseFloat alpha, Nnet *dest)
Does *dest += alpha * src (affects nnet parameters and stored stats).
Definition: nnet-utils.cc:349

◆ ReadNetwork()

fst::Fst< fst::StdArc > * ReadNetwork ( std::string  filename)

Definition at line 32 of file gmm-decode-biglm-faster.cc.

References KALDI_ERR, and Input::Stream().

Referenced by main().

32  {
33  // read decoding network FST
34  Input ki(filename); // use ki.Stream() instead of is.
35  if (!ki.Stream().good()) KALDI_ERR << "Could not open decoding-graph FST "
36  << filename;
37 
38  fst::FstHeader hdr;
39  if (!hdr.Read(ki.Stream(), "<unknown>")) {
40  KALDI_ERR << "Reading FST: error reading FST header.";
41  }
42  if (hdr.ArcType() != fst::StdArc::Type()) {
43  KALDI_ERR << "FST with arc type " << hdr.ArcType() << " not supported.";
44  }
45  fst::FstReadOptions ropts("<unspecified>", &hdr);
46 
47  fst::Fst<fst::StdArc> *decode_fst = NULL;
48 
49  if (hdr.FstType() == "vector") {
50  decode_fst = fst::VectorFst<fst::StdArc>::Read(ki.Stream(), ropts);
51  } else if (hdr.FstType() == "const") {
52  decode_fst = fst::ConstFst<fst::StdArc>::Read(ki.Stream(), ropts);
53  } else {
54  KALDI_ERR << "Reading FST: unsupported FST type: " << hdr.FstType();
55  }
56  if (decode_fst == NULL) { // fst code will warn.
57  KALDI_ERR << "Error reading FST (after reading header).";
58  return NULL;
59  } else {
60  return decode_fst;
61  }
62 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ ReadPhoneMap()

void ReadPhoneMap ( std::string  phone_map_rxfilename,
std::vector< int32 > *  phone_map 
)

Definition at line 106 of file tree-accu.cc.

References rnnlm::i, KALDI_ASSERT, KALDI_ERR, PrintableRxfilename(), and ReadIntegerVectorVectorSimple().

Referenced by AccumulateTreeStatsInfo::AccumulateTreeStatsInfo(), and main().

107  {
108  phone_map->clear();
109  // phone map file has format e.g.:
110  // 1 1
111  // 2 1
112  // 3 2
113  // 4 2
114  std::vector<std::vector<int32> > vec; // vector of vectors, each with two elements
115  // (if file has right format). first is old phone, second is new phone
116  if (!ReadIntegerVectorVectorSimple(phone_map_rxfilename, &vec))
117  KALDI_ERR << "Error reading phone map from " <<
118  PrintableRxfilename(phone_map_rxfilename);
119  for (size_t i = 0; i < vec.size(); i++) {
120  if (vec[i].size() != 2 || vec[i][0]<=0 || vec[i][1]<=0 ||
121  (vec[i][0]<static_cast<int32>(phone_map->size()) &&
122  (*phone_map)[vec[i][0]] != -1))
123  KALDI_ERR << "Error reading phone map from "
124  << PrintableRxfilename(phone_map_rxfilename)
125  << " (bad line " << i << ")";
126  if (vec[i][0]>=static_cast<int32>(phone_map->size()))
127  phone_map->resize(vec[i][0]+1, -1);
128  KALDI_ASSERT((*phone_map)[vec[i][0]] == -1);
129  (*phone_map)[vec[i][0]] = vec[i][1];
130  }
131  if (phone_map->empty()) {
132  KALDI_ERR << "Read empty phone map from "
133  << PrintableRxfilename(phone_map_rxfilename);
134  }
135 }
kaldi::int32 int32
bool ReadIntegerVectorVectorSimple(const std::string &rxfilename, std::vector< std::vector< int32 > > *list)
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
std::string PrintableRxfilename(const std::string &rxfilename)
PrintableRxfilename turns the rxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:61

◆ ReadSharedPhonesList()

void ReadSharedPhonesList ( std::string  rxfilename,
std::vector< std::vector< int32 > > *  list_out 
)

Definition at line 35 of file gmm-init-biphone.cc.

References IsSortedAndUniq(), KALDI_ERR, PrintableRxfilename(), SplitStringToIntegers(), and Input::Stream().

Referenced by main().

35  {
36  list_out->clear();
37  Input input(rxfilename);
38  std::istream &is = input.Stream();
39  std::string line;
40  while (std::getline(is, line)) {
41  list_out->push_back(std::vector<int32>());
42  if (!SplitStringToIntegers(line, " \t\r", true, &(list_out->back())))
43  KALDI_ERR << "Bad line in shared phones list: " << line << " (reading "
44  << PrintableRxfilename(rxfilename) << ")";
45  std::sort(list_out->rbegin()->begin(), list_out->rbegin()->end());
46  if (!IsSortedAndUniq(*(list_out->rbegin())))
47  KALDI_ERR << "Bad line in shared phones list (repeated phone): " << line
48  << " (reading " << PrintableRxfilename(rxfilename) << ")";
49  }
50 }
bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
Split a string (e.g.
Definition: text-utils.h:68
#define KALDI_ERR
Definition: kaldi-error.h:147
std::string PrintableRxfilename(const std::string &rxfilename)
PrintableRxfilename turns the rxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:61
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ ReadSymbolList()

void kaldi::ReadSymbolList ( const std::string &  rxfilename,
fst::SymbolTable *  word_syms,
LabelPairVector lpairs 
)

Definition at line 35 of file lattice-oracle.cc.

References KALDI_ASSERT, KALDI_ERR, PrintableRxfilename(), and Input::Stream().

Referenced by main().

37  {
38  Input ki(rxfilename);
39  std::string line;
40  KALDI_ASSERT(lpairs != NULL);
41  lpairs->clear();
42  while (getline(ki.Stream(), line)) {
43  std::string sym;
44  std::istringstream ss(line);
45  ss >> sym >> std::ws;
46  if (ss.fail() || !ss.eof()) {
47  KALDI_ERR << "Bad line in symbol list: "<< line
48  << ", file is: " << PrintableRxfilename(rxfilename);
49  }
50  fst::StdArc::Label lab = word_syms->Find(sym.c_str());
51  if (lab == -1) { // fst::kNoSymbol
52  KALDI_ERR << "Can't find symbol in symbol table: "
53  << line << ", file is: "
54  << PrintableRxfilename(rxfilename);
55  }
56  lpairs->emplace_back(lab, 0);
57  }
58 }
fst::StdArc::Label Label
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
std::string PrintableRxfilename(const std::string &rxfilename)
PrintableRxfilename turns the rxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:61

◆ RealFft() [1/2]

template void kaldi::RealFft ( VectorBase< float > *  v,
bool  forward 
)

◆ RealFft() [2/2]

template void kaldi::RealFft ( VectorBase< double > *  v,
bool  forward 
)

◆ RealFftInefficient() [1/2]

template void kaldi::RealFftInefficient ( VectorBase< float > *  v,
bool  forward 
)

◆ RealFftInefficient() [2/2]

template void kaldi::RealFftInefficient ( VectorBase< double > *  v,
bool  forward 
)

◆ RegisterCuAllocatorOptions()

void kaldi::RegisterCuAllocatorOptions ( OptionsItf po)
inline

Definition at line 87 of file cu-allocator.h.

References CuAllocatorOptions::Register().

Referenced by main().

87  {
89 }
CuAllocatorOptions g_allocator_options
void Register(OptionsItf *po)
Definition: cu-allocator.h:70

◆ RemoveDuplicates()

static void kaldi::RemoveDuplicates ( std::vector< std::vector< int32 > > *  vecs)
static

Definition at line 533 of file build-tree.cc.

References KALDI_VLOG.

Referenced by ObtainSetsOfPhones().

533  {
534  unordered_set<std::vector<int32>, VectorHasher<int32> > vec_set;
535  std::vector<std::vector<int32 > > new_vecs;
536  new_vecs.reserve(vecs->size());
537  int32 num_not_inserted = 0;
538  for (std::vector<std::vector<int32 > >::const_iterator iter = vecs->begin(),
539  end = vecs->end(); iter != end; iter++) {
540  if (vec_set.insert(*iter).second) { // if this vector was not already in
541  // the set...
542  new_vecs.push_back(*iter);
543  } else {
544  num_not_inserted++;
545  }
546  }
547  KALDI_VLOG(2) << "Removed " << num_not_inserted
548  << " duplicates from the phone sets.";
549  vecs->swap(new_vecs);
550 }
kaldi::int32 int32
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ RemoveLongSilences()

void RemoveLongSilences ( int32  max_silence_frames,
const std::vector< int32 > &  state_times,
KwsProductFst factor_transducer 
)

Definition at line 265 of file kws-functions.cc.

Referenced by main().

267  {
268  using namespace fst;
270 
271  StateId ns = factor_transducer->NumStates();
272  StateId ss = factor_transducer->Start();
273  StateId bad_state = factor_transducer->AddState();
274  for (StateId s = 0; s < ns; s++) {
275  // Skip arcs start from the initial state
276  if (s == ss)
277  continue;
278  for (MutableArcIterator<KwsProductFst>
279  aiter(factor_transducer, s); !aiter.Done(); aiter.Next()) {
280  KwsProductArc arc = aiter.Value();
281  // Skip arcs end with the final state
282  if (factor_transducer->Final(arc.nextstate) != KwsProductWeight::Zero())
283  continue;
284  // Non-silence arcs
285  if (arc.ilabel != 0)
286  continue;
287  // Short silence arcs
288  if (state_times[arc.nextstate]-state_times[s] <= max_silence_frames)
289  continue;
290  // The rest are the long silence arcs, we point their nextstate to
291  // bad_state
292  arc.nextstate = bad_state;
293  aiter.SetValue(arc);
294  }
295  }
296 
297  // Trim the unsuccessful paths
298  Connect(factor_transducer);
299 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
LogXStdXStdprimeArc KwsProductArc
Definition: kaldi-kws.h:48

◆ ReplaceAcousticScoresFromMap()

void ReplaceAcousticScoresFromMap ( const unordered_map< std::pair< int32, int32 >, std::pair< BaseFloat, int32 >, PairHasher< int32 > > &  acoustic_scores,
Lattice lat 
)

This function restores acoustic scores computed using the function ComputeAcousticScoresMap into the lattice.

Parameters
[in]acoustic_scoresA map from the pair (frame-index, transition-id) to a pair (sum-of-acoustic-scores, num-of-occurences) of the occurences of the transition-id in that frame. See the comments for ComputeAcousticScoresMap for details.
[out]latPointer to the output lattice.

Definition at line 1709 of file lattice-functions.cc.

References KALDI_ASSERT, KALDI_ERR, LatticeStateTimes(), LatticeWeightTpl< FloatType >::SetValue2(), TopSortLatticeIfNeeded(), and LatticeWeightTpl< BaseFloat >::Zero().

Referenced by main().

1712  {
1713  // typedef the arc, weight types
1714  typedef Lattice::Arc Arc;
1715  typedef Arc::Weight LatticeWeight;
1716  typedef Arc::StateId StateId;
1717 
1719 
1720  std::vector<int32> state_times;
1721  LatticeStateTimes(*lat, &state_times);
1722 
1723  KALDI_ASSERT(lat->Start() == 0);
1724 
1725  for (StateId s = 0; s < lat->NumStates(); s++) {
1726  int32 t = state_times[s];
1727  for (fst::MutableArcIterator<Lattice> aiter(lat, s);
1728  !aiter.Done(); aiter.Next()) {
1729  Arc arc(aiter.Value());
1730 
1731  int32 tid = arc.ilabel;
1732  if (tid != 0) {
1733  unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
1734  PairHasher<int32> >::const_iterator it = acoustic_scores.find(std::make_pair(t, tid));
1735  if (it == acoustic_scores.end()) {
1736  KALDI_ERR << "Could not find tid " << tid << " at time " << t
1737  << " in the acoustic scores map.";
1738  } else {
1739  arc.weight.SetValue2(it->second.first / it->second.second);
1740  }
1741  } else {
1742  // For epsilon arcs, set acoustic cost to 0.0
1743  arc.weight.SetValue2(0.0);
1744  }
1745  aiter.SetValue(arc);
1746  }
1747 
1748  LatticeWeight f = lat->Final(s);
1749  if (f != LatticeWeight::Zero()) {
1750  // Set final acoustic cost to 0.0
1751  f.SetValue2(0.0);
1752  lat->SetFinal(s, f);
1753  }
1754  }
1755 }
fst::StdArc::StateId StateId
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
void TopSortLatticeIfNeeded(Lattice *lat)
Topologically sort the lattice if not already topologically sorted.
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
fst::StdArc::Weight Weight
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
LatticeWeightTpl< BaseFloat > LatticeWeight

◆ ReplaceSymbolWithEpsilon()

static void kaldi::ReplaceSymbolWithEpsilon ( typename Arc::Label  symbol,
fst::VectorFst< Arc > *  fst 
)
static

Definition at line 36 of file kws-functions2.cc.

References KALDI_ASSERT.

Referenced by DoFactorMerging().

37  {
38  typedef typename Arc::StateId StateId;
39  for (StateId s = 0; s < fst->NumStates(); s++) {
40  for (fst::MutableArcIterator<fst::VectorFst<Arc> > aiter(fst, s);
41  !aiter.Done(); aiter.Next()) {
42  Arc arc = aiter.Value();
43  KALDI_ASSERT(arc.ilabel == arc.olabel);
44  if (arc.ilabel == symbol) {
45  arc.ilabel = 0;
46  arc.olabel = 0;
47  aiter.SetValue(arc);
48  }
49  }
50  }
51 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RescoreCompactLattice()

bool RescoreCompactLattice ( DecodableInterface decodable,
CompactLattice clat 
)

This function *adds* the negated scores obtained from the Decodable object, to the acoustic scores on the arcs.

If you want to replace them, you should use ScaleCompactLattice to first set the acoustic scores to zero. Returns true on success, false on error (typically some kind of mismatched inputs).

Definition at line 1354 of file lattice-functions.cc.

References RescoreCompactLatticeInternal().

Referenced by main().

1355  {
1356  return RescoreCompactLatticeInternal(NULL, 1.0, decodable, clat);
1357 }
bool RescoreCompactLatticeInternal(const TransitionModel *tmodel, BaseFloat speedup_factor, DecodableInterface *decodable, CompactLattice *clat)
RescoreCompactLatticeInternal is the internal code for both RescoreCompactLattice and RescoreCompatLa...

◆ RescoreCompactLatticeInternal()

bool kaldi::RescoreCompactLatticeInternal ( const TransitionModel tmodel,
BaseFloat  speedup_factor,
DecodableInterface decodable,
CompactLattice clat 
)

RescoreCompactLatticeInternal is the internal code for both RescoreCompactLattice and RescoreCompatLatticeSpeedup.

For RescoreCompactLattice, "tmodel" will be NULL and speedup_factor will be 1.0.

Definition at line 1216 of file lattice-functions.cc.

References CompactLatticeStateTimes(), rnnlm::i, DecodableInterface::IsLastFrame(), KALDI_ASSERT, KALDI_WARN, DecodableInterface::LogLikelihood(), LatticeWeightTpl< FloatType >::SetValue2(), CompactLatticeWeightTpl< WeightType, IntType >::SetWeight(), TransitionModel::TransitionIdToPdf(), CompactLatticeWeightTpl< WeightType, IntType >::Weight(), WithProb(), and CompactLatticeWeightTpl< WeightType, IntType >::Zero().

Referenced by RescoreCompactLattice(), and RescoreCompactLatticeSpeedup().

1220  {
1221  KALDI_ASSERT(speedup_factor >= 1.0);
1222  if (clat->NumStates() == 0) {
1223  KALDI_WARN << "Rescoring empty lattice";
1224  return false;
1225  }
1226  if (!clat->Properties(fst::kTopSorted, true)) {
1227  if (fst::TopSort(clat) == false) {
1228  KALDI_WARN << "Cycles detected in lattice.";
1229  return false;
1230  }
1231  }
1232  std::vector<int32> state_times;
1233  int32 utt_len = kaldi::CompactLatticeStateTimes(*clat, &state_times);
1234 
1235  std::vector<std::vector<ClatRescoreTuple> > time_to_state(utt_len);
1236 
1237  int32 num_states = clat->NumStates();
1238  KALDI_ASSERT(num_states == state_times.size());
1239  for (size_t state = 0; state < num_states; state++) {
1240  KALDI_ASSERT(state_times[state] >= 0);
1241  int32 t = state_times[state];
1242  int32 arc_id = 0;
1243  for (fst::MutableArcIterator<CompactLattice> aiter(clat, state);
1244  !aiter.Done(); aiter.Next(), arc_id++) {
1245  CompactLatticeArc arc = aiter.Value();
1246  std::vector<int32> arc_string = arc.weight.String();
1247 
1248  for (size_t offset = 0; offset < arc_string.size(); offset++) {
1249  if (t < utt_len) { // end state may be past this..
1250  int32 tid = arc_string[offset];
1251  time_to_state[t+offset].push_back(ClatRescoreTuple(state, arc_id, tid));
1252  } else {
1253  if (t != utt_len) {
1254  KALDI_WARN << "There appears to be lattice/feature mismatch, "
1255  << "aborting.";
1256  return false;
1257  }
1258  }
1259  }
1260  }
1261  if (clat->Final(state) != CompactLatticeWeight::Zero()) {
1262  arc_id = -1;
1263  std::vector<int32> arc_string = clat->Final(state).String();
1264  for (size_t offset = 0; offset < arc_string.size(); offset++) {
1265  KALDI_ASSERT(t + offset < utt_len); // already checked in
1266  // CompactLatticeStateTimes, so would be code error.
1267  time_to_state[t+offset].push_back(
1268  ClatRescoreTuple(state, arc_id, arc_string[offset]));
1269  }
1270  }
1271  }
1272 
1273  for (int32 t = 0; t < utt_len; t++) {
1274  if ((t < utt_len - 1) && decodable->IsLastFrame(t)) {
1275  KALDI_WARN << "Features are too short for lattice: utt-len is "
1276  << utt_len << ", " << t << " is last frame";
1277  return false;
1278  }
1279  // frame_scale is the scale we put on the computed acoustic probs for this
1280  // frame. It will always be 1.0 if tmodel == NULL (i.e. if we are not doing
1281  // the "speedup" code). For frames with multiple pdf-ids it will be one.
1282  // For frames with only one pdf-id, it will equal speedup_factor (>=1.0)
1283  // with probability 1.0 / speedup_factor, and zero otherwise. If it is zero,
1284  // we can avoid computing the probabilities.
1285  BaseFloat frame_scale = 1.0;
1286  KALDI_ASSERT(!time_to_state[t].empty());
1287  if (tmodel != NULL) {
1288  int32 pdf_id = tmodel->TransitionIdToPdf(time_to_state[t][0].tid);
1289  bool frame_has_multiple_pdfs = false;
1290  for (size_t i = 1; i < time_to_state[t].size(); i++) {
1291  if (tmodel->TransitionIdToPdf(time_to_state[t][i].tid) != pdf_id) {
1292  frame_has_multiple_pdfs = true;
1293  break;
1294  }
1295  }
1296  if (frame_has_multiple_pdfs) {
1297  frame_scale = 1.0;
1298  } else {
1299  if (WithProb(1.0 / speedup_factor)) {
1300  frame_scale = speedup_factor;
1301  } else {
1302  frame_scale = 0.0;
1303  }
1304  }
1305  if (frame_scale == 0.0)
1306  continue; // the code below would be pointless.
1307  }
1308 
1309  for (size_t i = 0; i < time_to_state[t].size(); i++) {
1310  int32 state = time_to_state[t][i].state_id;
1311  int32 arc_id = time_to_state[t][i].arc_id;
1312  int32 tid = time_to_state[t][i].tid;
1313 
1314  if (arc_id == -1) { // Final state
1315  // Access the trans_id
1316  CompactLatticeWeight curr_clat_weight = clat->Final(state);
1317 
1318  // Calculate likelihood
1319  BaseFloat log_like = decodable->LogLikelihood(t, tid) * frame_scale;
1320  // update weight
1321  CompactLatticeWeight new_clat_weight = curr_clat_weight;
1322  LatticeWeight new_lat_weight = new_clat_weight.Weight();
1323  new_lat_weight.SetValue2(-log_like + curr_clat_weight.Weight().Value2());
1324  new_clat_weight.SetWeight(new_lat_weight);
1325  clat->SetFinal(state, new_clat_weight);
1326  } else {
1327  fst::MutableArcIterator<CompactLattice> aiter(clat, state);
1328 
1329  aiter.Seek(arc_id);
1330  CompactLatticeArc arc = aiter.Value();
1331 
1332  // Calculate likelihood
1333  BaseFloat log_like = decodable->LogLikelihood(t, tid) * frame_scale;
1334  // update weight
1335  LatticeWeight new_weight = arc.weight.Weight();
1336  new_weight.SetValue2(-log_like + arc.weight.Weight().Value2());
1337  arc.weight.SetWeight(new_weight);
1338  aiter.SetValue(arc);
1339  }
1340  }
1341  }
1342  return true;
1343 }
bool WithProb(BaseFloat prob, struct RandomState *state)
Definition: kaldi-math.cc:72
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 CompactLatticeStateTimes(const CompactLattice &lat, vector< int32 > *times)
As LatticeStateTimes, but in the CompactLattice format.
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ RescoreCompactLatticeSpeedup()

bool RescoreCompactLatticeSpeedup ( const TransitionModel tmodel,
BaseFloat  speedup_factor,
DecodableInterface decodable,
CompactLattice clat 
)

This function is like RescoreCompactLattice, but it is modified to avoid computing probabilities on most frames where all the pdf-ids are the same.

(it needs the transition-model to work out whether two transition-ids map to the same pdf-id, and it assumes that the lattice has transition-ids on it). The naive thing would be to just set all probabilities to zero on frames where all the pdf-ids are the same (because this value won't affect the lattice posterior). But this would become confusing when we compute corpus-level diagnostics such as the MMI objective function. Instead, imagine speedup_factor = 100 (it must be >= 1.0)... with probability (1.0 / speedup_factor) we compute those likelihoods and multiply them by speedup_factor; otherwise we set them to zero. This gives the right expected probability so our corpus-level diagnostics will be about right.

Definition at line 1346 of file lattice-functions.cc.

References RescoreCompactLatticeInternal().

Referenced by main().

1350  {
1351  return RescoreCompactLatticeInternal(&tmodel, speedup_factor, decodable, clat);
1352 }
bool RescoreCompactLatticeInternal(const TransitionModel *tmodel, BaseFloat speedup_factor, DecodableInterface *decodable, CompactLattice *clat)
RescoreCompactLatticeInternal is the internal code for both RescoreCompactLattice and RescoreCompatLa...

◆ RescoreLattice()

bool RescoreLattice ( DecodableInterface decodable,
Lattice lat 
)

This function *adds* the negated scores obtained from the Decodable object, to the acoustic scores on the arcs.

If you want to replace them, you should use ScaleCompactLattice to first set the acoustic scores to zero. Returns true on success, false on error (e.g. some kind of mismatched inputs). The input labels, if nonzero, are interpreted as transition-ids or whatever other index the Decodable object expects.

Definition at line 1360 of file lattice-functions.cc.

References rnnlm::i, DecodableInterface::IsLastFrame(), KALDI_ASSERT, KALDI_WARN, LatticeStateTimes(), and DecodableInterface::LogLikelihood().

Referenced by SingleUtteranceGmmDecoder::GetLattice().

1361  {
1362  if (lat->NumStates() == 0) {
1363  KALDI_WARN << "Rescoring empty lattice";
1364  return false;
1365  }
1366  if (!lat->Properties(fst::kTopSorted, true)) {
1367  if (fst::TopSort(lat) == false) {
1368  KALDI_WARN << "Cycles detected in lattice.";
1369  return false;
1370  }
1371  }
1372  std::vector<int32> state_times;
1373  int32 utt_len = kaldi::LatticeStateTimes(*lat, &state_times);
1374 
1375  std::vector<std::vector<int32> > time_to_state(utt_len );
1376 
1377  int32 num_states = lat->NumStates();
1378  KALDI_ASSERT(num_states == state_times.size());
1379  for (size_t state = 0; state < num_states; state++) {
1380  int32 t = state_times[state];
1381  // Don't check t >= 0 because non-accessible states could have t = -1.
1382  KALDI_ASSERT(t <= utt_len);
1383  if (t >= 0 && t < utt_len)
1384  time_to_state[t].push_back(state);
1385  }
1386 
1387  for (int32 t = 0; t < utt_len; t++) {
1388  if ((t < utt_len - 1) && decodable->IsLastFrame(t)) {
1389  KALDI_WARN << "Features are too short for lattice: utt-len is "
1390  << utt_len << ", " << t << " is last frame";
1391  return false;
1392  }
1393  for (size_t i = 0; i < time_to_state[t].size(); i++) {
1394  int32 state = time_to_state[t][i];
1395  for (fst::MutableArcIterator<Lattice> aiter(lat, state);
1396  !aiter.Done(); aiter.Next()) {
1397  LatticeArc arc = aiter.Value();
1398  if (arc.ilabel != 0) {
1399  int32 trans_id = arc.ilabel; // Note: it doesn't necessarily
1400  // have to be a transition-id, just whatever the Decodable
1401  // object is expecting, but it's normally a transition-id.
1402 
1403  BaseFloat log_like = decodable->LogLikelihood(t, trans_id);
1404  arc.weight.SetValue2(-log_like + arc.weight.Value2());
1405  aiter.SetValue(arc);
1406  }
1407  }
1408  }
1409  }
1410  return true;
1411 }
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
int32 LatticeStateTimes(const Lattice &lat, vector< int32 > *times)
This function iterates over the states of a topologically sorted lattice and counts the time instance...
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ ResizeModel()

void kaldi::ResizeModel ( int32  dim,
AmDiagGmm am_gmm 
)

Definition at line 176 of file mle-am-diag-gmm.cc.

References DiagGmm::ComputeGconsts(), AmDiagGmm::GetPdf(), DiagGmm::NumGauss(), AmDiagGmm::NumPdfs(), DiagGmm::Resize(), MatrixBase< Real >::Set(), and DiagGmm::SetInvVars().

Referenced by MleAmDiagGmmUpdate().

176  {
177  for (int32 pdf_id = 0; pdf_id < am_gmm->NumPdfs(); pdf_id++) {
178  DiagGmm &pdf = am_gmm->GetPdf(pdf_id);
179  pdf.Resize(pdf.NumGauss(), dim);
180  Matrix<BaseFloat> inv_vars(pdf.NumGauss(), dim);
181  inv_vars.Set(1.0); // make all vars 1.
182  pdf.SetInvVars(inv_vars);
183  pdf.ComputeGconsts();
184  }
185 }
kaldi::int32 int32

◆ ReverseVector()

void kaldi::ReverseVector ( std::vector< T > *  vec)
inline

Reverses the contents of a vector.

Definition at line 264 of file stl-utils.h.

References rnnlm::i, KALDI_ASSERT, and swap().

Referenced by LevenshteinAlignment(), and TestReverseVector().

264  {
265  KALDI_ASSERT(vec != NULL);
266  size_t sz = vec->size();
267  for (size_t i = 0; i < sz/2; i++)
268  std::swap( (*vec)[i], (*vec)[sz-1-i]);
269 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RoundUpToNearestPowerOfTwo()

int32 RoundUpToNearestPowerOfTwo ( int32  n)

Definition at line 32 of file kaldi-math.cc.

References KALDI_ASSERT.

Referenced by ComputationGraphBuilder::AddDependencies(), AssertEqual(), FFTbasedBlockConvolveSignals(), FFTbasedConvolveSignals(), FrameExtractionOptions::PaddedWindowSize(), and UnitTestRoundUpToNearestPowerOfTwo().

32  {
33  KALDI_ASSERT(n > 0);
34  n--;
35  n |= n >> 1;
36  n |= n >> 2;
37  n |= n >> 4;
38  n |= n >> 8;
39  n |= n >> 16;
40  return n+1;
41 }
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ RuleActivated()

static bool kaldi::RuleActivated ( const OnlineEndpointRule rule,
const std::string &  rule_name,
BaseFloat  trailing_silence,
BaseFloat  relative_cost,
BaseFloat  utterance_length 
)
static

Definition at line 26 of file online-endpoint.cc.

References KALDI_VLOG, OnlineEndpointRule::max_relative_cost, OnlineEndpointRule::min_trailing_silence, OnlineEndpointRule::min_utterance_length, and OnlineEndpointRule::must_contain_nonsilence.

Referenced by EndpointDetected().

30  {
31  bool contains_nonsilence = (utterance_length > trailing_silence);
32 
33  bool ans = (contains_nonsilence || !rule.must_contain_nonsilence) &&
34  trailing_silence >= rule.min_trailing_silence &&
35  relative_cost <= rule.max_relative_cost &&
36  utterance_length >= rule.min_utterance_length;
37  if (ans) {
38  KALDI_VLOG(2) << "Endpointing rule " << rule_name << " activated: "
39  << (contains_nonsilence ? "true" : "false" ) << ','
40  << trailing_silence << ',' << relative_cost << ','
41  << utterance_length;
42  }
43  return ans;
44 }
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156

◆ RunMultiThreaded()

void kaldi::RunMultiThreaded ( const C &  c_in)

Here, class C should inherit from MultiThreadable.

Note: if you want to control the number of threads yourself, or need to do something in the main thread of the program while the objects exist, just initialize the MultiThreader<C> object yourself.

Definition at line 151 of file kaldi-thread.h.

Referenced by AmSgmm2::ComputeNormalizers(), TestThreads(), EbwAmSgmm2Updater::UpdatePhoneVectors(), MleAmSgmm2Updater::UpdatePhoneVectors(), EbwAmSgmm2Updater::UpdateW(), and MleAmSgmm2Updater::UpdateW().

151  {
152  MultiThreader<C> m(g_num_threads, c_in);
153 }
int32 g_num_threads
Definition: kaldi-thread.cc:25

◆ RunPerSpeaker()

int32 kaldi::RunPerSpeaker ( const std::string &  ivector_extractor_rxfilename,
const IvectorEstimationOptions opts,
bool  compute_objf_change,
const std::string &  spk2utt_rspecifier,
const std::string &  feature_rspecifier,
const std::string &  posterior_rspecifier,
const std::string &  ivector_wspecifier 
)

Definition at line 92 of file ivector-extract.cc.

References IvectorEstimationOptions::acoustic_weight, SequentialTableReader< Holder >::Done(), IvectorExtractor::FeatDim(), IvectorExtractor::GetAuxf(), IvectorExtractor::GetIvectorDistribution(), RandomAccessTableReader< Holder >::HasKey(), rnnlm::i, IvectorExtractor::IvectorDim(), KALDI_LOG, KALDI_WARN, SequentialTableReader< Holder >::Key(), IvectorEstimationOptions::max_count, SequentialTableReader< Holder >::Next(), IvectorExtractor::NumGauss(), MatrixBase< Real >::NumRows(), IvectorExtractor::PriorOffset(), ReadKaldiObject(), ScalePosterior(), RandomAccessTableReader< Holder >::Value(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

98  {
99  IvectorExtractor extractor;
100  ReadKaldiObject(ivector_extractor_rxfilename, &extractor);
101  SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier);
102  RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier);
103  RandomAccessPosteriorReader posterior_reader(posterior_rspecifier);
104  BaseFloatVectorWriter ivector_writer(ivector_wspecifier);
105 
106  double tot_auxf_change = 0.0, tot_post = 0.0, tot_norm = 0.0;
107  int32 num_utt_done = 0, num_utt_err = 0,
108  num_spk_done = 0, num_spk_err = 0;
109 
110  for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) {
111  std::string spk = spk2utt_reader.Key();
112  const std::vector<std::string> &utts = spk2utt_reader.Value();
113 
114  bool need_2nd_order_stats = false;
115 
116  IvectorExtractorUtteranceStats utt_stats(extractor.NumGauss(),
117  extractor.FeatDim(),
118  need_2nd_order_stats);
119 
120  for (size_t i = 0; i < utts.size(); i++) {
121  const std::string &utt = utts[i];
122  if (!feature_reader.HasKey(utt)) {
123  KALDI_WARN << "No features present for utterance " << utt;
124  num_utt_err++;
125  continue;
126  }
127  const Matrix<BaseFloat> &feats = feature_reader.Value(utt);
128  if (!posterior_reader.HasKey(utt)) {
129  KALDI_WARN << "No posteriors present for utterance " << utt;
130  num_utt_err++;
131  continue;
132  }
133  Posterior posterior = posterior_reader.Value(utt);
134  if (feats.NumRows() != posterior.size()) {
135  KALDI_WARN << "Posterior has wrong size " << posterior.size()
136  << " vs. feats " << feats.NumRows() << " for "
137  << utt;
138  num_utt_err++;
139  continue;
140  }
141  ScalePosterior(opts.acoustic_weight, &posterior);
142  num_utt_done++;
143  utt_stats.AccStats(feats, posterior);
144  }
145 
146  if (utt_stats.NumFrames() == 0.0) {
147  KALDI_WARN << "No stats accumulated for speaker " << spk;
148  num_spk_err++;
149  continue;
150  } else {
151  if (opts.max_count > 0 && utt_stats.NumFrames() > opts.max_count) {
152  double scale = opts.max_count / utt_stats.NumFrames();
153  utt_stats.Scale(scale);
154  KALDI_LOG << "Scaling stats for speaker " << spk << " by scale "
155  << scale << " due to --max-count=" << opts.max_count;
156  }
157 
158  Vector<double> ivector(extractor.IvectorDim());
159  ivector(0) = extractor.PriorOffset();
160 
161  if (compute_objf_change) {
162  double old_auxf = extractor.GetAuxf(utt_stats, ivector);
163  extractor.GetIvectorDistribution(utt_stats, &ivector, NULL);
164  double new_auxf = extractor.GetAuxf(utt_stats, ivector);
165  double auxf_change = new_auxf - old_auxf;
166 
167  KALDI_LOG << "Auxf change for speaker " << spk << " was "
168  << (auxf_change / utt_stats.NumFrames()) << " per frame, over "
169  << utt_stats.NumFrames() << " frames (weighted).";
170  tot_auxf_change += auxf_change;
171  } else {
172  extractor.GetIvectorDistribution(utt_stats, &ivector, NULL);
173  }
174  // We actually write out the offset of the iVectors from the mean of the
175  // prior distribution; this is the form we'll need it in for scoring and
176  // as a feature for neural nets. (most formulations of iVectors have
177  // zero-mean priors so this is not normally an issue).
178  ivector(0) -= extractor.PriorOffset();
179  KALDI_LOG << "Ivector norm for speaker " << spk
180  << " was " << ivector.Norm(2.0);
181 
182  tot_norm += ivector.Norm(2.0) * utt_stats.NumFrames();
183  tot_post += utt_stats.NumFrames();
184  num_spk_done++;
185  Vector<BaseFloat> ivector_flt(ivector);
186  ivector_writer.Write(spk, ivector_flt);
187  }
188  }
189 
190  KALDI_LOG << "Done " << num_spk_done << " speakers; " << num_spk_err
191  << " with errors. " << num_utt_done << " utterances "
192  << "were processed, " << num_utt_err << " with errors.";
193  if (tot_post != 0.0) {
194  if (compute_objf_change) {
195  KALDI_LOG << "Overall weighted-average objective function improvement was "
196  << (tot_auxf_change / tot_post) << " over " << tot_post
197  << " frames (weighted)";
198  }
199  KALDI_LOG << "Average iVector norm (weighted by frames) was "
200  << (tot_norm / tot_post) << " over " << tot_post
201  << " frames (weighted)";
202  }
203  return (num_spk_done != 0 ? 0 : 1);
204 }
double PriorOffset() const
The distribution over iVectors, in our formulation, is not centered at zero; its first dimension has ...
double GetAuxf(const IvectorExtractorUtteranceStats &utt_stats, const VectorBase< double > &mean, const SpMatrix< double > *var=NULL) const
Returns the log-likelihood objective function, summed over frames, for this distribution of iVectors ...
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
void ReadKaldiObject(const std::string &filename, Matrix< float > *m)
Definition: kaldi-io.cc:832
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_WARN
Definition: kaldi-error.h:150
void ScalePosterior(BaseFloat scale, Posterior *post)
Scales the BaseFloat (weight) element in the posterior entries.
Definition: posterior.cc:218
void GetIvectorDistribution(const IvectorExtractorUtteranceStats &utt_stats, VectorBase< double > *mean, SpMatrix< double > *var) const
Gets the distribution over ivectors (or at least, a Gaussian approximation to it).
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
These are the stats for a particular utterance, i.e.
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ SameDim()

bool kaldi::SameDim ( const CuMatrixBase< Real > &  M,
const CuMatrixBase< Real > &  N 
)

Definition at line 949 of file cu-matrix.h.

949  {
950  return (M.NumRows() == N.NumRows() && M.NumCols() == N.NumCols());
951 }

◆ SameDimAndStride()

bool kaldi::SameDimAndStride ( const CuMatrixBase< Real > &  M,
const CuMatrixBase< Real > &  N 
)

Definition at line 954 of file cu-matrix.h.

Referenced by ScaleAndOffsetComponent::Backprop(), and ScaleAndOffsetComponent::Propagate().

954  {
955  return (M.NumRows() == N.NumRows() && M.NumCols() == N.NumCols()
956  && M.Stride() == N.Stride());
957 }

◆ ScoringTest()

bool kaldi::ScoringTest ( bool  seps,
const std::string &  infile,
const std::string &  sentence,
float  expected 
)

Definition at line 156 of file arpa-lm-compiler-test.cc.

References AddSelfLoops(), AddToChainFsa(), ApproxEqual(), Compile(), ArpaLmCompiler::Fst(), KALDI_ASSERT, KALDI_WARN, kBos, and kEos.

Referenced by RunAllTests().

157  {
158  ArpaLmCompiler* lm_compiler = Compile(seps, infile);
159  const fst::SymbolTable* symbols = lm_compiler->Fst().InputSymbols();
160 
161  // Create a sentence FST for scoring.
162  fst::StdVectorFst sentFst;
163  fst::StdArc::StateId state = sentFst.AddState();
164  sentFst.SetStart(state);
165  if (!seps) {
166  state = AddToChainFsa(&sentFst, state, kBos);
167  }
168  std::stringstream ss(sentence);
169  std::string word;
170  while (ss >> word) {
171  int64 word_sym = symbols->Find(word);
172  KALDI_ASSERT(word_sym != -1);
173  state = AddToChainFsa(&sentFst, state, word_sym);
174  }
175  if (!seps) {
176  state = AddToChainFsa(&sentFst, state, kEos);
177  }
178  if (seps) {
179  AddSelfLoops(&sentFst);
180  }
181  sentFst.SetFinal(state, 0);
182  sentFst.SetOutputSymbols(symbols);
183 
184  // Do the composition and extract final weight.
185  fst::StdVectorFst composed;
186  fst::Compose(sentFst, lm_compiler->Fst(), &composed);
187  delete lm_compiler;
188 
189  if (composed.Start() == fst::kNoStateId) {
190  KALDI_WARN << "Test sentence " << sentence << " did not compose "
191  << "with the language model FST\n";
192  return false;
193  }
194 
195  std::vector<fst::StdArc::Weight> shortest;
196  fst::ShortestDistance(composed, &shortest, true);
197  float actual = shortest[composed.Start()].Value();
198 
199  bool ok = ApproxEqual(expected, actual);
200  if (!ok) {
201  KALDI_WARN << "Scored " << sentence << " in " << infile
202  << ": Expected=" << expected << " actual=" << actual;
203  }
204  return ok;
205 }
fst::StdArc::StateId StateId
void AddSelfLoops(fst::StdMutableFst *fst)
ArpaLmCompiler * Compile(bool seps, const std::string &infile)
fst::StdArc::StateId AddToChainFsa(fst::StdMutableFst *fst, fst::StdArc::StateId last_state, int64 symbol)
fst::StdVectorFst StdVectorFst
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ SelectLags()

void kaldi::SelectLags ( const PitchExtractionOptions opts,
Vector< BaseFloat > *  lags 
)

This function selects the lags at which we measure the NCCF: we need to select lags from 1/max_f0 to 1/min_f0, in a geometric progression with ratio 1 + d.

Definition at line 157 of file pitch-functions.cc.

References VectorBase< Real >::Data(), PitchExtractionOptions::delta_pitch, PitchExtractionOptions::max_f0, PitchExtractionOptions::min_f0, and Vector< Real >::Resize().

Referenced by OnlinePitchFeatureImpl::OnlinePitchFeatureImpl().

158  {
159  // choose lags relative to acceptable pitch tolerance
160  BaseFloat min_lag = 1.0 / opts.max_f0, max_lag = 1.0 / opts.min_f0;
161 
162  std::vector<BaseFloat> tmp_lags;
163  for (BaseFloat lag = min_lag; lag <= max_lag; lag *= 1.0 + opts.delta_pitch)
164  tmp_lags.push_back(lag);
165  lags->Resize(tmp_lags.size());
166  std::copy(tmp_lags.begin(), tmp_lags.end(), lags->Data());
167 }
float BaseFloat
Definition: kaldi-types.h:29

◆ SendPartialResult()

void kaldi::SendPartialResult ( const std::vector< int32 > &  words,
const fst::SymbolTable *  word_syms,
const bool  line_break,
const int32  serv_sock,
const sockaddr_in &  client_addr 
)

Definition at line 30 of file online-server-gmm-decode-faster.cc.

References rnnlm::i, KALDI_ASSERT, KALDI_ERR, and KALDI_WARN.

Referenced by main().

34  {
35  KALDI_ASSERT(word_syms != NULL);
36  std::stringstream sstream;
37  for (size_t i = 0; i < words.size(); i++) {
38  std::string word = word_syms->Find(words[i]);
39  if (word == "")
40  KALDI_ERR << "Word-id " << words[i] <<" not in symbol table.";
41  sstream << word << ' ';
42  }
43  if (line_break)
44  sstream << "\n\n";
45 
46  ssize_t sent = sendto(serv_sock, sstream.str().c_str(), sstream.str().size(),
47  0, reinterpret_cast<const sockaddr*>(&client_addr),
48  sizeof(client_addr));
49  if (sent == -1)
50  KALDI_WARN << "sendto() call failed when tried to send recognition results";
51 }
int32 words[kMaxOrder]
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ SentenceLevelConfidence() [1/2]

BaseFloat SentenceLevelConfidence ( const CompactLattice clat,
int32 num_paths,
std::vector< int32 > *  best_sentence,
std::vector< int32 > *  second_best_sentence 
)

Caution: this function is not the only way to get confidences in Kaldi.

This only gives you sentence-level (utterance-level) confidence. You can get word-by-word confidence within a sentence, along with Minimum Bayes Risk decoding, by looking at sausages.h. Caution: confidences estimated using this type of method are not very accurate. This function will return the difference between the best path in clat and the second-best path in clat (a positive number), or zero if clat was equivalent to the empty FST (no successful paths), or infinity if there was only one path in "clat". It will output to "num_paths" (if non-NULL) a number n = 0, 1 or 2 saying how many n-best paths (up to two) were found. If n >= 1 it outputs to "best_sentence" (if non-NULL) the best word-sequence; if n == 2 it outputs to "second_best_sentence" (if non-NULL) the second best word-sequence (this may be useful for testing whether the two best word sequences are somehow equivalent for the task at hand). If you need more information than this or want to look deeper inside the n-best list, then look at the implementation of this function. This function requires that distinct paths in "lat" have distinct word sequences; this will automatically be the case if you generated "clat" in any normal way, such as from a decoder, because a deterministic FST has this property. This function assumes that any acoustic scaling you want to apply, has already been applied.

Definition at line 26 of file confidence.cc.

References fst::ConvertLattice(), fst::ConvertToCost(), KALDI_ASSERT, KALDI_WARN, rnnlm::n, and fst::NbestAsFsts().

Referenced by main(), and SentenceLevelConfidence().

29  {
30  /* It may seem strange that the first thing we do is to convert the
31  CompactLattice to a Lattice, given that we may have just created the
32  CompactLattice by determinizing a Lattice. However, this is not just
33  a circular conversion; "lat" will have the property that distinct
34  paths have distinct word sequences.
35  Below, we could run NbestAsFsts on a CompactLattice, but the time
36  taken would be quadratic in the length in words of the CompactLattice,
37  because of the alignment information getting appended as vectors.
38  That's why we convert back to Lattice.
39  */
40  Lattice lat;
41  ConvertLattice(clat, &lat);
42 
43  std::vector<Lattice> lats;
44  NbestAsFsts(lat, 2, &lats);
45  int32 n = lats.size();
46  KALDI_ASSERT(n >= 0 && n <= 2);
47  if (num_paths != NULL) *num_paths = n;
48  if (best_sentence != NULL) best_sentence->clear();
49  if (second_best_sentence != NULL) second_best_sentence->clear();
50 
51  LatticeWeight weight1, weight2;
52  if (n >= 1)
53  fst::GetLinearSymbolSequence<LatticeArc,int32>(lats[0], NULL,
54  best_sentence,
55  &weight1);
56  if (n >= 2)
57  fst::GetLinearSymbolSequence<LatticeArc,int32>(lats[1], NULL,
58  second_best_sentence,
59  &weight2);
60 
61  if (n == 0) {
62  return 0; // this seems most appropriate because it will be interpreted as
63  // zero confidence, and something definitely went wrong for this
64  // to happen.
65  } else if (n == 1) {
66  // If there is only one sentence in the lattice, we interpret this as there
67  // being perfect confidence
68  return std::numeric_limits<BaseFloat>::infinity();
69  } else {
70  BaseFloat best_cost = ConvertToCost(weight1),
71  second_best_cost = ConvertToCost(weight2);
72  BaseFloat ans = second_best_cost - best_cost;
73  if (!(ans >= -0.001 * (fabs(best_cost) + fabs(second_best_cost)))) {
74  // Answer should be positive. Make sure it's at at least not
75  // substantially negative. This would be very strange.
76  KALDI_WARN << "Very negative difference." << ans;
77  }
78  if (ans < 0) ans = 0;
79  return ans;
80  }
81 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
void NbestAsFsts(const Fst< Arc > &fst, size_t n, std::vector< VectorFst< Arc > > *fsts_out)
Takes the n-shortest-paths (using ShortestPath), but outputs the result as a vector of up to n fsts...
double ConvertToCost(const LatticeWeightTpl< Float > &w)
struct rnnlm::@11::@12 n
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
LatticeWeightTpl< BaseFloat > LatticeWeight

◆ SentenceLevelConfidence() [2/2]

BaseFloat SentenceLevelConfidence ( const Lattice lat,
int32 num_paths,
std::vector< int32 > *  best_sentence,
std::vector< int32 > *  second_best_sentence 
)

This version of SentenceLevelConfidence takes as input a state-level lattice.

It needs to determinize it first, but it does so in a "smart" way that only generates about as many output paths as it needs.

Definition at line 85 of file confidence.cc.

References fst::DeterminizeLatticePruned(), LongestSentenceLength(), DeterminizeLatticePrunedOptions::max_arcs, and SentenceLevelConfidence().

88  {
89  int32 max_sentence_length = LongestSentenceLength(lat);
90  fst::DeterminizeLatticePrunedOptions determinize_opts;
91  // The basic idea of expanding only up to "max_sentence_length * 2" arcs,
92  // is that that should be sufficient to get the best and second-best paths
93  // through the lattice, which is all we need for this particular application.
94  // "safety_term" is just in case there is some reason why we might need a few
95  // extra arcs, e.g. in case of a tie on the weights of the second-best path.
96  int32 safety_term = 4 + max_sentence_length;
97  determinize_opts.max_arcs = max_sentence_length * 2 + safety_term;
98  // set prune_beam to a large value... we don't really rely on the beam; we
99  // rely on the max_arcs variable to limit the size of the lattice.
100  double prune_beam = std::numeric_limits<double>::infinity();
101 
102  CompactLattice clat;
103  // We ignore the return status of DeterminizeLatticePruned. It will likely
104  // return false, but this is expected because the expansion is limited
105  // by "max_arcs" not "prune_beam".
106  Lattice inverse_lat(lat);
107  fst::Invert(&inverse_lat); // Swap input and output symbols.
108  DeterminizeLatticePruned(inverse_lat, prune_beam, &clat, determinize_opts);
109 
110  // Call the version of this function that takes a CompactLattice.
111  return SentenceLevelConfidence(clat, num_paths,
112  best_sentence, second_best_sentence);
113 }
bool DeterminizeLatticePruned(const ExpandedFst< ArcTpl< Weight > > &ifst, double beam, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, IntType > > > *ofst, DeterminizeLatticePrunedOptions opts)
kaldi::int32 int32
BaseFloat SentenceLevelConfidence(const Lattice &lat, int32 *num_paths, std::vector< int32 > *best_sentence, std::vector< int32 > *second_best_sentence)
This version of SentenceLevelConfidence takes as input a state-level lattice.
Definition: confidence.cc:85
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
int32 LongestSentenceLength(const Lattice &lat)
This function returns the number of words in the longest sentence in a CompactLattice (i...

◆ SetLinearAcceptorWeight()

void kaldi::SetLinearAcceptorWeight ( double  cost,
fst::VectorFst< fst::StdArc > *  fst 
)

Definition at line 27 of file transcripts-to-fsts.cc.

Referenced by main().

27  {
28  typedef typename fst::StdArc::Label Label;
29  typedef typename fst::StdArc::Weight Weight;
30  typedef typename fst::StdArc::StateId StateId;
31 
32  StateId start = fst->Start();
33  fst::MutableArcIterator<fst::VectorFst<fst::StdArc> > aiter(fst, start);
34  fst::StdArc arc = aiter.Value();
35  arc.weight = cost;
36  aiter.SetValue(arc);
37 }
fst::StdArc::StateId StateId
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
fst::StdArc StdArc
fst::StdArc::Label Label
fst::StdArc::Weight Weight

◆ SetOptionImpl()

static bool kaldi::SetOptionImpl ( const std::string &  key,
const T &  value,
std::map< std::string, T *> &  some_map 
)
static

Definition at line 69 of file simple-options.cc.

Referenced by SimpleOptions::SetOption().

70  {
71  if (some_map.end() != some_map.find(key)) {
72  *(some_map[key]) = value;
73  return true;
74  }
75  return false;
76 }

◆ SetToMovingAverage()

void kaldi::SetToMovingAverage ( int32  average_window_size,
Matrix< BaseFloat > *  mat 
)

Definition at line 84 of file process-pitch-feats.cc.

References rnnlm::i, rnnlm::j, and MatrixBase< Real >::NumRows().

Referenced by main().

85  {
86  int32 num_frames = mat->NumRows();
87  Matrix<BaseFloat> &features = *mat;
88  Vector<BaseFloat> temp_pitch(num_frames);
89  int32 width = (average_window_size - 1) / 2, i;
90  // e.g. if average_window_size is 5, width will equal 2.
91 
92  for (i = width; i < num_frames - width ; i++) {
93  temp_pitch(i) = features(i, 1);
94  for(int j = 1; j <= width; ++j) {
95  temp_pitch(i) += (features(i - j, 1) + features(i + j, 1));
96  }
97  temp_pitch(i) /= (2 * width + 1);
98  }
99  for (i = width; i < num_frames - width; i++)
100  features(i, 1) = temp_pitch(i);
101 }
kaldi::int32 int32
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ ShiftFeatureMatrix()

void kaldi::ShiftFeatureMatrix ( const Matrix< BaseFloat > &  src,
int32  shift,
Matrix< BaseFloat > *  rearranged 
)

Definition at line 26 of file shift-feats.cc.

References MatrixBase< Real >::NumRows(), and MatrixBase< Real >::Row().

Referenced by main().

27  {
28  for (int32 r = 0; r < src.NumRows(); r++) {
29  int32 src_r = r - shift;
30  if (src_r < 0) src_r = 0;
31  if (src_r >= src.NumRows()) src_r = src.NumRows() - 1;
32  rearranged->Row(r).CopyFromVec(src.Row(src_r));
33  }
34  }
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ Sleep()

void Sleep ( float  seconds)

Definition at line 45 of file kaldi-utils.cc.

Referenced by MachineIsLittleEndian(), main(), OnlineTimer::SleepUntil(), TimerTest(), kaldi::nnet2::UnitTestAffineComponent(), kaldi::nnet2::UnitTestAffineComponentPreconditioned(), kaldi::nnet2::UnitTestAffineComponentPreconditionedOnline(), kaldi::nnet2::UnitTestConvolutional1dComponent(), UnitTestIoPipe(), and UnitTestReadScriptFile().

45  {
46 #if defined(_MSC_VER) || defined(MINGW)
47  ::Sleep(static_cast<int>(seconds * 1000.0));
48 #elif defined(__CYGWIN__)
49  sleep(static_cast<int>(seconds));
50 #else
51  usleep(static_cast<int>(seconds * 1000000.0));
52 #endif
53 }
void Sleep(float seconds)
Definition: kaldi-utils.cc:45

◆ SlidingWindowCmnInternal()

void kaldi::SlidingWindowCmnInternal ( const SlidingWindowCmnOptions opts,
const MatrixBase< double > &  input,
MatrixBase< double > *  output 
)

Definition at line 250 of file feature-functions.cc.

References VectorBase< Real >::AddDiagMat2(), VectorBase< Real >::AddVec(), VectorBase< Real >::AddVec2(), VectorBase< Real >::ApplyFloor(), VectorBase< Real >::ApplyPow(), SlidingWindowCmnOptions::center, SlidingWindowCmnOptions::Check(), SlidingWindowCmnOptions::cmn_window, VectorBase< Real >::CopyFromVec(), KALDI_ASSERT, KALDI_WARN, kTrans, SlidingWindowCmnOptions::max_warnings, SlidingWindowCmnOptions::min_window, VectorBase< Real >::MulElements(), SlidingWindowCmnOptions::normalize_variance, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), VectorBase< Real >::Scale(), and VectorBase< Real >::Set().

Referenced by SlidingWindowCmn().

252  {
253  opts.Check();
254  int32 num_frames = input.NumRows(), dim = input.NumCols(),
255  last_window_start = -1, last_window_end = -1,
256  warning_count = 0;
257  Vector<double> cur_sum(dim), cur_sumsq(dim);
258 
259  for (int32 t = 0; t < num_frames; t++) {
260  int32 window_start, window_end; // note: window_end will be one
261  // past the end of the window we use for normalization.
262  if (opts.center) {
263  window_start = t - (opts.cmn_window / 2);
264  window_end = window_start + opts.cmn_window;
265  } else {
266  window_start = t - opts.cmn_window;
267  window_end = t + 1;
268  }
269  if (window_start < 0) { // shift window right if starts <0.
270  window_end -= window_start;
271  window_start = 0; // or: window_start -= window_start
272  }
273  if (!opts.center) {
274  if (window_end > t)
275  window_end = std::max(t + 1, opts.min_window);
276  }
277  if (window_end > num_frames) {
278  window_start -= (window_end - num_frames);
279  window_end = num_frames;
280  if (window_start < 0) window_start = 0;
281  }
282  if (last_window_start == -1) {
283  SubMatrix<double> input_part(input,
284  window_start, window_end - window_start,
285  0, dim);
286  cur_sum.AddRowSumMat(1.0, input_part , 0.0);
287  if (opts.normalize_variance)
288  cur_sumsq.AddDiagMat2(1.0, input_part, kTrans, 0.0);
289  } else {
290  if (window_start > last_window_start) {
291  KALDI_ASSERT(window_start == last_window_start + 1);
292  SubVector<double> frame_to_remove(input, last_window_start);
293  cur_sum.AddVec(-1.0, frame_to_remove);
294  if (opts.normalize_variance)
295  cur_sumsq.AddVec2(-1.0, frame_to_remove);
296  }
297  if (window_end > last_window_end) {
298  KALDI_ASSERT(window_end == last_window_end + 1);
299  SubVector<double> frame_to_add(input, last_window_end);
300  cur_sum.AddVec(1.0, frame_to_add);
301  if (opts.normalize_variance)
302  cur_sumsq.AddVec2(1.0, frame_to_add);
303  }
304  }
305  int32 window_frames = window_end - window_start;
306  last_window_start = window_start;
307  last_window_end = window_end;
308 
309  KALDI_ASSERT(window_frames > 0);
310  SubVector<double> input_frame(input, t),
311  output_frame(*output, t);
312  output_frame.CopyFromVec(input_frame);
313  output_frame.AddVec(-1.0 / window_frames, cur_sum);
314 
315  if (opts.normalize_variance) {
316  if (window_frames == 1) {
317  output_frame.Set(0.0);
318  } else {
319  Vector<double> variance(cur_sumsq);
320  variance.Scale(1.0 / window_frames);
321  variance.AddVec2(-1.0 / (window_frames * window_frames), cur_sum);
322  // now "variance" is the variance of the features in the window,
323  // around their own mean.
324  int32 num_floored;
325  variance.ApplyFloor(1.0e-10, &num_floored);
326  if (num_floored > 0 && num_frames > 1) {
327  if (opts.max_warnings == warning_count) {
328  KALDI_WARN << "Suppressing the remaining variance flooring "
329  << "warnings. Run program with --max-warnings=-1 to "
330  << "see all warnings.";
331  }
332  // If opts.max_warnings is a negative number, we won't restrict the
333  // number of times that the warning is printed out.
334  else if (opts.max_warnings < 0
335  || opts.max_warnings > warning_count) {
336  KALDI_WARN << "Flooring when normalizing variance, floored "
337  << num_floored << " elements; num-frames was "
338  << window_frames;
339  }
340  warning_count++;
341  }
342  variance.ApplyPow(-0.5); // get inverse standard deviation.
343  output_frame.MulElements(variance);
344  }
345  }
346  }
347 }
kaldi::int32 int32
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ SlowMatMul()

static void kaldi::SlowMatMul ( )
static

Definition at line 169 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), rnnlm::i, and kNoTrans.

169  {
170  MatrixIndexT N = 1000;
171  Matrix<Real> M(N, N), P(N, N), Q(N, N);
172  for (MatrixIndexT i = 0; i < 10000; i++) {
173  Q.AddMatMat(1.0, M, kNoTrans, P, kNoTrans, 0.0);
174  }
175 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98

◆ SolveDoubleQuadraticMatrixProblem() [1/2]

template float kaldi::SolveDoubleQuadraticMatrixProblem ( const MatrixBase< float > &  G,
const SpMatrix< float > &  P1,
const SpMatrix< float > &  P2,
const SpMatrix< float > &  Q1,
const SpMatrix< float > &  Q2,
const SolverOptions opts,
MatrixBase< float > *  M 
)

◆ SolveDoubleQuadraticMatrixProblem() [2/2]

template double kaldi::SolveDoubleQuadraticMatrixProblem ( const MatrixBase< double > &  G,
const SpMatrix< double > &  P1,
const SpMatrix< double > &  P2,
const SpMatrix< double > &  Q1,
const SpMatrix< double > &  Q2,
const SolverOptions opts,
MatrixBase< double > *  M 
)

◆ SolveQuadraticMatrixProblem() [1/2]

template float kaldi::SolveQuadraticMatrixProblem ( const SpMatrix< float > &  Q,
const MatrixBase< float > &  Y,
const SpMatrix< float > &  SigmaInv,
const SolverOptions opts,
MatrixBase< float > *  M 
)

◆ SolveQuadraticMatrixProblem() [2/2]

template double kaldi::SolveQuadraticMatrixProblem ( const SpMatrix< double > &  Q,
const MatrixBase< double > &  Y,
const SpMatrix< double > &  SigmaInv,
const SolverOptions opts,
MatrixBase< double > *  M 
)

◆ SolveQuadraticProblem() [1/2]

double SolveQuadraticProblem ( const SpMatrix< double > &  H,
const VectorBase< double > &  g,
const SolverOptions opts,
VectorBase< double > *  x 
)

Definition at line 635 of file sp-matrix.cc.

References VectorBase< Real >::AddMatVec(), VectorBase< Real >::AddSpVec(), VectorBase< Real >::AddVec(), SpMatrix< Real >::AddVec2Sp(), VectorBase< Real >::ApplyFloor(), VectorBase< Real >::ApplyPow(), SolverOptions::Check(), VectorBase< Real >::CopyDiagFromSp(), VectorBase< Real >::CopyFromVec(), SolverOptions::diagonal_precondition, VectorBase< Real >::Dim(), VectorBase< Real >::DivElements(), SolverOptions::eps, rnnlm::i, VectorBase< Real >::InvertElements(), SpMatrix< Real >::IsZero(), SolverOptions::K, KALDI_ASSERT, KALDI_LOG, KALDI_WARN, kNoTrans, kTrans, VectorBase< Real >::Max(), VectorBase< Real >::MulElements(), SolverOptions::name, PackedMatrix< Real >::NumRows(), SolverOptions::optimize_delta, SolverOptions::print_debug_output, SpMatrix< Real >::SymPosSemiDefEig(), VecSpVec(), and VecVec().

Referenced by LinearCgd(), SolveDoubleQuadraticMatrixProblem(), SolveQuadraticProblem(), SolverOptions::SolverOptions(), UnitTestSolve(), MleSgmm2SpeakerAccs::UpdateNoU(), EbwAmSgmm2Updater::UpdatePhoneVectorsInternal(), MleAmSgmm2Updater::UpdatePhoneVectorsInternal(), EbwAmSgmm2Updater::UpdateU(), MleAmSgmm2Updater::UpdateU(), EbwAmSgmm2Updater::UpdateW(), MleAmSgmm2Updater::UpdateW(), IvectorExtractorStats::UpdateWeight(), and MleSgmm2SpeakerAccs::UpdateWithU().

638  {
639  KALDI_ASSERT(H.NumRows() == g.Dim() && g.Dim() == x->Dim() && x->Dim() != 0);
640  opts.Check();
641  MatrixIndexT dim = x->Dim();
642  if (H.IsZero(0.0)) {
643  KALDI_WARN << "Zero quadratic term in quadratic vector problem for "
644  << opts.name << ": leaving it unchanged.";
645  return 0.0;
646  }
647  if (opts.diagonal_precondition) {
648  // We can re-cast the problem with a diagonal preconditioner to
649  // make H better-conditioned.
650  Vector<double> H_diag(dim);
651  H_diag.CopyDiagFromSp(H);
652  H_diag.ApplyFloor(std::numeric_limits<double>::min() * 1.0E+3);
653  Vector<double> H_diag_sqrt(H_diag);
654  H_diag_sqrt.ApplyPow(0.5);
655  Vector<double> H_diag_inv_sqrt(H_diag_sqrt);
656  H_diag_inv_sqrt.InvertElements();
657  Vector<double> x_scaled(*x);
658  x_scaled.MulElements(H_diag_sqrt);
659  Vector<double> g_scaled(g);
660  g_scaled.MulElements(H_diag_inv_sqrt);
661  SpMatrix<double> H_scaled(dim);
662  H_scaled.AddVec2Sp(1.0, H_diag_inv_sqrt, H, 0.0);
663  double ans;
664  SolverOptions new_opts(opts);
665  new_opts.diagonal_precondition = false;
666  ans = SolveQuadraticProblem(H_scaled, g_scaled, new_opts, &x_scaled);
667  x->CopyFromVec(x_scaled);
668  x->MulElements(H_diag_inv_sqrt);
669  return ans;
670  }
671  Vector<double> gbar(g);
672  if (opts.optimize_delta) gbar.AddSpVec(-1.0, H, *x, 1.0); // gbar = g - H x
673  Matrix<double> U(dim, dim);
674  Vector<double> l(dim);
675  H.SymPosSemiDefEig(&l, &U); // does svd H = U L V^T and checks that H == U L U^T to within a tolerance.
676  // floor l.
677  double f = std::max(static_cast<double>(opts.eps), l.Max() / opts.K);
678  MatrixIndexT nfloored = 0;
679  for (MatrixIndexT i = 0; i < dim; i++) { // floor l.
680  if (l(i) < f) {
681  nfloored++;
682  l(i) = f;
683  }
684  }
685  if (nfloored != 0 && opts.print_debug_output) {
686  KALDI_LOG << "Solving quadratic problem for " << opts.name
687  << ": floored " << nfloored<< " eigenvalues. ";
688  }
689  Vector<double> tmp(dim);
690  tmp.AddMatVec(1.0, U, kTrans, gbar, 0.0); // tmp = U^T \bar{g}
691  tmp.DivElements(l); // divide each element of tmp by l: tmp = \tilde{L}^{-1} U^T \bar{g}
692  Vector<double> delta(dim);
693  delta.AddMatVec(1.0, U, kNoTrans, tmp, 0.0); // delta = U tmp = U \tilde{L}^{-1} U^T \bar{g}
694  Vector<double> &xhat(tmp);
695  xhat.CopyFromVec(delta);
696  if (opts.optimize_delta) xhat.AddVec(1.0, *x); // xhat = x + delta.
697  double auxf_before = VecVec(g, *x) - 0.5 * VecSpVec(*x, H, *x),
698  auxf_after = VecVec(g, xhat) - 0.5 * VecSpVec(xhat, H, xhat);
699  if (auxf_after < auxf_before) { // Reject change.
700  if (auxf_after < auxf_before - 1.0e-10 && opts.print_debug_output)
701  KALDI_WARN << "Optimizing vector auxiliary function for "
702  << opts.name<< ": auxf decreased " << auxf_before
703  << " to " << auxf_after << ", change is "
704  << (auxf_after-auxf_before);
705  return 0.0;
706  } else {
707  x->CopyFromVec(xhat);
708  return auxf_after - auxf_before;
709  }
710 }
double SolveQuadraticProblem(const SpMatrix< double > &H, const VectorBase< double > &g, const SolverOptions &opts, VectorBase< double > *x)
Definition: sp-matrix.cc:635
MatrixIndexT NumRows() const
template double VecSpVec(const VectorBase< double > &v1, const SpMatrix< double > &M, const VectorBase< double > &v2)
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void SymPosSemiDefEig(VectorBase< Real > *s, MatrixBase< Real > *P, Real tolerance=0.001) const
This is the version of SVD that we implement for symmetric positive definite matrices.
Definition: sp-matrix.cc:57
#define KALDI_LOG
Definition: kaldi-error.h:153
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37
bool IsZero(Real cutoff=1.0e-05) const
Definition: sp-matrix.cc:507

◆ SolveQuadraticProblem() [2/2]

float SolveQuadraticProblem ( const SpMatrix< float > &  H,
const VectorBase< float > &  g,
const SolverOptions opts,
VectorBase< float > *  x 
)

Definition at line 712 of file sp-matrix.cc.

References VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Dim(), KALDI_ASSERT, PackedMatrix< Real >::NumRows(), and SolveQuadraticProblem().

715  {
716  KALDI_ASSERT(H.NumRows() == g.Dim() && g.Dim() == x->Dim() && x->Dim() != 0);
717  SpMatrix<double> Hd(H);
718  Vector<double> gd(g);
719  Vector<double> xd(*x);
720  float ans = static_cast<float>(SolveQuadraticProblem(Hd, gd, opts, &xd));
721  x->CopyFromVec(xd);
722  return ans;
723 }
double SolveQuadraticProblem(const SpMatrix< double > &H, const VectorBase< double > &g, const SolverOptions &opts, VectorBase< double > *x)
Definition: sp-matrix.cc:635
MatrixIndexT NumRows() const
void CopyFromVec(const VectorBase< Real > &v)
Copy data from another vector (must match own size).
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ SortAndUniq()

void kaldi::SortAndUniq ( std::vector< T > *  vec)
inline

Sorts and uniq's (removes duplicates) from a vector.

Definition at line 39 of file stl-utils.h.

Referenced by ComputationGraphBuilder::AddDependencies(), AutomaticallyObtainQuestions(), HmmTopology::Check(), Nnet::Check(), kaldi::nnet3::ComputeCommandAttributes(), kaldi::nnet3::ComputeComputationGraph(), kaldi::nnet3::ComputeComputationPhasesForEpoch(), kaldi::nnet3::ComputeMatrixAccesses(), ComputationVariables::ComputeSplitPoints(), kaldi::nnet3::ComputeVariableAccesses(), ConstIntegerSet< EventValueType >::ConstIntegerSet(), ContextDependency::EnumeratePairs(), WordAlignLatticeLexiconInfo::FinalizeViabilityMap(), kaldi::nnet3::FindNStride(), GenerateLexicon(), GenRandStats(), GetHTransducer(), ContextDependency::GetPdfInfo(), GetPdfsForPhones(), GetPhonesForPdfs(), kaldi::nnet3::time_height_convolution::GetRandomConvolutionIndexes(), kaldi::nnet3::time_height_convolution::GetRandomConvolutionModel(), kaldi::nnet3::IndexesMultiToSubmatrixIndexes(), ConstIntegerSet< EventValueType >::Init(), TimeHeightConvolutionComponent::InitFromConfig(), Questions::InitRand(), InverseLeftBiphoneContextFst::InverseLeftBiphoneContextFst(), KMeansClusterPhones(), main(), kaldi::nnet3::MakeSccGraph(), SplitEventMap::MapValues(), kaldi::nnet3::NnetToDirectedGraph(), ProcessTopo(), ComputationGraphBuilder::PruneDependencies(), ReadSymbolTableAsIntegers(), RenumberEventMap(), ShareEventMapLeaves(), SingleUtteranceGmmDecoder::SingleUtteranceGmmDecoder(), Compiler::SplitByScale(), TestClusterEventMapGetMappingAndRenumberEventMap(), TestClusterEventMapGetMappingAndRenumberEventMap2(), TestEventMapPrune(), fst::TestMakeLinearAcceptor(), TestShareEventMapLeaves(), TestSortAndUniq(), TrainingGraphCompiler::TrainingGraphCompiler(), kaldi::nnet2::UnitTestSolvePackingProblem(), and WordAlignLatticeLexiconInfo::UpdateEquivalenceMap().

39  {
40  std::sort(vec->begin(), vec->end());
41  vec->erase(std::unique(vec->begin(), vec->end()), vec->end());
42 }

◆ SortSvd() [1/2]

template void kaldi::SortSvd ( VectorBase< float > *  s,
MatrixBase< float > *  U,
MatrixBase< float > *  Vt,
bool   
)

◆ SortSvd() [2/2]

template void kaldi::SortSvd ( VectorBase< double > *  s,
MatrixBase< double > *  U,
MatrixBase< double > *  Vt,
bool   
)

Referenced by SortSvd().

◆ SparseMatrixUnitTest()

void kaldi::SparseMatrixUnitTest ( )

Definition at line 314 of file sparse-matrix-test.cc.

References rnnlm::i.

314  {
315  // SparseVector
316  UnitTestSparseVectorSum<Real>();
317  UnitTestSparseVectorAddToVec<Real>();
318  UnitTestSparseVectorMax<Real>();
319  UnitTestSparseVectorVecSvec<Real>();
320 
321  // SparseMatrix
322  UnitTestSparseMatrixSum<Real>();
323  UnitTestSparseMatrixFrobeniusNorm<Real>();
324  UnitTestSparseMatrixAddToMat<Real>();
325  UnitTestSparseMatrixTraceMatSmat<Real>();
326  for (int32 i = 0; i < 30; i++)
327  UnitTestSparseMatrixConstructor<Real>();
328 
329 
330  // Matrix functions involving sparse matrices.
331  UnitTestMatrixAddMatSmat<Real>();
332  UnitTestMatrixAddSmatMat<Real>();
333 }
kaldi::int32 int32

◆ SplitArgOnEquals()

void kaldi::SplitArgOnEquals ( const std::string &  arg,
std::string *  name,
std::string *  rspecifier 
)

Definition at line 33 of file nnet3-get-egs-simple.cc.

References ClassifyRspecifier(), IsToken(), KALDI_ERR, and kNoRspecifier.

Referenced by main().

35  {
36  size_t pos = arg.find_first_of('=');
37  if (pos == std::string::npos) {
38  KALDI_ERR << "Bad command line argument (expecting '='): "
39  << arg;
40  }
41  *name = std::string(arg, 0, pos);
42  *rspecifier = std::string(arg, pos + 1);
43  if (!IsToken(*name)) {
44  KALDI_ERR << "Bad command line argument (expecting a valid name before '='): "
45  << arg;
46  }
47  if (ClassifyRspecifier(*rspecifier, NULL, NULL) == kNoRspecifier) {
48  KALDI_ERR << "Bad command line argument (expecting an rspecifier after '='): "
49  << arg;
50  }
51 }
RspecifierType ClassifyRspecifier(const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
Definition: kaldi-table.cc:225
bool IsToken(const std::string &token)
Returns true if "token" is nonempty, and all characters are printable and whitespace-free.
Definition: text-utils.cc:105
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ SplitEgsKey()

bool kaldi::SplitEgsKey ( const std::string &  key,
std::string *  utt_id,
int32 frame_id 
)

Definition at line 34 of file nnet-relabel-egs.cc.

Referenced by main().

35  {
36  size_t start = 0, found = 0, end = key.size();
37  utt_id->clear();
38 
39  found = key.find_last_of("-", end);
40  // start != end condition is for when the delimiter is at the end
41 
42  if (found != start && start != end && found < end) {
43  *utt_id = key.substr(start, found - start);
44  std::istringstream tmp(key.substr(found + 1, end));
45  tmp >> *frame_id;
46  return true;
47  }
48 
49  return false;
50  }

◆ SplitStringOnFirstSpace()

void SplitStringOnFirstSpace ( const std::string &  line,
std::string *  first,
std::string *  rest 
)

Removes leading and trailing white space from the string, then splits on the first section of whitespace found (if present), putting the part before the whitespace in "first" and the rest in "rest".

If there is no such space, everything that remains after removing leading and trailing whitespace goes in "first".

Definition at line 120 of file text-utils.cc.

References KALDI_ASSERT.

Referenced by ConvertStringToInteger(), SequentialTableReaderScriptImpl< Holder >::NextScpLine(), ReadScriptFile(), and TestSplitStringOnFirstSpace().

122  {
123  const char *white_chars = " \t\n\r\f\v";
124  typedef std::string::size_type I;
125  const I npos = std::string::npos;
126  I first_nonwhite = str.find_first_not_of(white_chars);
127  if (first_nonwhite == npos) {
128  first->clear();
129  rest->clear();
130  return;
131  }
132  // next_white is first whitespace after first nonwhitespace.
133  I next_white = str.find_first_of(white_chars, first_nonwhite);
134 
135  if (next_white == npos) { // no more whitespace...
136  *first = std::string(str, first_nonwhite);
137  rest->clear();
138  return;
139  }
140  I next_nonwhite = str.find_first_not_of(white_chars, next_white);
141  if (next_nonwhite == npos) {
142  *first = std::string(str, first_nonwhite, next_white-first_nonwhite);
143  rest->clear();
144  return;
145  }
146 
147  I last_nonwhite = str.find_last_not_of(white_chars);
148  KALDI_ASSERT(last_nonwhite != npos); // or coding error.
149 
150  *first = std::string(str, first_nonwhite, next_white-first_nonwhite);
151  *rest = std::string(str, next_nonwhite, last_nonwhite+1-next_nonwhite);
152 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ SplitStringToFloats() [1/3]

bool SplitStringToFloats ( const std::string &  full,
const char *  delim,
bool  omit_empty_strings,
std::vector< F > *  out 
)

Definition at line 30 of file text-utils.cc.

References ConvertStringToReal(), full, rnnlm::i, KALDI_ASSERT, and SplitStringToVector().

Referenced by GetWeights(), main(), PreparePriors(), SplitStringToIntegers(), SplitStringToWeights(), and TestSplitStringToFloats().

33  {
34  KALDI_ASSERT(out != NULL);
35  if (*(full.c_str()) == '\0') {
36  out->clear();
37  return true;
38  }
39  std::vector<std::string> split;
40  SplitStringToVector(full, delim, omit_empty_strings, &split);
41  out->resize(split.size());
42  for (size_t i = 0; i < split.size(); i++) {
43  F f = 0;
44  if (!ConvertStringToReal(split[i], &f))
45  return false;
46  (*out)[i] = f;
47  }
48  return true;
49 }
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
template bool ConvertStringToReal(const std::string &str, double *out)

◆ SplitStringToFloats() [2/3]

template bool kaldi::SplitStringToFloats ( const std::string &  full,
const char *  delim,
bool  omit_empty_strings,
std::vector< float > *  out 
)

◆ SplitStringToFloats() [3/3]

template bool kaldi::SplitStringToFloats ( const std::string &  full,
const char *  delim,
bool  omit_empty_strings,
std::vector< double > *  out 
)

◆ SplitStringToIntegers()

bool kaldi::SplitStringToIntegers ( const std::string &  full,
const char *  delim,
bool  omit_empty_strings,
std::vector< I > *  out 
)

Split a string (e.g.

1:2:3) into a vector of integers.

Parameters
[in]delimString containing a list of characters, any of which is allowed as a delimiter.
[in]omit_empty_stringsIf true, empty strings between delimiters are allowed and will not produce an output integer; if false, instances of characters in 'delim' that are consecutive or at the start or end of the string would be an error. You'll normally want this to be true if 'delim' consists of spaces, and false otherwise.
[out]outThe output list of integers.

Definition at line 68 of file text-utils.h.

References full, rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_ASSERT_IS_INTEGER_TYPE, KALDI_STRTOLL, SplitStringToFloats(), and SplitStringToVector().

Referenced by AccumulateTreeStatsInfo::AccumulateTreeStatsInfo(), ExampleGenerationConfig::ComputeDerived(), DiscriminativeComputation::DiscriminativeComputation(), ExtractObjectRange(), GetSkipLayers(), ConfigLine::GetValue(), Splice::InitData(), BlockSoftmax::InitData(), CopyComponent::InitData(), TimeHeightConvolutionComponent::InitFromConfig(), TdnnComponent::InitFromConfig(), PermuteComponent::InitFromConfig(), main(), NnetDiscriminativeUpdater::NnetDiscriminativeUpdater(), OnlineCmvn::OnlineCmvn(), OnlineSilenceWeighting::OnlineSilenceWeighting(), kaldi::nnet2::ParseFromString(), ExampleMergingConfig::ParseIntSet(), ParseMatrixRangeSpecifier(), fst::ReadFstKaldi(), ReadIntegerVectorVectorSimple(), ReadLexiconForWordAlign(), ReadSharedPhonesList(), WordBoundaryInfo::SetOptions(), SingleUtteranceGmmDecoder::SingleUtteranceGmmDecoder(), kaldi::nnet3::SummarizeVector(), TestSplitStringToIntegers(), and TrailingSilenceLength().

73  {
74  KALDI_ASSERT(out != NULL);
76  if (*(full.c_str()) == '\0') {
77  out->clear();
78  return true;
79  }
80  std::vector<std::string> split;
81  SplitStringToVector(full, delim, omit_empty_strings, &split);
82  out->resize(split.size());
83  for (size_t i = 0; i < split.size(); i++) {
84  const char *this_str = split[i].c_str();
85  char *end = NULL;
86  int64 j = 0;
87  j = KALDI_STRTOLL(this_str, &end);
88  if (end == this_str || *end != '\0') {
89  out->clear();
90  return false;
91  } else {
92  I jI = static_cast<I>(j);
93  if (static_cast<int64>(jI) != j) {
94  // output type cannot fit this integer.
95  out->clear();
96  return false;
97  }
98  (*out)[i] = jI;
99  }
100  }
101  return true;
102 }
#define KALDI_ASSERT_IS_INTEGER_TYPE(I)
Definition: kaldi-utils.h:133
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_STRTOLL(cur_cstr, end_cstr)
Definition: kaldi-utils.h:152

◆ SplitStringToVector()

void SplitStringToVector ( const std::string &  full,
const char *  delim,
bool  omit_empty_strings,
std::vector< std::string > *  out 
)

Split a string using any of the single character delimiters.

If omit_empty_strings == true, the output will contain any nonempty strings after splitting on any of the characters in the delimiter. If omit_empty_strings == false, the output will contain n+1 strings if there are n characters in the set "delim" within the input string. In this case the empty string is split to a single empty string.

Definition at line 63 of file text-utils.cc.

Referenced by ClassifyRspecifier(), ClassifyWspecifier(), ExampleMergingConfig::ComputeDerived(), CopyExcludedFeats(), CopyIncludedFeats(), CopySubsetLattices(), ExtractObjectRange(), ExtractRangeSpecifier(), GetUtterancePairs(), WordBoundaryInfo::Init(), TimeHeightConvolutionComponent::InitFromConfig(), MultiTaskLoss::InitFromString(), main(), kaldi::nnet2::ParseFromString(), ExampleMergingConfig::ParseIntSet(), ParseMatrixRangeSpecifier(), PrepareMap(), kaldi::nnet3::ProcessRangeFile(), ArpaFileParser::Read(), TokenVectorHolder::Read(), ReadCommaSeparatedCommand(), fst::ReadFstKaldi(), LatticeReader::ReadText(), Fmpe::SetContexts(), SplitStringToFloats(), SplitStringToIntegers(), and TestSplitStringToVector().

65  {
66  size_t start = 0, found = 0, end = full.size();
67  out->clear();
68  while (found != std::string::npos) {
69  found = full.find_first_of(delim, start);
70  // start != end condition is for when the delimiter is at the end
71  if (!omit_empty_strings || (found != start && start != end))
72  out->push_back(full.substr(start, found - start));
73  start = found + 1;
74  }
75 }

◆ SplitStringToWeights()

void kaldi::SplitStringToWeights ( const string &  full,
const char *  delim,
vector< BaseFloat > *  out 
)

Definition at line 91 of file lattice-combine.cc.

References KALDI_WARN, and SplitStringToFloats().

Referenced by main().

92  {
93  vector<BaseFloat> tmp;
94  SplitStringToFloats(full, delim, true /*omit empty strings*/, &tmp);
95  if (tmp.size() != out->size()) {
96  KALDI_WARN << "Expecting " << out->size() << " weights, found " << tmp.size()
97  << ": using uniform weights.";
98  return;
99  }
100  BaseFloat sum = 0;
101  for (vector<BaseFloat>::const_iterator itr = tmp.begin();
102  itr != tmp.end(); ++itr) {
103  if (*itr < 0.0) {
104  KALDI_WARN << "Cannot use negative weight: " << *itr << "; input string: "
105  << full << "\n\tUsing uniform weights.";
106  return;
107  }
108  sum += (*itr);
109  }
110  if (sum != 1.0) {
111  KALDI_WARN << "Weights sum to " << sum << " instead of 1: renormalizing";
112  for (vector<BaseFloat>::iterator itr = tmp.begin();
113  itr != tmp.end(); ++itr)
114  (*itr) /= sum;
115  }
116  out->swap(tmp);
117 }
bool SplitStringToFloats(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< F > *out)
Definition: text-utils.cc:30
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ SplitToPhonesInternal()

static bool kaldi::SplitToPhonesInternal ( const TransitionModel trans_model,
const std::vector< int32 > &  alignment,
bool  reordered,
std::vector< std::vector< int32 > > *  split_output 
)
static

Definition at line 659 of file hmm-utils.cc.

References TransitionModel::GetTopo(), rnnlm::i, TransitionModel::IsFinal(), TransitionModel::IsSelfLoop(), rnnlm::j, KALDI_ASSERT, kNoPdf, HmmTopology::TopologyForPhone(), TransitionModel::TransitionIdToTransitionState(), TransitionModel::TransitionStateToHmmState(), and TransitionModel::TransitionStateToPhone().

Referenced by SplitToPhones().

662  {
663  if (alignment.empty()) return true; // nothing to split.
664  std::vector<size_t> end_points; // points at which phones end [in an
665  // stl iterator sense, i.e. actually one past the last transition-id within
666  // each phone]..
667 
668  bool was_ok = true;
669  for (size_t i = 0; i < alignment.size(); i++) {
670  int32 trans_id = alignment[i];
671  if (trans_model.IsFinal(trans_id)) { // is final-prob
672  if (!reordered) end_points.push_back(i+1);
673  else { // reordered.
674  while (i+1 < alignment.size() &&
675  trans_model.IsSelfLoop(alignment[i+1])) {
676  KALDI_ASSERT(trans_model.TransitionIdToTransitionState(alignment[i]) ==
677  trans_model.TransitionIdToTransitionState(alignment[i+1]));
678  i++;
679  }
680  end_points.push_back(i+1);
681  }
682  } else if (i+1 == alignment.size()) {
683  // need to have an end-point at the actual end.
684  // but this is an error- should have been detected already.
685  was_ok = false;
686  end_points.push_back(i+1);
687  } else {
688  int32 this_state = trans_model.TransitionIdToTransitionState(alignment[i]),
689  next_state = trans_model.TransitionIdToTransitionState(alignment[i+1]);
690  if (this_state == next_state) continue; // optimization.
691  int32 this_phone = trans_model.TransitionStateToPhone(this_state),
692  next_phone = trans_model.TransitionStateToPhone(next_state);
693  if (this_phone != next_phone) {
694  // The phone changed, but this is an error-- we should have detected this via the
695  // IsFinal check.
696  was_ok = false;
697  end_points.push_back(i+1);
698  }
699  }
700  }
701 
702  size_t cur_point = 0;
703  for (size_t i = 0; i < end_points.size(); i++) {
704  split_output->push_back(std::vector<int32>());
705  // The next if-statement checks if the initial trans-id at the current end
706  // point is the initial-state of the current phone if that initial-state
707  // is emitting (a cursory check that the alignment is plausible).
708  int32 trans_state =
709  trans_model.TransitionIdToTransitionState(alignment[cur_point]);
710  int32 phone = trans_model.TransitionStateToPhone(trans_state);
711  int32 forward_pdf_class = trans_model.GetTopo().TopologyForPhone(phone)[0].forward_pdf_class;
712  if (forward_pdf_class != kNoPdf) // initial-state of the current phone is emitting
713  if (trans_model.TransitionStateToHmmState(trans_state) != 0)
714  was_ok = false;
715  for (size_t j = cur_point; j < end_points[i]; j++)
716  split_output->back().push_back(alignment[j]);
717  cur_point = end_points[i];
718  }
719  return was_ok;
720 }
kaldi::int32 int32
static const int32 kNoPdf
A constant used in the HmmTopology class as the pdf-class kNoPdf, which is used when a HMM-state is n...
Definition: hmm-topology.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ StringsApproxEqual()

bool StringsApproxEqual ( const std::string &  a,
const std::string &  b,
int32  decimal_places_check = 2 
)

This function returns true when two text strings are approximately equal, and false when they are not.

The definition of 'equal' is normal string equality, except that two substrings like "0.31134" and "0.311341" would be considered equal. 'decimal_places_tolerance' controls how many digits after the '.' have to match up. E.g. StringsApproxEqual("hello 0.23 there", "hello 0.24 there", 2) would return false because there is a difference in the 2nd decimal, but with an argument of 1 it would return true.

Definition at line 335 of file text-utils.cc.

References StringsApproxEqualInternal().

Referenced by kaldi::nnet3::CheckStringsApproxEqual(), ConvertStringToInteger(), kaldi::nnet3::TestNnetComponentCopy(), kaldi::nnet3::TestNnetComponentUpdatable(), and TestStringsApproxEqual().

337  {
338  return StringsApproxEqualInternal(a.c_str(), b.c_str(),
339  decimal_places_tolerance, -1);
340 }
bool StringsApproxEqualInternal(const char *a, const char *b, int32 decimal_places_tolerance, int32 places_into_number)
Definition: text-utils.cc:286

◆ StringsApproxEqualInternal()

bool kaldi::StringsApproxEqualInternal ( const char *  a,
const char *  b,
int32  decimal_places_tolerance,
int32  places_into_number 
)

Definition at line 286 of file text-utils.cc.

Referenced by StringsApproxEqual().

288  {
289 start:
290  char ca = *a, cb = *b;
291  if (ca == cb) {
292  if (ca == '\0') {
293  return true;
294  } else {
295  if (places_into_number >= 0) {
296  if (isdigit(ca)) {
297  places_into_number++;
298  } else {
299  places_into_number = -1;
300  }
301  } else {
302  if (ca == '.') {
303  places_into_number = 0;
304  }
305  }
306  a++;
307  b++;
308  goto start;
309  }
310  } else {
311  if (places_into_number >= decimal_places_tolerance &&
312  (isdigit(ca) || isdigit(cb))) {
313  // we're potentially willing to accept this difference between the
314  // strings.
315  if (isdigit(ca)) a++;
316  if (isdigit(cb)) b++;
317  // we'll have advanced at least one of the two strings.
318  goto start;
319  } else if (places_into_number >= 0 &&
320  ((ca == '0' && !isdigit(cb)) || (cb == '0' && !isdigit(ca)))) {
321  // this clause is designed to ensure that, for example,
322  // "0.1" would count the same as "0.100001".
323  if (ca == '0') a++;
324  else b++;
325  places_into_number++;
326  goto start;
327  } else {
328  return false;
329  }
330  }
331 
332 }

◆ StringToGmmFlags()

GmmFlagsType StringToGmmFlags ( std::string  str)

Convert string which is some subset of "mSwa" to flags.

Definition at line 26 of file model-common.cc.

References CharToString(), KALDI_ERR, kGmmAll, kGmmMeans, kGmmTransitions, kGmmVariances, and kGmmWeights.

Referenced by main().

26  {
27  GmmFlagsType flags = 0;
28  for (const char *c = str.c_str(); *c != '\0'; c++) {
29  switch (*c) {
30  case 'm': flags |= kGmmMeans; break;
31  case 'v': flags |= kGmmVariances; break;
32  case 'w': flags |= kGmmWeights; break;
33  case 't': flags |= kGmmTransitions; break;
34  case 'a': flags |= kGmmAll; break;
35  default: KALDI_ERR << "Invalid element " << CharToString(*c)
36  << " of GmmFlagsType option string "
37  << str;
38  }
39  }
40  return flags;
41 }
uint16 GmmFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:35
#define KALDI_ERR
Definition: kaldi-error.h:147
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36

◆ StringToSgmmUpdateFlags()

SgmmUpdateFlagsType StringToSgmmUpdateFlags ( std::string  str)

Definition at line 64 of file model-common.cc.

References CharToString(), KALDI_ERR, kSgmmAll, kSgmmCovarianceMatrix, kSgmmPhoneProjections, kSgmmPhoneVectors, kSgmmPhoneWeightProjections, kSgmmSpeakerProjections, kSgmmSpeakerWeightProjections, kSgmmSubstateWeights, and kSgmmTransitions.

Referenced by main().

64  {
65  SgmmUpdateFlagsType flags = 0;
66  for (const char *c = str.c_str(); *c != '\0'; c++) {
67  switch (*c) {
68  case 'v': flags |= kSgmmPhoneVectors; break;
69  case 'M': flags |= kSgmmPhoneProjections; break;
70  case 'w': flags |= kSgmmPhoneWeightProjections; break;
71  case 'S': flags |= kSgmmCovarianceMatrix; break;
72  case 'c': flags |= kSgmmSubstateWeights; break;
73  case 'N': flags |= kSgmmSpeakerProjections; break;
74  case 't': flags |= kSgmmTransitions; break;
75  case 'u': flags |= kSgmmSpeakerWeightProjections; break;
76  case 'a': flags |= kSgmmAll; break;
77  default: KALDI_ERR << "Invalid element " << CharToString(*c)
78  << " of SgmmUpdateFlagsType option string "
79  << str;
80  }
81  }
82  return flags;
83 }
t .. not really part of SGMM.
Definition: model-common.h:55
uint16 SgmmUpdateFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:59
The letters correspond to the variable names.
Definition: model-common.h:48
#define KALDI_ERR
Definition: kaldi-error.h:147
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
u [ for SSGMM ]
Definition: model-common.h:56

◆ StringToSgmmWriteFlags()

SgmmWriteFlagsType StringToSgmmWriteFlags ( std::string  str)

Definition at line 86 of file model-common.cc.

References CharToString(), KALDI_ERR, kSgmmAll, kSgmmBackgroundGmms, kSgmmGlobalParams, kSgmmNormalizers, and kSgmmStateParams.

Referenced by main().

86  {
87  SgmmWriteFlagsType flags = 0;
88  for (const char *c = str.c_str(); *c != '\0'; c++) {
89  switch (*c) {
90  case 'g': flags |= kSgmmGlobalParams; break;
91  case 's': flags |= kSgmmStateParams; break;
92  case 'n': flags |= kSgmmNormalizers; break;
93  case 'u': flags |= kSgmmBackgroundGmms; break;
94  case 'a': flags |= kSgmmAll; break;
95  default: KALDI_ERR << "Invalid element " << CharToString(*c)
96  << " of SgmmWriteFlagsType option string "
97  << str;
98  }
99  }
100  return flags;
101 }
uint16 SgmmWriteFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:70
#define KALDI_ERR
Definition: kaldi-error.h:147
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
u [ for SSGMM ]
Definition: model-common.h:56

◆ SubtractMovingAverage()

void kaldi::SubtractMovingAverage ( int32  normalization_window_size,
Matrix< BaseFloat > *  mat 
)

Definition at line 49 of file process-pitch-feats.cc.

References rnnlm::i, and MatrixBase< Real >::NumRows().

Referenced by main().

50  {
51  int32 num_frames = mat->NumRows();
52  Vector<BaseFloat> temp_pitch(num_frames);
53  Matrix<BaseFloat> &features = *mat;
54  int32 i;
55  for (i = 0; i < num_frames; i++)
56  temp_pitch(i) = features(i, 1);
57 
58  // Moving Window Normalization
59  BaseFloat mean = 0.0;
60  int32 mid_win = (normalization_window_size - 1) / 2;
61  for (i = 0; (i < num_frames) && (i < normalization_window_size); i++) {
62  mean += features(i, 1);
63  }
64  mean /= i;
65 
66  if (num_frames <= normalization_window_size) {
67  for (i = 0; i < num_frames; i++) {
68  features(i, 1) -= mean;
69  }
70  } else {
71  for (i = 0; i <= mid_win; i++) {
72  features(i, 1) -= mean;
73  }
74  for (i = (mid_win + 1); i < num_frames; i++) {
75  if (i + (mid_win + 1) < num_frames)
76  mean -= (temp_pitch(i - (mid_win + 1)) -
77  temp_pitch(i + (mid_win + 1))) / normalization_window_size;
78  features(i,1) -= mean;
79  }
80  }
81 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ swap()

void kaldi::swap ( basic_filebuf< CharT, Traits > &  x,
basic_filebuf< CharT, Traits > &  y 
)
inline

Definition at line 275 of file basic-filebuf.h.

References basic_filebuf< CharT, Traits >::swap().

Referenced by VectorBase< float >::AddDiagMatMat(), CuMatrixBase< float >::AddDiagVecMat(), MatrixBase< float >::AddDiagVecMat(), CuMatrixBase< float >::AddMatBlock(), CuMatrixBase< float >::AddMatDiagVec(), MatrixBase< float >::AddMatDiagVec(), CuBlockMatrix< Real >::AddMatMat(), MatrixBase< float >::AddMatMatMat(), ChangeReorderingOfAlignment(), kaldi::nnet3::CheckComputationOnline(), PosteriorHolder::Clear(), GaussPostHolder::Clear(), fst::ComposeDeterministicOnDemandInverse(), fst::ConvertLattice(), DiscriminativeSupervisionSplitter::CreateRangeLattice(), DeterminizerStar< F >::Debug(), GeneralDropoutComponent::GetMemo(), GeneralDescriptor::Normalize(), CuSpMatrix< Real >::operator()(), SpMatrix< float >::operator()(), CuPackedMatrix< Real >::operator()(), LatticeDeterminizer< Weight, IntType >::Output(), LatticeLexiconWordAligner::ProcessFinalForceOut(), RandomizeVector(), BottomUpClusterer::ReconstructQueue(), CompartmentalizedBottomUpClusterer::ReconstructQueue(), CompartmentalizedBottomUpClusterer::Renumber(), DctComponent::Reorder(), ReverseVector(), CRnnLM::sortVocab(), RowOpsSplitter::SplitCommand(), basic_filebuf< CharT, Traits >::swap(), SparseVector< Real >::Swap(), SpMatrix< float >::Swap(), TpMatrix< float >::Swap(), IoSpecification::Swap(), CompactLatticeHolder::Swap(), KaldiObjectHolder< KaldiType >::Swap(), CuBlockMatrix< Real >::Swap(), CuSparseMatrix< Real >::Swap(), CuPackedMatrix< Real >::Swap(), DiscriminativeSupervision::Swap(), LatticeHolder::Swap(), VectorFstTplHolder< Arc >::Swap(), GenericHolder< SomeType >::Swap(), WaveData::Swap(), PackedMatrix< float >::Swap(), CuArray< Int32Pair >::Swap(), CompressedMatrix::Swap(), BasicHolder< BasicType >::Swap(), WaveInfoHolder::Swap(), CuVector< float >::Swap(), NnetComputation::MatrixDebugInfo::Swap(), Vector< float >::Swap(), OnlineNaturalGradient::Swap(), HtkMatrixHolder::Swap(), Matrix< BaseFloat >::Swap(), CuMatrix< float >::Swap(), TestClusterBottomUp(), TestEditDistance2(), TestEditDistance2String(), TestHashList(), TestSetOfNumbers(), TraceMatMatMat(), TraceMatMatMatMat(), MatrixBase< float >::Transpose(), UnitTestCuBlockMatrixAddMatBlock(), UnitTestCuBlockMatrixAddMatMat(), UnitTestCuBlockMatrixIO(), UnitTestCuMatrixIO(), UnitTextCuMatrixAddMatSmat(), UnitTextCuMatrixAddSmat(), UnitTextCuMatrixAddSmatMat(), and WordAlignLatticeLexiconInfo::UpdateEquivalenceMap().

275  {
276  x.swap(y);
277 }

◆ SynchronizeGpu()

void SynchronizeGpu ( )

The function SynchronizeGpu(), which for convenience is defined whether or not we have compiled for CUDA, is intended to be called in places where threads need to be synchronized.

It just launches a no-op kernel into the legacy default stream. This will have the effect that it will run after any kernels previously launched from any stream(*), and before kernels that will later be launched from any stream(*). (*) does not apply to non-blocking streams.

Note: at the time of writing we never call SynchronizeGpu() from binary-level code because it hasn't become necessary yet; the only program that might have multiple threads actually using the GPU is rnnlm-train (if the user were to invoke it with the ,bg option for loading training examples); but the only CUDA invocation the RnnlmExample::Read() function uses (via CuMatrix::Read()), is cudaMemcpy, which is synchronous already.

Definition at line 638 of file cu-device.cc.

Referenced by NnetBatchComputer::Compute(), and NnetBatchComputer::FormatOutputs().

638 { }

◆ TakeLogOfPitch()

void kaldi::TakeLogOfPitch ( Matrix< BaseFloat > *  mat)

Definition at line 39 of file process-pitch-feats.cc.

References rnnlm::i, KALDI_ASSERT, Log(), and MatrixBase< Real >::NumRows().

Referenced by main().

39  {
40  int32 num_frames = mat->NumRows();
41  for (int32 i = 0; i < num_frames; i++) {
42  KALDI_ASSERT((*mat)(i, 1) > 0.0);
43  (*mat)(i, 1) = Log((*mat)(i, 1));
44  }
45 }
kaldi::int32 int32
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64

◆ TestAccumulateTreeStatsOptions()

void kaldi::TestAccumulateTreeStatsOptions ( )

Definition at line 188 of file hmm-utils-test.cc.

References AccumulateTreeStatsOptions::central_position, AccumulateTreeStatsInfo::central_position, AccumulateTreeStatsInfo::ci_phones, AccumulateTreeStatsOptions::ci_phones_str, AccumulateTreeStatsOptions::context_width, AccumulateTreeStatsInfo::context_width, KALDI_ASSERT, AccumulateTreeStatsInfo::phone_map, AccumulateTreeStatsOptions::phone_map_rxfilename, RandInt(), AccumulateTreeStatsOptions::var_floor, and AccumulateTreeStatsInfo::var_floor.

Referenced by main().

188  {
189  AccumulateTreeStatsOptions opts;
190  opts.var_floor = RandInt(0, 10);
191  opts.ci_phones_str = "3:2:1";
192  opts.phone_map_rxfilename = "echo 1 2; echo 2 5 |";
193  opts.context_width = RandInt(3, 4);
194  opts.central_position = RandInt(0, 2);
195  AccumulateTreeStatsInfo info(opts);
196  KALDI_ASSERT(info.var_floor == opts.var_floor);
197  KALDI_ASSERT(info.ci_phones.size() == 3 && info.ci_phones[2] == 3);
198  KALDI_ASSERT(info.phone_map.size() == 3 && info.phone_map[2] == 5);
199  KALDI_ASSERT(info.context_width == opts.context_width);
200  KALDI_ASSERT(info.central_position == opts.central_position);
201 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestAddToClusters()

static void kaldi::TestAddToClusters ( )
static

Definition at line 156 of file cluster-utils-test.cc.

References AddToClusters(), AssertEqual(), ScalarClusterable::Copy(), DeletePointers(), rnnlm::i, KALDI_ASSERT, and ScalarClusterable::Mean().

Referenced by main().

156  {
157  ScalarClusterable a(1.0), b(2.5), c(3.0);
158  std::vector<Clusterable*> stats(3);
159  stats[0] = a.Copy(); stats[1] = b.Copy(); stats[2] = c.Copy();
160  std::vector<int32> assignments(3);
161  assignments[0] = 1; assignments[1] = 1; assignments[2] = 4;
162  std::vector<Clusterable*> clusters;
163  std::vector<Clusterable*> clusters2;
164  AddToClusters(stats, assignments, &clusters);
165 
166  AddToClusters(stats, assignments, &clusters2); // do this twice.
167  AddToClusters(stats, assignments, &clusters2);
168 
169  KALDI_ASSERT(clusters.size() == 5);
170  KALDI_ASSERT(clusters[0] == NULL && clusters[1] != NULL && clusters[4] != NULL);
171  for (size_t i = 0;i < 5;i++) {
172  if (clusters[i] != NULL) {
173  AssertEqual(clusters2[i]->Objf(), clusters[i]->Objf()*2);
174  }
175  }
176  AssertEqual(c.Mean(), ((ScalarClusterable*)clusters[4])->Mean());
177  AssertEqual( ((ScalarClusterable*)clusters[1])->Mean(), 0.5*(1.0+2.5));
178  DeletePointers(&stats);
179  DeletePointers(&clusters);
180  DeletePointers(&clusters2);
181 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
void AddToClusters(const std::vector< Clusterable *> &stats, const std::vector< int32 > &assignments, std::vector< Clusterable *> *clusters)
Given stats and a vector "assignments" of the same size (that maps to cluster indices), sums the stats up into "clusters." It will add to any stats already present in "clusters" (although typically "clusters" will be empty when called), and it will extend with NULL pointers for any unseen indices.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
ScalarClusterable clusters scalars with x^2 loss.

◆ TestAddToClustersOptimized()

static void kaldi::TestAddToClustersOptimized ( )
static

Definition at line 183 of file cluster-utils-test.cc.

References ScalarClusterable::Add(), AddToClusters(), AddToClustersOptimized(), AssertEqual(), DeletePointers(), rnnlm::i, KALDI_ASSERT, Rand(), RandGauss(), SumClusterable(), and SumClusterableNormalizer().

Referenced by main().

183  {
184  for (size_t p = 0;p < 100;p++) {
185  size_t n_stats = Rand() % 5;
186  n_stats = n_stats * n_stats; // more interestingly distributed.
187  std::vector<Clusterable*> stats(n_stats);
188  for (size_t i = 0;i < n_stats;i++) {
189  if (Rand() % 5 < 4) {
191  if (Rand() % 2 == 0) ptr->Add(*ptr); // make count equal 2. for more randomness.
192  stats[i] = ptr;
193  } else stats[i] = NULL; // make some zero. supposed to be robust to this.
194  }
195  size_t n_clust = 1 + Rand() % 4;
196  std::vector<int32> assignments(n_stats);
197  for (size_t i = 0;i < assignments.size();i++)
198  assignments[i] = Rand() % n_clust;
199  std::vector<Clusterable*> clusts1;
200  std::vector<Clusterable*> clusts2;
201  Clusterable *total = SumClusterable(stats);
202  if (total == NULL) { // no stats were non-NULL.
203  KALDI_ASSERT(stats.size() == 0 || stats[0] == NULL);
204  DeletePointers(&stats);
205  continue;
206  }
207  AddToClusters(stats, assignments, &clusts1);
208  AddToClustersOptimized(stats, assignments, *total, &clusts2);
209 
210  BaseFloat tot1 = SumClusterableNormalizer(stats),
211  tot2 = SumClusterableNormalizer(clusts1),
212  tot3 = SumClusterableNormalizer(clusts2);
213  AssertEqual(tot1, tot2);
214  AssertEqual(tot1, tot3);
215  KALDI_ASSERT(clusts1.size() == clusts2.size());
216  for (size_t i = 0;i < clusts1.size();i++) {
217  if (clusts1[i] != NULL || clusts2[i] != NULL) {
218  KALDI_ASSERT(clusts1[i] != NULL && clusts2[i] != NULL);
219  AssertEqual(clusts1[i]->Normalizer(), clusts2[i]->Normalizer());
220  AssertEqual( ((ScalarClusterable*)clusts1[i])->Mean(),
221  ((ScalarClusterable*)clusts2[i])->Mean() );
222  }
223  }
224  delete total;
225  DeletePointers(&clusts1);
226  DeletePointers(&clusts2);
227  DeletePointers(&stats);
228  }
229 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
BaseFloat SumClusterableNormalizer(const std::vector< Clusterable *> &vec)
Returns the total normalizer (usually count) of the cluster (pointers may be NULL).
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
virtual void Add(const Clusterable &other_in)
Add other stats.
float BaseFloat
Definition: kaldi-types.h:29
void AddToClusters(const std::vector< Clusterable *> &stats, const std::vector< int32 > &assignments, std::vector< Clusterable *> *clusters)
Given stats and a vector "assignments" of the same size (that maps to cluster indices), sums the stats up into "clusters." It will add to any stats already present in "clusters" (although typically "clusters" will be empty when called), and it will extend with NULL pointers for any unseen indices.
void AddToClustersOptimized(const std::vector< Clusterable *> &stats, const std::vector< int32 > &assignments, const Clusterable &total, std::vector< Clusterable *> *clusters)
AddToClustersOptimized does the same as AddToClusters (it sums up the stats within each cluster...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Clusterable * SumClusterable(const std::vector< Clusterable *> &vec)
Sums stats (ptrs may be NULL). Returns NULL if no non-NULL stats present.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestBuildTree()

void kaldi::TestBuildTree ( )

Definition at line 90 of file build-tree-test.cc.

References BuildTree(), DeleteBuildTreeStats(), GenRandStats(), Questions::GetKeysWithQuestions(), Questions::GetQuestionsOf(), Questions::HasQuestionsForKey(), rnnlm::i, QuestionsForKey::initial_questions, Questions::InitRand(), rnnlm::j, KALDI_ASSERT, KALDI_VLOG, kAllKeysUnion, EventMap::Map(), Rand(), RandUniform(), EventMap::Write(), WriteBasicType(), WriteBuildTreeStats(), and WriteIntegerVector().

Referenced by main().

90  {
91  for (int32 p = 0; p < 3; p++) {
92  // First decide phone-ids, hmm lengths, is-ctx-dep...
93 
94  int32 dim = 1 + Rand() % 40;
95  int32 num_phones = 1 + Rand() % 8;
96  int32 num_stats = 1 + (Rand() % 15) * (Rand() % 15); // up to 14^2 + 1 separate stats.
97  int32 N = 2 + Rand() % 2; // 2 or 3.
98  int32 P = Rand() % N;
99  float ctx_dep_prob = 0.5 + 0.5*RandUniform();
100 
101  std::vector<int32> phone_ids(num_phones);
102  for (size_t i = 0;i < (size_t)num_phones;i++)
103  phone_ids[i] = (i == 0 ? (Rand() % 2) : phone_ids[i-1] + 1 + (Rand()%2));
104  int32 max_phone = *std::max_element(phone_ids.begin(), phone_ids.end());
105  std::vector<int32> hmm_lengths(max_phone+1);
106  std::vector<bool> is_ctx_dep(max_phone+1);
107 
108  for (int32 i = 0; i <= max_phone; i++) {
109  hmm_lengths[i] = 1 + Rand() % 3;
110  is_ctx_dep[i] = (RandUniform() < ctx_dep_prob); // true w.p. ctx_dep_prob.
111  }
112  for (size_t i = 0;i < (size_t) num_phones;i++) {
113  KALDI_VLOG(2) << "For idx = "<< i << ", (phone_id, hmm_length, is_ctx_dep) == " << (phone_ids[i]) << " " << (hmm_lengths[phone_ids[i]]) << " " << (is_ctx_dep[phone_ids[i]]);
114  }
115  // Generate rand stats. These were tested in TestGenRandStats() above.
116  BuildTreeStatsType stats;
117  bool ensure_all_covered = false;
118  GenRandStats(dim, num_stats, N, P, phone_ids, hmm_lengths, is_ctx_dep, ensure_all_covered, &stats);
119 
120  { // print out the stats.
121  std::cout << "Writing random stats.";
122  std::cout << "dim = " << dim << '\n';
123  std::cout << "num_phones = " << num_phones << '\n';
124  std::cout << "num_stats = " << num_stats << '\n';
125  std::cout << "N = "<< N << '\n';
126  std::cout << "P = "<< P << '\n';
127  std::cout << "is-ctx-dep = ";
128  for (size_t i = 0;i < is_ctx_dep.size();i++)
129  WriteBasicType(std::cout, false, static_cast<bool>(is_ctx_dep[i]));
130  std::cout << "hmm_lengths = "; WriteIntegerVector(std::cout, false, hmm_lengths);
131  std::cout << "phone_ids = "; WriteIntegerVector(std::cout, false, phone_ids);
132  std::cout << "Stats are: \n";
133  WriteBuildTreeStats(std::cout, false, stats);
134  }
135 
136  // Now build the tree.
137 
138  Questions qopts;
139  int32 num_quest = Rand() % 10, num_iters = rand () % 5;
140  qopts.InitRand(stats, num_quest, num_iters, kAllKeysUnion); // This was tested in build-tree-utils-test.cc
141 
142  {
143  std::cout << "Printing questions:\n";
144  std::vector<EventKeyType> keys;
145  qopts.GetKeysWithQuestions(&keys);
146  for (size_t i = 0;i < keys.size();i++) {
147  KALDI_ASSERT(qopts.HasQuestionsForKey(keys[i]));
148  const QuestionsForKey &opts = qopts.GetQuestionsOf(keys[i]);
149  std::cout << "num-quest: "<< opts.initial_questions.size() << '\n';
150  for (size_t j = 0;j < opts.initial_questions.size();j++) {
151  for (size_t k = 0;k < opts.initial_questions[j].size();k++)
152  std::cout << opts.initial_questions[j][k] <<" ";
153  std::cout << '\n';
154  }
155  }
156  }
157 
158  float thresh = 100.0 * RandUniform();
159  int max_leaves = 100;
160  std::cout <<"Thresh = "<<thresh<<" for building tree.\n";
161 
162  {
163  std::cout << "Building tree\n";
164  EventMap *tree = NULL;
165  std::vector<std::vector<int32> > phone_sets(phone_ids.size());
166  for (size_t i = 0; i < phone_ids.size(); i++)
167  phone_sets[i].push_back(phone_ids[i]);
168  std::vector<bool> share_roots(phone_sets.size(), true),
169  do_split(phone_sets.size(), true);
170 
171  if (p % 3 != 0) {
172  bool round_num_leaves = true;
173 
174  EventMap *tree_not_rounded =
175  BuildTree(qopts, phone_sets, hmm_lengths, share_roots,
176  do_split, stats, thresh, max_leaves, 0.0, P,
177  false);
178 
179  tree = BuildTree(qopts, phone_sets, hmm_lengths, share_roots,
180  do_split, stats, thresh, max_leaves, 0.0, P,
181  round_num_leaves);
182 
183  BuildTreeStatsType::const_iterator iter, end = stats.end();
184 
185  std::map<EventAnswerType, std::set<EventAnswerType> > mapping;
186  int32 num_removed = 0;
187  for (iter = stats.begin(); iter != end; ++iter) {
188  const EventType &evec = iter->first;
189  EventAnswerType ans_not_rounded;
190  KALDI_ASSERT(tree_not_rounded->Map(evec, &ans_not_rounded));
191 
192  EventAnswerType ans;
193  KALDI_ASSERT(tree->Map(evec, &ans));
194 
195  auto it = mapping.find(ans);
196  if (it == mapping.end()) {
197  std::set<EventAnswerType> leaf_set;
198  leaf_set.insert(ans_not_rounded);
199  mapping.insert(it, std::make_pair(ans, leaf_set));
200  } else if (it->second.count(ans_not_rounded) == 0) {
201  num_removed++;
202  it->second.insert(ans_not_rounded);
203  }
204  }
205 
206  std::cout << "Leaf rounding map:\n";
207  for (auto it = mapping.begin(); it != mapping.end(); ++it) {
208  WriteBasicType(std::cout, false, it->first);
209  for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) {
210  WriteBasicType(std::cout, false, *it2);
211  }
212  std::cout << std::endl;
213  }
214 
215  KALDI_ASSERT(num_removed < 8);
216  } else {
217  tree = BuildTree(qopts, phone_sets, hmm_lengths, share_roots,
218  do_split, stats, thresh, max_leaves, 0.0, P,
219  false);
220  }
221 
222  // Would have print-out & testing code here.
223  std::cout << "Tree [default build] is:\n";
224  tree->Write(std::cout, false);
225  delete tree;
226  }
227  DeleteBuildTreeStats(&stats);
228  }
229 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
void GenRandStats(int32 dim, int32 num_stats, int32 N, int32 P, const std::vector< int32 > &phone_ids, const std::vector< int32 > &phone2hmm_length, const std::vector< bool > &is_ctx_dep, bool ensure_all_phones_covered, BuildTreeStatsType *stats_out)
GenRandStats generates random statistics of the form used by BuildTree.
Definition: build-tree.cc:30
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
EventMap * BuildTree(Questions &qopts, const std::vector< std::vector< int32 > > &phone_sets, const std::vector< int32 > &phone2num_pdf_classes, const std::vector< bool > &share_roots, const std::vector< bool > &do_split, const BuildTreeStatsType &stats, BaseFloat thresh, int32 max_leaves, BaseFloat cluster_thresh, int32 P, bool round_num_leaves)
BuildTree is the normal way to build a set of decision trees.
Definition: build-tree.cc:136
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
void WriteIntegerVector(std::ostream &os, bool binary, const std::vector< T > &v)
Function for writing STL vectors of integer types.
Definition: io-funcs-inl.h:198
void WriteBasicType(std::ostream &os, bool binary, T t)
WriteBasicType is the name of the write function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:34
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
void WriteBuildTreeStats(std::ostream &os, bool binary, const BuildTreeStatsType &stats)
Writes BuildTreeStats object. This works even if pointers are NULL.

◆ TestBuildTreeStatsIo()

void kaldi::TestBuildTreeStatsIo ( bool  binary)

Definition at line 838 of file build-tree-utils-test.cc.

References rnnlm::i, KALDI_ASSERT, Rand(), ReadBuildTreeStats(), Input::Stream(), and WriteBuildTreeStats().

Referenced by main().

838  {
839  for (int32 p = 0; p < 10; p++) {
840  size_t num_stats = Rand() % 20;
841  BuildTreeStatsType stats;
842  for (size_t i = 0; i < num_stats; i++) {
843  EventType ev;
844  int32 ev_sz = Rand() % 5;
845  for (int32 i = 0; i < ev_sz; i++) {
846  EventKeyType key = (i == 0 ? 0 : ev[i-1].first) + Rand() % 2, value = Rand() % 10;
847  ev.push_back(std::make_pair(key, value));
848  }
849  stats.push_back(std::make_pair(ev, (Clusterable*) NULL));
850  }
851  const char *filename = "tmpf";
852  WriteBuildTreeStats(Output(filename, binary).Stream(), binary, stats);
853 
854  {
855  bool binary_in;
856  BuildTreeStatsType stats2;
857  GaussClusterable gc; // just need some random Clusterable object
858  Input ki(filename, &binary_in);
859  ReadBuildTreeStats(ki.Stream(),
860  binary_in, gc, &stats2);
861  KALDI_ASSERT(stats == stats2);
862  }
863  }
864 
865  unlink("tmpf");
866 }
kaldi::int32 int32
void ReadBuildTreeStats(std::istream &is, bool binary, const Clusterable &example, BuildTreeStatsType *stats)
Reads BuildTreeStats object.
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
GaussClusterable wraps Gaussian statistics in a form accessible to generic clustering algorithms...
void WriteBuildTreeStats(std::ostream &os, bool binary, const BuildTreeStatsType &stats)
Writes BuildTreeStats object. This works even if pointers are NULL.

◆ TestClusterBottomUp()

static void kaldi::TestClusterBottomUp ( )
static

Definition at line 232 of file cluster-utils-test.cc.

References ClusterBottomUp(), DeletePointers(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, Rand(), RandUniform(), and swap().

Referenced by main().

232  {
233  for (size_t i = 0;i < 10;i++) {
234  size_t n_clust = Rand() % 10;
235  std::vector<Clusterable*> points;
236  for (size_t j = 0;j < n_clust;j++) {
237  size_t n_points = 1 + Rand() % 5;
238  BaseFloat clust_center = (BaseFloat)j;
239  for (size_t k = 0;k < n_points;k++) points.push_back(new ScalarClusterable(clust_center + RandUniform()*0.01));
240  }
241 
242  BaseFloat max_merge_thresh = 0.1;
243  size_t min_clust = Rand() % 10; // use max_merge_thresh to control #clust.
244  std::vector<Clusterable*> clusters;
245  std::vector<int32> assignments;
246 
247  for (size_t i = 0;i < points.size();i++) {
248  size_t j = Rand() % points.size();
249  if (i != j) std::swap(points[i], points[j]); // randomize order.
250  }
251 
252 
253  float ans = ClusterBottomUp(points, max_merge_thresh, min_clust, &clusters, &assignments);
254 
255  KALDI_ASSERT(ans < 0.000001); // objf change should be negative.
256  KALDI_LOG << "Objf change from bottom-up clustering is "<<ans<<'\n';
257 
258  ClusterBottomUp(points, max_merge_thresh, min_clust, NULL, NULL); // make sure no crash.
259 
260  if (0) { // for debug if it breaks.
261  for (size_t i = 0;i < points.size();i++) {
262  KALDI_LOG << "point " << i << ": " << ((ScalarClusterable*)points[i])->Info() << " -> " << assignments[i];
263  }
264  for (size_t i = 0;i < clusters.size();i++) {
265  KALDI_LOG << "clust " << i << ": " << ((ScalarClusterable*)clusters[i])->Info();
266  }
267  }
268 
269  KALDI_ASSERT(clusters.size() == std::max(n_clust, std::min(points.size(), min_clust)));
270 
271  for (size_t i = 0;i < points.size();i++) {
272  size_t j = Rand() % points.size();
273  BaseFloat xi = ((ScalarClusterable*)points[i])->Mean(),
274  xj = ((ScalarClusterable*)points[j])->Mean();
275  if (fabs(xi-xj) < 0.011) {
276  if (clusters.size() == n_clust) KALDI_ASSERT(assignments[i] == assignments[j]);
277  } else KALDI_ASSERT(assignments[i] != assignments[j]);
278  }
279  DeletePointers(&clusters);
280  DeletePointers(&points);
281  }
282 
283 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
float BaseFloat
Definition: kaldi-types.h:29
BaseFloat ClusterBottomUp(const std::vector< Clusterable *> &points, BaseFloat max_merge_thresh, int32 min_clust, std::vector< Clusterable *> *clusters_out, std::vector< int32 > *assignments_out)
A bottom-up clustering algorithm.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
ScalarClusterable clusters scalars with x^2 loss.

◆ TestClusterEventMap()

void kaldi::TestClusterEventMap ( )

Definition at line 376 of file build-tree-utils-test.cc.

References ClusterEventMap(), DeleteBuildTreeStats(), DoTableSplit(), rnnlm::i, rnnlm::j, KALDI_ASSERT, EventMap::Map(), rnnlm::n, Rand(), RandUniform(), and TrivialTree().

Referenced by main().

376  {
377  // This second testing routine checks that ClusterEventMap does not renumber leaves whose stats
378  // we exclude.
379  // ClusterEventMapGetMapping (the internal version) were tested in another
380  // testing routine.
381 
382  EventKeyType key = 0; // just one key.
383  for (size_t iter = 0;iter < 1;iter++) { // in loop anyway.
384  BuildTreeStatsType stats;
385  EventValueType cur_value = 0;
386  int32 num_clust = 10;
387  for (int32 i = 0;i < num_clust;i++) { // this will correspond to the "cluster".
388  size_t n = 1 + Rand() % 3;
389  for (size_t j = 0;j < n;j++) {
390  BaseFloat scalar = static_cast<BaseFloat>(i) + RandUniform()*0.001;
391  EventType evec;
392  evec.push_back(std::make_pair(key, cur_value++));
393  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(new ScalarClusterable(scalar))));
394  }
395  }
396 
397  int32 nleaves = 0;
398  EventMap *trivial_map = TrivialTree(&nleaves);
399 
400  EventMap *table_map = DoTableSplit(*trivial_map, key, stats, &nleaves);
401  KALDI_ASSERT(nleaves == cur_value);
402 
403  std::set<EventValueType> exclude_leaves;
404  for (size_t i = 0;i < 4;i++) exclude_leaves.insert(Rand() % num_clust);
405  BuildTreeStatsType stats_excluded;
406  BuildTreeStatsType stats_included;
407  for (size_t i = 0;i < stats.size();i++) {
408  if (exclude_leaves.count(stats[i].first[0].second) != 0) { // this code relies on the fact that there is just one event in the EventVector.
409  stats_excluded.push_back(stats[i]);
410  } else {
411  stats_included.push_back(stats[i]);
412  }
413  }
414  KALDI_ASSERT(!stats_excluded.empty()&&!stats_included.empty() && stats_excluded.size()+stats_included.size() == stats.size());
415 
416  int32 num_reduced;
417  EventMap *clustered_map = ClusterEventMap(*table_map, stats_included, 0.1, &num_reduced);
418 
419  std::cout << "TestCluster*(): num_reduced = "<<num_reduced<<", expected [without exclusion]: "<<cur_value<<" - "<<num_clust<<" = "<<(cur_value-num_clust)<<'\n';
420 
421  // Make sure stats we excluded are not renumbered.
422  for (size_t i = 0;i < stats_excluded.size();i++) {
423  const EventType &evec = stats_excluded[i].first;
424  EventAnswerType ans; table_map->Map(evec, &ans);
425  EventAnswerType ans2; clustered_map->Map(evec, &ans2);
426  KALDI_ASSERT(ans == ans2);
427  }
428 
429  delete clustered_map;
430  delete table_map;
431  delete trivial_map;
432  DeleteBuildTreeStats(&stats);
433  }
434 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
virtual bool Map(const EventType &event, EventAnswerType *ans) const =0
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
EventMap * ClusterEventMap(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, int32 *num_removed_ptr)
This is as ClusterEventMapGetMapping but a more convenient interface that exposes less of the interna...
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.
EventMap * DoTableSplit(const EventMap &orig, EventKeyType key, const BuildTreeStatsType &stats, int32 *num_leaves)
DoTableSplit does a complete split on this key (e.g.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestClusterEventMapGetMappingAndRenumberEventMap()

void kaldi::TestClusterEventMapGetMappingAndRenumberEventMap ( )

Definition at line 256 of file build-tree-utils-test.cc.

References ClusterEventMapGetMapping(), EventMap::Copy(), DeleteBuildTreeStats(), DeletePointers(), DoTableSplit(), rnnlm::i, rnnlm::j, KALDI_ASSERT, EventMap::MaxResult(), EventMap::MultiMap(), rnnlm::n, Rand(), RandUniform(), RenumberEventMap(), SortAndUniq(), and TrivialTree().

Referenced by main().

256  {
257  EventKeyType key = 0; // just one key.
258  for (size_t iter = 0;iter < 1;iter++) { // in loop anyway.
259  BuildTreeStatsType stats;
260  EventValueType cur_value = 0;
261  int32 num_clust = 10;
262  for (int32 i = 0;i < num_clust;i++) { // this will correspond to the "cluster".
263  size_t n = 1 + Rand() % 3;
264  for (size_t j = 0;j < n;j++) {
265  BaseFloat scalar = static_cast<BaseFloat>(i) + RandUniform()*0.001;
266  EventType evec;
267  evec.push_back(std::make_pair(key, cur_value++));
268  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(new ScalarClusterable(scalar))));
269  }
270  }
271 
272  int32 nleaves = 0;
273  EventMap *trivial_map = TrivialTree(&nleaves);
274 
275  EventMap *table_map = DoTableSplit(*trivial_map, key, stats, &nleaves);
276  KALDI_ASSERT(nleaves == cur_value);
277 
278  std::vector<EventMap*> mapping;
279  int32 num_reduced = ClusterEventMapGetMapping(*table_map, stats, 0.1, &mapping);
280 
281  std::cout << "TestCluster(): num_reduced = "<<num_reduced<<", expected: "<<cur_value<<" - "<<num_clust<<" = "<<(cur_value-num_clust)<<'\n';
282  KALDI_ASSERT(num_reduced == cur_value - num_clust);
283 
284  EventMap *clustered_map = table_map->Copy(mapping);
285 
286  EventAnswerType new_nleaves;
287  EventMap *renumbered_map = RenumberEventMap(*clustered_map, &new_nleaves);
288  KALDI_ASSERT(new_nleaves == num_clust);
289 
290  std::vector<EventAnswerType> orig_answers, clustered_answers, renumbered_answers;
291 
292  EventType empty_vec;
293  table_map->MultiMap(empty_vec, &orig_answers);
294  clustered_map->MultiMap(empty_vec, &clustered_answers);
295  renumbered_map->MultiMap(empty_vec, &renumbered_answers);
296 
297  SortAndUniq(&orig_answers);
298  SortAndUniq(&clustered_answers);
299  SortAndUniq(&renumbered_answers);
300  KALDI_ASSERT(orig_answers.size() == (size_t) cur_value);
301  KALDI_ASSERT(clustered_answers.size() == (size_t) num_clust);
302  KALDI_ASSERT(renumbered_answers.size() == (size_t) num_clust);
303  KALDI_ASSERT(renumbered_map->MaxResult()+1 == num_clust);
304 
305  DeletePointers(&mapping);
306  delete renumbered_map;
307  delete clustered_map;
308  delete table_map;
309  delete trivial_map;
310  DeleteBuildTreeStats(&stats);
311  }
312 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
virtual EventAnswerType MaxResult() const
Definition: event-map.h:142
kaldi::int32 int32
void SortAndUniq(std::vector< T > *vec)
Sorts and uniq&#39;s (removes duplicates) from a vector.
Definition: stl-utils.h:39
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
int ClusterEventMapGetMapping(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, std::vector< EventMap *> *mapping)
"ClusterEventMapGetMapping" clusters the leaves of the EventMap, with "thresh" a delta-likelihood thr...
EventMap * RenumberEventMap(const EventMap &e_in, int32 *num_leaves)
RenumberEventMap [intended to be used after calling ClusterEventMap] renumbers an EventMap so its lea...
virtual EventMap * Copy(const std::vector< EventMap *> &new_leaves) const =0
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
virtual void MultiMap(const EventType &event, std::vector< EventAnswerType > *ans) const =0
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.
EventMap * DoTableSplit(const EventMap &orig, EventKeyType key, const BuildTreeStatsType &stats, int32 *num_leaves)
DoTableSplit does a complete split on this key (e.g.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestClusterEventMapGetMappingAndRenumberEventMap2()

void kaldi::TestClusterEventMapGetMappingAndRenumberEventMap2 ( )

Definition at line 315 of file build-tree-utils-test.cc.

References ClusterEventMapGetMapping(), EventMap::Copy(), DeleteBuildTreeStats(), DeletePointers(), DoTableSplit(), rnnlm::i, rnnlm::j, KALDI_ASSERT, EventMap::MultiMap(), rnnlm::n, Rand(), RandUniform(), RenumberEventMap(), SortAndUniq(), and TrivialTree().

Referenced by main().

315  {
316  EventKeyType key = 0; // just one key.
317  for (size_t iter = 0;iter < 1;iter++) { // in loop anyway.
318  BuildTreeStatsType stats;
319  BuildTreeStatsType stats_reduced;
320  EventValueType cur_value = 0;
321  int32 num_clust = 10;
322  for (int32 i = 0;i < num_clust;i++) { // this will correspond to the "cluster".
323  size_t n = 1 + Rand() % 3;
324  for (size_t j = 0;j < n;j++) {
325  BaseFloat scalar = static_cast<BaseFloat>(i) + RandUniform()*0.001;
326  EventType evec;
327  evec.push_back(std::make_pair(key, cur_value++));
328  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(new ScalarClusterable(scalar))));
329  if (Rand() % 10 < 5) stats_reduced.push_back(stats.back());
330  }
331  }
332 
333  int32 nleaves = 0;
334  EventMap *trivial_map = TrivialTree(&nleaves);
335 
336  EventMap *table_map = DoTableSplit(*trivial_map, key, stats, &nleaves);
337  KALDI_ASSERT(nleaves == cur_value);
338 
339  std::vector<EventMap*> mapping;
340  int32 num_reduced = ClusterEventMapGetMapping(*table_map, stats_reduced, 0.1, &mapping);
341 
342  std::cout << "TestCluster(): num_reduced = "<<num_reduced<<", expected [ignoring gaps]: "<<cur_value<<" - "<<num_clust<<" = "<<(cur_value-num_clust)<<'\n';
343  // KALDI_ASSERT(num_reduced == cur_value - num_clust);
344 
345  EventMap *clustered_map = table_map->Copy(mapping);
346 
347  EventAnswerType new_nleaves;
348  EventMap *renumbered_map = RenumberEventMap(*clustered_map, &new_nleaves);
349  // KALDI_ASSERT(new_nleaves == num_clust);
350 
351  std::vector<EventAnswerType> orig_answers, clustered_answers, renumbered_answers;
352 
353  EventType empty_vec;
354  table_map->MultiMap(empty_vec, &orig_answers);
355  clustered_map->MultiMap(empty_vec, &clustered_answers);
356  renumbered_map->MultiMap(empty_vec, &renumbered_answers);
357 
358  SortAndUniq(&orig_answers);
359  SortAndUniq(&clustered_answers);
360  SortAndUniq(&renumbered_answers);
361  // KALDI_ASSERT(orig_answers.size() == (size_t) cur_value);
362  // KALDI_ASSERT(clustered_answers.size() == (size_t) num_clust);
363  // KALDI_ASSERT(renumbered_answers.size() == (size_t) num_clust);
364  // KALDI_ASSERT(renumbered_map->MaxResult()+1 == num_clust);
365 
366  DeletePointers(&mapping);
367  delete renumbered_map;
368  delete clustered_map;
369  delete table_map;
370  delete trivial_map;
371  DeleteBuildTreeStats(&stats);
372  }
373 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
void SortAndUniq(std::vector< T > *vec)
Sorts and uniq&#39;s (removes duplicates) from a vector.
Definition: stl-utils.h:39
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
int ClusterEventMapGetMapping(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, std::vector< EventMap *> *mapping)
"ClusterEventMapGetMapping" clusters the leaves of the EventMap, with "thresh" a delta-likelihood thr...
EventMap * RenumberEventMap(const EventMap &e_in, int32 *num_leaves)
RenumberEventMap [intended to be used after calling ClusterEventMap] renumbers an EventMap so its lea...
virtual EventMap * Copy(const std::vector< EventMap *> &new_leaves) const =0
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
virtual void MultiMap(const EventType &event, std::vector< EventAnswerType > *ans) const =0
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.
EventMap * DoTableSplit(const EventMap &orig, EventKeyType key, const BuildTreeStatsType &stats, int32 *num_leaves)
DoTableSplit does a complete split on this key (e.g.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestClusterEventMapRestricted()

void kaldi::TestClusterEventMapRestricted ( )

Definition at line 437 of file build-tree-utils-test.cc.

References ClusterEventMap(), ClusterEventMapRestrictedByKeys(), ClusterEventMapRestrictedByMap(), CopySetToVector(), DeleteBuildTreeStats(), DoTableSplitMultiple(), rnnlm::i, Questions::InitRand(), rnnlm::j, KALDI_ASSERT, kAllKeysInsistIdentical, Rand(), RandGauss(), RandUniform(), SplitDecisionTree(), and TrivialTree().

Referenced by main().

437  {
438 
439  // TestClusterEventMapRestricted() tests that ClusterEventMapRestricted()
440  // does not combine leaves that we were trying to keep separate.
441 
442  bool test_by_key = (Rand()%2 == 0);
443 
444  int32 num_keys = 1 + Rand() % 4;
445  std::vector<EventKeyType> keys;
446 
447  { // randomly choose keys. Will always define all of them.
448  std::set<EventKeyType> keys_set;
449  while (keys_set.size() < (size_t)num_keys)
450  keys_set.insert( (Rand() % (num_keys + 10)) - 3 );
451  CopySetToVector(keys_set, &keys);
452  }
453 
454 
455  BuildTreeStatsType stats;
456 
457  int32 n_stats = 1 + (Rand() % 10);
458  n_stats *= n_stats; // up to 81 stats.
459 
460  for (size_t i = 0; i < (size_t)n_stats; i++) {
461  EventType evec;
462 
463  for (size_t j = 0; j < keys.size(); j++) {
464  EventValueType val = Rand() % 100;
465  evec.push_back(std::make_pair(keys[j], val));
466  }
467  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(new ScalarClusterable(RandGauss()))));
468  }
469 
470  std::vector<EventKeyType> special_keys;
471  for (size_t i = 0; i < keys.size(); i++)
472  if (RandUniform() < 0.5) special_keys.push_back(keys[i]);
473 
474 
475  int32 nleaves = 0;
476  EventMap *trivial_map = TrivialTree(&nleaves);
477 
478 
479  // We do a complete split on these keys.
480  EventMap *table_split_map = DoTableSplitMultiple(*trivial_map, special_keys,
481  stats, &nleaves);
482  int32 nleaves_after_table_split = nleaves;
483  std::cout << "TestClusterEventMapRestricted: after splitting on "<<special_keys.size()<<" keys, nleaves = " <<nleaves<<'\n';
484  // We now do decision tree split.
485 
486  Questions qo; // all default.
487  int32 num_quest = Rand() % 10, num_iters = rand () % 5;
488  qo.InitRand(stats, num_quest, num_iters, kAllKeysInsistIdentical);
489  float thresh = 0.001;
490  int32 max_leaves = 50;
491  BaseFloat smallest_split = 0.0;
492  BaseFloat impr;
493  EventMap *split_tree = SplitDecisionTree(*table_split_map, stats, qo, thresh, max_leaves,
494  &nleaves, &impr, &smallest_split);
495  KALDI_ASSERT((nleaves <= max_leaves || nleaves == nleaves_after_table_split) && smallest_split >= thresh);
496 
497  std::cout << "TestClusterEventMapRestricted: after building decision tree, " <<nleaves<<'\n';
498 
499  thresh = 1000; // will ensure everything is combined.
500  {
501  int32 num_removed;
502  EventMap *map_clustered = ClusterEventMap(*split_tree, stats,
503  thresh, &num_removed);
504  std::cout << "ClusterEventMap: num_removed = "<<num_removed;
505  KALDI_ASSERT(num_removed == nleaves - 1);
506  delete map_clustered;
507  }
508 
509  {
510  int32 num_removed;
511 
512  EventMap *map_clustered = NULL;
513  if (test_by_key)
514  map_clustered = ClusterEventMapRestrictedByKeys(*split_tree, stats,
515  thresh, special_keys,
516  &num_removed);
517  else
518  map_clustered = ClusterEventMapRestrictedByMap(*split_tree, stats,
519  thresh, *table_split_map,
520  &num_removed);
521 
522  std::cout << "ClusterEventMapRestricted: num_removed = "<<num_removed;
523  // should take it back to status after table split.
524  KALDI_ASSERT(num_removed == nleaves - nleaves_after_table_split);
525  delete map_clustered;
526  }
527 
528  delete split_tree;
529  delete trivial_map;
530  delete table_split_map;
531  DeleteBuildTreeStats(&stats);
532 }
EventMap * DoTableSplitMultiple(const EventMap &orig, const std::vector< EventKeyType > &keys, const BuildTreeStatsType &stats, int32 *num_leaves)
DoTableSplitMultiple does a complete split on all the keys, in order from keys[0], keys[1] and so on.
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
This class defines, for each EventKeyType, a set of initial questions that it tries and also a number...
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
EventMap * SplitDecisionTree(const EventMap &input_map, const BuildTreeStatsType &stats, Questions &q_opts, BaseFloat thresh, int32 max_leaves, int32 *num_leaves, BaseFloat *obj_impr_out, BaseFloat *smallest_split_change_out)
Does a decision-tree split at the leaves of an EventMap.
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
void InitRand(const BuildTreeStatsType &stats, int32 num_quest, int32 num_iters_refine, AllKeysType all_keys_type)
InitRand attempts to generate "reasonable" random questions.
EventMap * ClusterEventMapRestrictedByKeys(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, const std::vector< EventKeyType > &keys, int32 *num_removed)
This is as ClusterEventMap, but first splits the stats on the keys specified in "keys" (e...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
EventMap * ClusterEventMap(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, int32 *num_removed_ptr)
This is as ClusterEventMapGetMapping but a more convenient interface that exposes less of the interna...
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
EventMap * ClusterEventMapRestrictedByMap(const EventMap &e_in, const BuildTreeStatsType &stats, BaseFloat thresh, const EventMap &e_restrict, int32 *num_removed_ptr)
This version of ClusterEventMapRestricted restricts the clustering to only allow things that "e_restr...
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestClusterKMeans()

static void kaldi::TestClusterKMeans ( )
static

Definition at line 329 of file cluster-utils-test.cc.

References ClusterKMeans(), DeletePointers(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, rnnlm::n, Rand(), RandUniform(), and SumClusterableObjf().

Referenced by main().

329  {
330  size_t n_points_tot = 0, n_wrong_tot = 0;
331  for (size_t n = 0;n < 3;n++) {
332  // Test it by creating a random clustering and verifying that it does not make it worse, and
333  // if done with the optimal parameters, makes it optimal.
334  size_t n_clust = Rand() % 10;
335  std::vector<Clusterable*> points;
336  std::vector<int32> assignments_ref;
337  for (size_t j = 0;j < n_clust;j++) {
338  size_t n_points = 1 + Rand() % 5;
339  BaseFloat clust_center = (BaseFloat)j;
340  for (size_t k = 0;k < n_points;k++) {
341  points.push_back(new ScalarClusterable(clust_center + RandUniform()*0.01));
342  assignments_ref.push_back(j);
343  }
344  }
345  std::vector<Clusterable*> clusters;
346  std::vector<int32> assignments;
348 
349  BaseFloat ans = ClusterKMeans(points, n_clust, &clusters, &assignments, kcfg);
350 
351  if (n < 3) ClusterKMeans(points, n_clust, NULL, NULL, kcfg); // make sure no crash.
352 
353  BaseFloat clust_objf = SumClusterableObjf(clusters);
354 
355  KALDI_LOG << "TestClusterKmeans: objf after clustering is: "<<clust_objf<<", impr is: "<<ans<<'\n';
356 
357  if (clusters.size() != n_clust) {
358  KALDI_LOG << "Warning: unexpected number of clusters "<<clusters.size()<<" vs. "<<n_clust<<"";
359  }
360  KALDI_ASSERT(assignments.size() == points.size());
361 
362  if (clust_objf < -1.0 * points.size()) { // a bit high...
363  KALDI_LOG << "Warning: ClusterKMeans did not work quite as well as expected";
364  }
365 
366  int32 num_wrong = 0;
367  for (size_t i = 0;i < points.size();i++) {
368  size_t j = Rand() % points.size();
369  if (assignments_ref[i] == assignments_ref[j]) {
370  if (assignments[i] != assignments[j]) num_wrong++;
371  } else
372  if (assignments[i] == assignments[j]) num_wrong++;
373  }
374  KALDI_LOG << "num_wrong = "<<num_wrong<<'\n';
375 
376  n_points_tot += points.size();
377  n_wrong_tot += num_wrong;
378 
379  DeletePointers(&clusters);
380  DeletePointers(&points);
381  }
382  if (n_wrong_tot*4 > n_points_tot) {
383  KALDI_LOG << "Got too many wrong in k-means test [may not be fatal, but check it out.";
384  KALDI_ASSERT(0);
385  }
386 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
BaseFloat ClusterKMeans(const std::vector< Clusterable *> &points, int32 num_clust, std::vector< Clusterable *> *clusters_out, std::vector< int32 > *assignments_out, ClusterKMeansOptions cfg)
ClusterKMeans is a K-means-like clustering algorithm.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
#define KALDI_LOG
Definition: kaldi-error.h:153
ScalarClusterable clusters scalars with x^2 loss.

◆ TestClusterKMeansVector()

static void kaldi::TestClusterKMeansVector ( )
static

Definition at line 388 of file cluster-utils-test.cc.

References VectorBase< Real >::AddVec(), ClusterKMeans(), DeletePointers(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, rnnlm::n, ClusterKMeansOptions::num_tries, Rand(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), and SumClusterableObjf().

Referenced by main().

388  {
389  size_t n_points_tot = 0, n_wrong_tot = 0;
390  for (size_t n = 0; n < 3; n++) {
391  std::vector<int32> assignments_ref;
392  int32 dim = 5 + Rand() % 5;
393  // Test it by creating a random clustering and verifying that it does not make it worse, and
394  // if done with the optimal parameters, makes it optimal.
395  size_t n_clust = Rand() % 10;
396  std::vector<Clusterable*> points;
397  for (size_t j = 0; j < n_clust; j++) {
398  size_t n_points = 1 + Rand() % 5;
399 
400  Vector<BaseFloat> clust_center(dim);
401  clust_center.SetRandn();
402  for (size_t k = 0; k < n_points; k++) {
403  Vector<BaseFloat> point(dim);
404  point.SetRandn();
405  point.Scale(0.01);
406  point.AddVec(1.0, clust_center);
407  BaseFloat weight = 0.5 + 0.432 * (Rand() % 5);
408  points.push_back(new VectorClusterable(point, weight));
409  assignments_ref.push_back(j);
410  }
411  }
412  std::vector<Clusterable*> clusters;
413  std::vector<int32> assignments;
415  kcfg.num_tries = 5;
416 
417  BaseFloat ans = ClusterKMeans(points, n_clust, &clusters, &assignments, kcfg);
418 
419  if (n < 3) ClusterKMeans(points, n_clust, NULL, NULL, kcfg); // make sure no crash.
420 
421  BaseFloat clust_objf = SumClusterableObjf(clusters);
422 
423  KALDI_LOG << "TestClusterKmeans: objf after clustering is: "<<clust_objf<<", impr is: "<<ans<<'\n';
424 
425  if (clusters.size() != n_clust) {
426  KALDI_LOG << "Warning: unexpected number of clusters "<<clusters.size()<<" vs. "<<n_clust<<"";
427  }
428  KALDI_ASSERT(assignments.size() == points.size());
429 
430  if (clust_objf < -1.0 * points.size()) { // a bit high...
431  KALDI_LOG << "Warning: ClusterKMeans did not work quite as well as expected";
432  }
433 
434 
435  int32 num_wrong = 0;
436  for (size_t i = 0;i < points.size();i++) {
437  size_t j = Rand() % points.size();
438  if (assignments_ref[i] == assignments_ref[j]) {
439  if (assignments[i] != assignments[j]) num_wrong++;
440  } else
441  if (assignments[i] == assignments[j]) num_wrong++;
442  }
443 
444  n_points_tot += points.size();
445  n_wrong_tot += num_wrong;
446 
447  KALDI_LOG << "num_wrong = " << num_wrong << ", num-points-tot = "
448  << n_points_tot;
449 
450  DeletePointers(&clusters);
451  DeletePointers(&points);
452  }
453  if (n_wrong_tot*4 > n_points_tot) {
454  KALDI_LOG << "Got too many wrong in k-means test [may not be fatal, but check it out.";
455  KALDI_ASSERT(0);
456  }
457 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
BaseFloat ClusterKMeans(const std::vector< Clusterable *> &points, int32 num_clust, std::vector< Clusterable *> *clusters_out, std::vector< int32 > *assignments_out, ClusterKMeansOptions cfg)
ClusterKMeans is a K-means-like clustering algorithm.
kaldi::int32 int32
VectorClusterable wraps vectors in a form accessible to generic clustering algorithms.
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TestClusterTopDown()

static void kaldi::TestClusterTopDown ( )
static

Definition at line 509 of file cluster-utils-test.cc.

References ClusterTopDown(), DeletePointers(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, rnnlm::n, Rand(), RandUniform(), SumClusterableObjf(), and TreeClusterOptions::thresh.

Referenced by main().

509  {
510  size_t n_points_tot = 0, n_wrong_tot = 0;
511  for (size_t n = 0;n < 10;n++) {
512 
513  size_t n_clust = Rand() % 10;
514  std::vector<Clusterable*> points;
515  for (size_t j = 0;j < n_clust;j++) {
516  size_t n_points = 1 + Rand() % 5;
517  BaseFloat clust_center = (BaseFloat)j;
518  for (size_t k = 0;k < n_points;k++) points.push_back(new ScalarClusterable(clust_center + RandUniform()*0.01));
519  }
520  std::vector<Clusterable*> clusters;
521  std::vector<int32> assignments;
522  TreeClusterOptions tcfg;
523  tcfg.thresh = 0.01; // should prevent us splitting things in same bucket.
524 
525 
526  BaseFloat ans = ClusterTopDown(points, n_clust, &clusters, &assignments, tcfg);
527 
528  if (n < 3) ClusterTopDown(points, n_clust, NULL, NULL, tcfg); // make sure doesn't crash.
529 
530  BaseFloat clust_objf = SumClusterableObjf(clusters);
531 
532  KALDI_LOG << "ClusterTopDown: objf after clustering is: "<<clust_objf<<", impr is: "<<ans<<'\n';
533 
534  if (n<=2) // avoid generating too much output.
535  KALDI_LOG << "Num nodes is "<<clusters.size()<<'\n';
536  for (size_t i = 0;i < clusters.size();i++) {
537  if (n<=2) { // avoid generating too much output.
538  KALDI_LOG << "Cluster "<<i<<": "<<((ScalarClusterable*)clusters[i])->Info()<<", objf is: "<<clusters[i]->Objf()<<"";
539  }
540  }
541  KALDI_ASSERT(clusters.size() == n_clust);
542  DeletePointers(&clusters);
543  DeletePointers(&points);
544  }
545  if (n_wrong_tot*4 > n_points_tot) {
546  KALDI_LOG << "Got too many wrong in k-means test [may not be fatal, but check it out.";
547  KALDI_ASSERT(0);
548  }
549 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
BaseFloat ClusterTopDown(const std::vector< Clusterable *> &points, int32 max_clust, std::vector< Clusterable *> *clusters_out, std::vector< int32 > *assignments_out, TreeClusterOptions cfg)
A clustering algorithm that internally uses TreeCluster, but does not give you the information about ...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
#define KALDI_LOG
Definition: kaldi-error.h:153
ScalarClusterable clusters scalars with x^2 loss.

◆ TestClusterUtils()

static void kaldi::TestClusterUtils ( )
static

Definition at line 25 of file cluster-utils-test.cc.

References Clusterable::Add(), Clusterable::Copy(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, Clusterable::Normalizer(), Clusterable::Objf(), Rand(), and RandGauss().

Referenced by main().

25  { // just some very basic tests of the GaussClusterable class.
26  BaseFloat varFloor = 0.1;
27  size_t dim = 1 + Rand() % 10;
28  size_t nGauss = 1 + Rand() % 10;
29  std::vector< GaussClusterable * > v(nGauss);
30  for (size_t i = 0;i < nGauss;i++) {
31  v[i] = new GaussClusterable(dim, varFloor);
32  }
33  for (size_t i = 0;i < nGauss;i++) {
34  size_t nPoints = 1 + Rand() % 30;
35  for (size_t j = 0;j < nPoints;j++) {
36  BaseFloat post = 0.5 *(Rand()%3);
37  Vector<BaseFloat> vec(dim);
38  for (size_t k = 0;k < dim;k++) vec(k) = RandGauss();
39  v[i]->AddStats(vec, post);
40  }
41  }
42  for (size_t i = 0;i+1 < nGauss;i++) {
43  BaseFloat like_before = (v[i]->Objf() + v[i+1]->Objf()) / (v[i]->Normalizer() + v[i+1]->Normalizer());
44  Clusterable *tmp = v[i]->Copy();
45  tmp->Add( *(v[i+1]));
46  BaseFloat like_after = tmp->Objf() / tmp->Normalizer();
47  KALDI_LOG << "Like_before = " << like_before <<", after = "<<like_after <<" over "<<tmp->Normalizer()<<" frames.";
48  if (tmp->Normalizer() > 0.1)
49  KALDI_ASSERT(like_after <= like_before); // should get worse after combining stats.
50  delete tmp;
51  }
52  for (size_t i = 0;i < nGauss;i++)
53  delete v[i];
54 }
virtual void Add(const Clusterable &other)=0
Add other stats.
virtual BaseFloat Objf() const =0
Return the objective function associated with the stats [assuming ML estimation]. ...
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
virtual Clusterable * Copy() const =0
Return a copy of this object.
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
virtual BaseFloat Normalizer() const =0
Return the normalizer (typically, count) associated with the stats.
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
GaussClusterable wraps Gaussian statistics in a form accessible to generic clustering algorithms...
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TestClusterUtilsVector()

static void kaldi::TestClusterUtilsVector ( )
static

Definition at line 56 of file cluster-utils-test.cc.

References Clusterable::Add(), VectorClusterable::Add(), Clusterable::Copy(), kaldi::cu::Copy(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, Clusterable::Normalizer(), Clusterable::Objf(), VectorClusterable::Objf(), Rand(), RandUniform(), and VectorBase< Real >::SetRandn().

Referenced by main().

56  { // just some very basic tests of the VectorClusterable class.
57  size_t dim = 2 + Rand() % 10;
58  size_t num_vectors = 1 + Rand() % 10;
59  std::vector<VectorClusterable*> v(num_vectors);
60  for (size_t i = 0;i < num_vectors;i++) {
61  BaseFloat weight = RandUniform();
62  Vector<BaseFloat> vec(dim);
63  vec.SetRandn();
64  v[i] = new VectorClusterable(vec, weight);
65 
66  {
67  VectorClusterable *tmp = static_cast<VectorClusterable*>(v[i]->Copy()),
68  *tmp2 = static_cast<VectorClusterable*>(v[i]->Copy());
69  tmp->Add(*tmp2);
70  KALDI_ASSERT(fabs(tmp->Objf()) < 0.001);
71  if (i > 0) {
72  tmp->Add(*(v[i-1]));
73  KALDI_ASSERT(tmp->Objf() < 0.0);
74  }
75  delete tmp;
76  delete tmp2;
77  }
78  }
79 
80  for (size_t i = 0; i+1 < num_vectors; i++) {
81  BaseFloat like_before = (v[i]->Objf() + v[i+1]->Objf()) / (v[i]->Normalizer() + v[i+1]->Normalizer());
82  Clusterable *tmp = v[i]->Copy();
83  tmp->Add( *(v[i+1]));
84  BaseFloat like_after = tmp->Objf() / tmp->Normalizer();
85  KALDI_LOG << "Like_before = " << like_before <<", after = "<<like_after <<" over "<<tmp->Normalizer()<<" frames.";
86  if (tmp->Normalizer() > 0.1)
87  KALDI_ASSERT(like_after <= like_before); // should get worse after combining stats.
88  delete tmp;
89  }
90  for (size_t i = 0;i < num_vectors;i++)
91  delete v[i];
92 }
virtual void Add(const Clusterable &other)=0
Add other stats.
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
virtual BaseFloat Objf() const =0
Return the objective function associated with the stats [assuming ML estimation]. ...
VectorClusterable wraps vectors in a form accessible to generic clustering algorithms.
virtual void Add(const Clusterable &other_in)
Add other stats.
float BaseFloat
Definition: kaldi-types.h:29
virtual Clusterable * Copy() const
Return a copy of this object.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
virtual BaseFloat Normalizer() const =0
Return the normalizer (typically, count) associated with the stats.
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
virtual BaseFloat Objf() const
Return the objective function associated with the stats [assuming ML estimation]. ...
#define KALDI_LOG
Definition: kaldi-error.h:153
void Copy(const CuMatrixBase< Real > &src, const CuArray< int32 > &copy_from_indices, CuMatrixBase< Real > *tgt)
Copies elements from src into tgt as given by copy_from_indices.
Definition: cu-math.cc:173

◆ TestCompactLatticeTable()

void kaldi::TestCompactLatticeTable ( bool  binary)

Definition at line 41 of file kaldi-lattice-test.cc.

References TableWriter< Holder >::Close(), rnnlm::i, KALDI_ASSERT, RandCompactLattice(), RandomAccessTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

41  {
42  CompactLatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
43  int N = 10;
44  std::vector<CompactLattice*> lat_vec(N);
45  for (int i = 0; i < N; i++) {
46  char buf[2];
47  buf[0] = '0' + i;
48  buf[1] = '\0';
49  std::string key = "key" + std::string(buf);
51  lat_vec[i] = fst;
52  writer.Write(key, *fst);
53  }
54  writer.Close();
55 
56  RandomAccessCompactLatticeReader reader("ark:tmpf");
57  for (int i = 0; i < N; i++) {
58  char buf[2];
59  buf[0] = '0' + i;
60  buf[1] = '\0';
61  std::string key = "key" + std::string(buf);
62  const CompactLattice &fst = reader.Value(key);
63  KALDI_ASSERT(fst::Equal(fst, *(lat_vec[i])));
64  delete lat_vec[i];
65  }
66 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
CompactLattice * RandCompactLattice()
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestCompactLatticeTableCross()

void kaldi::TestCompactLatticeTableCross ( bool  binary)

Definition at line 69 of file kaldi-lattice-test.cc.

References TableWriter< Holder >::Close(), fst::ConvertLattice(), rnnlm::i, KALDI_ASSERT, RandCompactLattice(), RandomAccessTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

69  {
70  CompactLatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
71  int N = 10;
72  std::vector<CompactLattice*> lat_vec(N);
73  for (int i = 0; i < N; i++) {
74  char buf[2];
75  buf[0] = '0' + i;
76  buf[1] = '\0';
77  std::string key = "key" + std::string(buf);
79  lat_vec[i] = fst;
80  writer.Write(key, *fst);
81  }
82  writer.Close();
83 
84  RandomAccessLatticeReader reader("ark:tmpf");
85  for (int i = 0; i < N; i++) {
86  char buf[2];
87  buf[0] = '0' + i;
88  buf[1] = '\0';
89  std::string key = "key" + std::string(buf);
90  const Lattice &fst = reader.Value(key);
91  CompactLattice fst2;
92  ConvertLattice(fst, &fst2);
93  KALDI_ASSERT(fst::Equal(fst2, *(lat_vec[i])));
94  delete lat_vec[i];
95  }
96 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
CompactLattice * RandCompactLattice()
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestContainsNullPointers()

void kaldi::TestContainsNullPointers ( )

Definition at line 190 of file stl-utils-test.cc.

References ContainsNullPointers(), rnnlm::i, KALDI_ASSERT, and Rand().

Referenced by main().

190  {
191  for (int p = 0; p < 100; p++) {
192  std::vector<char*> vec;
193  int sz = Rand() % 3;
194  bool is_null = false;
195  for (int i = 0;i < sz;i++) {
196  vec.push_back(reinterpret_cast<char*>(static_cast<intptr_t>(Rand() % 2)));
197  if (vec.back() == NULL)
198  is_null = true;
199  }
200  KALDI_ASSERT(is_null == ContainsNullPointers(vec));
201  }
202 }
bool ContainsNullPointers(const std::vector< A *> &v)
Returns true if the vector of pointers contains NULL pointers.
Definition: stl-utils.h:197
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestContextDep()

void kaldi::TestContextDep ( )

Definition at line 25 of file context-dep-test.cc.

References Clusterable::Add(), Clusterable::Copy(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Clusterable::Normalizer(), Clusterable::Objf(), Rand(), and RandGauss().

Referenced by main().

25  {
26  BaseFloat varFloor = 0.1;
27  size_t dim = 1 + Rand() % 20;
28  size_t nGauss = 1 + Rand() % 10;
29  std::vector< GaussClusterable * > v(nGauss);
30  for (size_t i = 0;i < nGauss;i++) {
31  v[i] = new GaussClusterable(dim, varFloor);
32  }
33  for (size_t i = 0;i < nGauss;i++) {
34  size_t nPoints = 1 + Rand() % 30;
35  for (size_t j = 0;j < nPoints;j++) {
36  BaseFloat post = 0.5 *(Rand()%3);
37  Vector<BaseFloat> vec(dim);
38  for (size_t k = 0;k < dim;k++) vec(k) = RandGauss();
39  v[i]->AddStats(vec, post);
40  }
41  }
42  for (size_t i = 0;i+1 < nGauss;i++) {
43  BaseFloat like_before = (v[i]->Objf() + v[i+1]->Objf()) / (v[i]->Normalizer() + v[i+1]->Normalizer());
44  Clusterable *tmp = v[i]->Copy();
45  tmp->Add(*(v[i+1]));
46  BaseFloat like_after = tmp->Objf() / tmp->Normalizer();
47  std::cout << "Like_before = " << like_before <<", after = "<<like_after <<" over "<<tmp->Normalizer()<<" frames.\n";
48  if (tmp->Normalizer() > 0.1)
49  KALDI_ASSERT(like_after <= like_before); // should get worse after combining stats.
50  delete tmp;
51  }
52  for (size_t i = 0;i < nGauss;i++)
53  delete v[i];
54 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestConvertAlignment()

void kaldi::TestConvertAlignment ( )

Definition at line 232 of file hmm-utils-test.cc.

References ConvertAlignment(), ContextDependencyInterface::Copy(), GenerateRandomAlignment(), GenRandContextDependencyLarge(), GenRandTopology(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, KALDI_WARN, MonophoneContextDependency(), RandInt(), SplitToPhones(), and TransitionModel::TransitionIdToPhone().

Referenced by main().

232  {
233  bool old_reorder = (RandInt(0, 1) == 1),
234  new_reorder = (RandInt(0, 1) == 1),
235  new_tree = (RandInt(0, 1) == 1),
236  new_topology = (RandInt(0, 1) == 1);
237  if (!new_tree)
238  new_topology = true;
239 
240  int32 subsample_factor = RandInt(1, 3);
241 
242  KALDI_LOG << " old-reorder = " << old_reorder
243  << ", new-reorder = " << new_reorder
244  << ", new-tree = " << new_tree
245  << ", subsample-factor = " << subsample_factor;
246 
247  std::vector<int32> phones;
248  phones.push_back(1);
249  for (int32 i = 2; i < 20; i++)
250  if (rand() % 2 == 0)
251  phones.push_back(i);
252  int32 N = 2 + rand() % 2, // context-size N is 2 or 3.
253  P = rand() % N; // Central-phone is random on [0, N)
254 
255  std::vector<int32> num_pdf_classes_old,
256  num_pdf_classes_new;
257 
258  ContextDependencyInterface *ctx_dep_old =
259  GenRandContextDependencyLarge(phones, N, P,
260  true, &num_pdf_classes_old),
261  *ctx_dep_new;
262  if (new_tree) {
263  if (new_topology) {
264  ctx_dep_new = GenRandContextDependencyLarge(phones, N, P,
265  true, &num_pdf_classes_new);
266  } else {
267  num_pdf_classes_new = num_pdf_classes_old;
268  ctx_dep_new = MonophoneContextDependency(phones, num_pdf_classes_new);
269  }
270  } else {
271  num_pdf_classes_new = num_pdf_classes_old;
272  ctx_dep_new = ctx_dep_old->Copy();
273  }
274 
275 
276  HmmTopology topo_old = GenRandTopology(phones, num_pdf_classes_old),
277  topo_new = (new_topology ?
278  GenRandTopology(phones, num_pdf_classes_new) : topo_old);
279 
280  TransitionModel trans_model_old(*ctx_dep_old, topo_old),
281  trans_model_new(*ctx_dep_new, topo_new);
282 
283  std::vector<int32> phone_sequence;
284  int32 phone_sequence_length = RandInt(0, 20);
285  for (int32 i = 0; i < phone_sequence_length; i++)
286  phone_sequence.push_back(phones[RandInt(0, phones.size() - 1)]);
287  std::vector<int32> old_alignment;
288  GenerateRandomAlignment(*ctx_dep_old, trans_model_old,
289  old_reorder, phone_sequence,
290  &old_alignment);
291 
292  std::vector<int32> new_alignment;
293 
294  bool ans = ConvertAlignment(trans_model_old, trans_model_new, *ctx_dep_new,
295  old_alignment, subsample_factor, false,
296  new_reorder, NULL, &new_alignment);
297  if(!ans) {
298  KALDI_WARN << "Alignment conversion failed";
299  // make sure it failed for a good reason.
300  KALDI_ASSERT(new_topology || subsample_factor > 1);
301  } else {
302  std::vector<std::vector<int32> > old_split, new_split;
303  bool b1 = SplitToPhones(trans_model_old, old_alignment, &old_split),
304  b2 = SplitToPhones(trans_model_new, new_alignment, &new_split);
305  KALDI_ASSERT(b1 && b2);
306  KALDI_ASSERT(old_split.size() == new_split.size());
307  for (size_t i = 0; i < new_split.size(); i++)
308  KALDI_ASSERT(trans_model_old.TransitionIdToPhone(old_split[i].front()) ==
309  trans_model_new.TransitionIdToPhone(new_split[i].front()));
310  if (!new_topology && subsample_factor == 1) {
311  // we should be able to convert back and it'll be the same.
312  std::vector<int32> old_alignment_copy;
313  bool ans = ConvertAlignment(trans_model_new, trans_model_old, *ctx_dep_old,
314  new_alignment, subsample_factor, false,
315  old_reorder, NULL, &old_alignment_copy);
316  KALDI_ASSERT(ans);
317  KALDI_ASSERT(old_alignment_copy == old_alignment);
318  }
319 
320  }
321  delete ctx_dep_old;
322  delete ctx_dep_new;
323 }
ContextDependency * GenRandContextDependencyLarge(const std::vector< int32 > &phone_ids, int N, int P, bool ensure_all_covered, std::vector< int32 > *hmm_lengths)
GenRandContextDependencyLarge is like GenRandContextDependency but generates a larger tree with speci...
Definition: context-dep.cc:97
ContextDependency * MonophoneContextDependency(const std::vector< int32 > &phones, const std::vector< int32 > &phone2num_pdf_classes)
Definition: context-dep.cc:331
kaldi::int32 int32
bool SplitToPhones(const TransitionModel &trans_model, const std::vector< int32 > &alignment, std::vector< std::vector< int32 > > *split_alignment)
SplitToPhones splits up the TransitionIds in "alignment" into their individual phones (one vector per...
Definition: hmm-utils.cc:723
HmmTopology GenRandTopology(const std::vector< int32 > &phones_in, const std::vector< int32 > &num_pdf_classes)
This method of generating an arbitrary HmmTopology object allows you to specify the number of pdf-cla...
void GenerateRandomAlignment(const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, bool reorder, const std::vector< int32 > &phone_sequence, std::vector< int32 > *alignment)
For use in test code, this function generates an alignment (a sequence of transition-ids) correspondi...
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
bool ConvertAlignment(const TransitionModel &old_trans_model, const TransitionModel &new_trans_model, const ContextDependencyInterface &new_ctx_dep, const std::vector< int32 > &old_alignment, int32 subsample_factor, bool repeat_frames, bool new_is_reordered, const std::vector< int32 > *phone_map, std::vector< int32 > *new_alignment)
ConvertAlignment converts an alignment that was created using one model, to another model...
Definition: hmm-utils.cc:1013
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestConvertPhnxToProns()

void kaldi::TestConvertPhnxToProns ( )

Definition at line 28 of file hmm-utils-test.cc.

References ConvertPhnxToProns(), KALDI_ASSERT, and words.

Referenced by main().

28  {
29 
30  int32 word_start_sym = 1, word_end_sym = 2;
31  { // empty test.
32  std::vector<int32> phnx;
33  std::vector<int32> words;
34  std::vector<std::vector<int32> > ans, ans_check;
35  KALDI_ASSERT(ConvertPhnxToProns(phnx, words, word_start_sym,
36  word_end_sym, &ans)
37  && ans == ans_check);
38  }
39 
40  { // test w/ one empty word.
41  std::vector<int32> phnx; phnx.push_back(3);
42  std::vector<int32> words;
43  std::vector<std::vector<int32> > ans;
44  std::vector<std::vector<int32> > ans_check(1);
45  ans_check[0].push_back(0);
46  ans_check[0].push_back(3);
47  KALDI_ASSERT(ConvertPhnxToProns(phnx, words, word_start_sym,
48  word_end_sym, &ans)
49  && ans == ans_check);
50  }
51 
52  { // test w/ one empty word with two phones.
53  std::vector<int32> phnx; phnx.push_back(3); phnx.push_back(4);
54  std::vector<int32> words;
55  std::vector<std::vector<int32> > ans;
56  std::vector<std::vector<int32> > ans_check(1);
57  ans_check[0].push_back(0);
58  ans_check[0].push_back(3);
59  ans_check[0].push_back(4);
60  KALDI_ASSERT(ConvertPhnxToProns(phnx, words, word_start_sym,
61  word_end_sym, &ans)
62  && ans == ans_check);
63  }
64 
65  { // test w/ zero -> should fail.
66  std::vector<int32> phnx; phnx.push_back(3); phnx.push_back(4);
67  phnx.push_back(0);
68  std::vector<int32> words;
69  std::vector<std::vector<int32> > ans;
70  KALDI_ASSERT(!ConvertPhnxToProns(phnx, words, word_start_sym,
71  word_end_sym, &ans));
72  }
73 
74  { // test w/ unexpected word-end -> should fail.
75  std::vector<int32> phnx; phnx.push_back(3); phnx.push_back(4);
76  phnx.push_back(word_end_sym);
77  std::vector<int32> words;
78  std::vector<std::vector<int32> > ans;
79  KALDI_ASSERT(!ConvertPhnxToProns(phnx, words, word_start_sym,
80  word_end_sym, &ans));
81 
82  }
83 
84  { // test w/ word-start but no word-end -> should fail.
85  std::vector<int32> phnx; phnx.push_back(3); phnx.push_back(4);
86  phnx.push_back(word_start_sym);
87  std::vector<int32> words;
88  std::vector<std::vector<int32> > ans;
89  KALDI_ASSERT(!ConvertPhnxToProns(phnx, words, word_start_sym,
90  word_end_sym, &ans));
91 
92  }
93 
94  { // test w/ one empty word then one real word w/ zero phones.
95  std::vector<int32> phnx; phnx.push_back(3); phnx.push_back(4);
96  phnx.push_back(word_start_sym); phnx.push_back(word_end_sym);
97  std::vector<int32> words; words.push_back(100);
98  std::vector<std::vector<int32> > ans;
99  std::vector<std::vector<int32> > ans_check(2);
100  ans_check[0].push_back(0);
101  ans_check[0].push_back(3);
102  ans_check[0].push_back(4);
103  ans_check[1].push_back(100);
104  KALDI_ASSERT(ConvertPhnxToProns(phnx, words, word_start_sym,
105  word_end_sym, &ans)
106  && ans == ans_check);
107  }
108 
109  { // test w/ one empty word then one real word w/ one phone..
110  std::vector<int32> phnx; phnx.push_back(3); phnx.push_back(4);
111  phnx.push_back(word_start_sym); phnx.push_back(5); phnx.push_back(word_end_sym);
112  std::vector<int32> words; words.push_back(100);
113  std::vector<std::vector<int32> > ans;
114  std::vector<std::vector<int32> > ans_check(2);
115  ans_check[0].push_back(0);
116  ans_check[0].push_back(3);
117  ans_check[0].push_back(4);
118  ans_check[1].push_back(100);
119  ans_check[1].push_back(5);
120  KALDI_ASSERT(ConvertPhnxToProns(phnx, words, word_start_sym,
121  word_end_sym, &ans)
122  && ans == ans_check);
123  }
124 
125  { // test w/ ONE real word w/ one phone..
126  std::vector<int32> phnx;
127  phnx.push_back(word_start_sym); phnx.push_back(5); phnx.push_back(word_end_sym);
128  std::vector<int32> words; words.push_back(100);
129  std::vector<std::vector<int32> > ans;
130  std::vector<std::vector<int32> > ans_check(1);
131  ans_check[0].push_back(100);
132  ans_check[0].push_back(5);
133  KALDI_ASSERT(ConvertPhnxToProns(phnx, words, word_start_sym,
134  word_end_sym, &ans)
135  && ans == ans_check);
136  }
137 
138  { // test w/ ONE real word w/ one phone, but no
139  // words supplied-- should fail.
140  std::vector<int32> phnx;
141  phnx.push_back(word_start_sym); phnx.push_back(5); phnx.push_back(word_end_sym);
142  std::vector<int32> words;
143  std::vector<std::vector<int32> > ans;
144  KALDI_ASSERT(!ConvertPhnxToProns(phnx, words, word_start_sym,
145  word_end_sym, &ans));
146  }
147 
148  { // test w/ ONE real word w/ one phone, but two
149  // words supplied-- should fail.
150  std::vector<int32> phnx;
151  phnx.push_back(word_start_sym); phnx.push_back(5); phnx.push_back(word_end_sym);
152  std::vector<int32> words(2, 10);
153  std::vector<std::vector<int32> > ans;
154  KALDI_ASSERT(!ConvertPhnxToProns(phnx, words, word_start_sym,
155  word_end_sym, &ans));
156  }
157 
158  { // test w/ ONE real word w/ one phone, but word-id
159  // is zero-- should fail.
160  std::vector<int32> phnx;
161  phnx.push_back(word_start_sym); phnx.push_back(5); phnx.push_back(word_end_sym);
162  std::vector<int32> words(1, 0);
163  std::vector<std::vector<int32> > ans;
164  KALDI_ASSERT(!ConvertPhnxToProns(phnx, words, word_start_sym,
165  word_end_sym, &ans));
166  }
167 
168  { // test w/ ONE real word w/ two phones, then one
169  // empty word...
170  std::vector<int32> phnx;
171  phnx.push_back(word_start_sym); phnx.push_back(5);
172  phnx.push_back(7); phnx.push_back(word_end_sym);
173  phnx.push_back(10);
174  std::vector<int32> words; words.push_back(100);
175  std::vector<std::vector<int32> > ans;
176  std::vector<std::vector<int32> > ans_check(2);
177  ans_check[0].push_back(100);
178  ans_check[0].push_back(5);
179  ans_check[0].push_back(7);
180  ans_check[1].push_back(0);
181  ans_check[1].push_back(10);
182  KALDI_ASSERT(ConvertPhnxToProns(phnx, words, word_start_sym,
183  word_end_sym, &ans)
184  && ans == ans_check);
185  }
186 }
int32 words[kMaxOrder]
bool ConvertPhnxToProns(const std::vector< int32 > &phnx, const std::vector< int32 > &words, int32 word_start_sym, int32 word_end_sym, std::vector< std::vector< int32 > > *prons)
Definition: hmm-utils.cc:1161
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestConvertStats()

void kaldi::TestConvertStats ( )

Definition at line 72 of file build-tree-utils-test.cc.

References ConvertStats(), and KALDI_ASSERT.

Referenced by main().

72  {
73  {
74  BuildTreeStatsType stats;
75  EventType evec;
76  // this example is of ctx window (10, 11, 12), and pdf-class = 1.
77  evec.push_back(std::pair<int32, int32>(-1, 1));
78  evec.push_back(std::pair<int32, int32>(0, 10));
79  evec.push_back(std::pair<int32, int32>(1, 11));
80  evec.push_back(std::pair<int32, int32>(2, 12));
81  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(NULL)));
82  int32 oldN = 3, oldP = 1, newN = 1, newP = 0;
83  ConvertStats(oldN, oldP, newN, newP, &stats);
84  EventType new_evec = stats[0].first;
85  KALDI_ASSERT(new_evec.size() == 2); // keys: -1, 0.
86  KALDI_ASSERT(new_evec[0].first == -1 && new_evec[0].second == 1);
87  KALDI_ASSERT(new_evec[1].first == 0 && new_evec[1].second == 11);
88  }
89 
90  { // as above, but convert to left bigram (N = 2, P = 1).
91  BuildTreeStatsType stats;
92  EventType evec;
93  // this example is of ctx window (10, 11, 12), and pdf-class = 1.
94  evec.push_back(std::pair<int32, int32>(-1, 1));
95  evec.push_back(std::pair<int32, int32>(0, 10));
96  evec.push_back(std::pair<int32, int32>(1, 11));
97  evec.push_back(std::pair<int32, int32>(2, 12));
98  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(NULL)));
99  int32 oldN = 3, oldP = 1, newN = 2, newP = 1;
100  ConvertStats(oldN, oldP, newN, newP, &stats);
101  EventType new_evec = stats[0].first;
102  KALDI_ASSERT(new_evec.size() == 3); // keys: -1, 0, 1.
103  KALDI_ASSERT(new_evec[0].first == -1 && new_evec[0].second == 1);
104  KALDI_ASSERT(new_evec[1].first == 0 && new_evec[1].second == 10);
105  KALDI_ASSERT(new_evec[2].first == 1 && new_evec[2].second == 11);
106  }
107 
108  { // as above, but leave unchanged.
109  BuildTreeStatsType stats;
110  EventType evec;
111  // this example is of ctx window (10, 11, 12), and pdf-class = 1.
112  evec.push_back(std::pair<int32, int32>(-1, 1));
113  evec.push_back(std::pair<int32, int32>(0, 10));
114  evec.push_back(std::pair<int32, int32>(1, 11));
115  evec.push_back(std::pair<int32, int32>(2, 12));
116  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(NULL)));
117  int32 oldN = 3, oldP = 1, newN = 3, newP = 1;
118  ConvertStats(oldN, oldP, newN, newP, &stats);
119  EventType new_evec = stats[0].first;
120  KALDI_ASSERT(new_evec == evec);
121  }
122 }
bool ConvertStats(int32 oldN, int32 oldP, int32 newN, int32 newP, BuildTreeStatsType *stats)
Converts stats from a given context-window (N) and central-position (P) to a different N and P...
kaldi::int32 int32
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType

◆ TestConvertStringToInteger()

void kaldi::TestConvertStringToInteger ( )

Definition at line 145 of file text-utils-test.cc.

References ConvertStringToInteger(), rnnlm::i, rnnlm::j, and KALDI_ASSERT.

Referenced by main().

145  {
146  int32 i;
147  KALDI_ASSERT(ConvertStringToInteger("12345", &i) && i == 12345);
148  KALDI_ASSERT(ConvertStringToInteger("-12345", &i) && i == -12345);
149  char j;
150  KALDI_ASSERT(!ConvertStringToInteger("-12345", &j)); // too big for char.
151 
152  KALDI_ASSERT(ConvertStringToInteger(" -12345 ", &i)); // whitespace accepted
153 
154  KALDI_ASSERT(!ConvertStringToInteger("a ", &i)); // non-integers rejected.
155 
156  KALDI_ASSERT(ConvertStringToInteger("0", &i) && i == 0);
157 
158  uint64 k;
159  KALDI_ASSERT(ConvertStringToInteger("12345", &k) && k == 12345);
160  KALDI_ASSERT(!ConvertStringToInteger("-12345", &k)); // unsigned,
161  // cannot convert.
162 }
bool ConvertStringToInteger(const std::string &str, Int *out)
Converts a string into an integer via strtoll and returns false if there was any kind of problem (i...
Definition: text-utils.h:118
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestConvertStringToReal()

void kaldi::TestConvertStringToReal ( )

Definition at line 165 of file text-utils-test.cc.

References ConvertStringToReal(), rnnlm::d, and KALDI_ASSERT.

165  {
166  Real d;
167  KALDI_ASSERT(ConvertStringToReal("1", &d) && d == 1.0);
168  KALDI_ASSERT(ConvertStringToReal("-1", &d) && d == -1.0);
169  KALDI_ASSERT(ConvertStringToReal("-1", &d) && d == -1.0);
170  KALDI_ASSERT(ConvertStringToReal(" -1 ", &d) && d == -1.0);
171  KALDI_ASSERT(!ConvertStringToReal("-1 x", &d));
172  KALDI_ASSERT(!ConvertStringToReal("-1f", &d));
173  KALDI_ASSERT(ConvertStringToReal("12345.2", &d) && fabs(d-12345.2) < 1.0);
174  KALDI_ASSERT(ConvertStringToReal("1.0e+08", &d) && fabs(d-1.0e+08) < 100.0);
175 
176  // it also works for inf or nan.
177  KALDI_ASSERT(ConvertStringToReal("inf", &d) && d > 0 && d - d != 0);
178  KALDI_ASSERT(ConvertStringToReal(" inf", &d) && d > 0 && d - d != 0);
179  KALDI_ASSERT(ConvertStringToReal("inf ", &d) && d > 0 && d - d != 0);
180  KALDI_ASSERT(ConvertStringToReal(" inf ", &d) && d > 0 && d - d != 0);
181  KALDI_ASSERT(ConvertStringToReal("+inf", &d) && d > 0 && d - d != 0);
182  KALDI_ASSERT(ConvertStringToReal("-inf", &d) && d < 0 && d - d != 0);
183  KALDI_ASSERT(ConvertStringToReal("Inf", &d) && d > 0 && d - d != 0);
184  KALDI_ASSERT(ConvertStringToReal("INF", &d) && d > 0 && d - d != 0);
185  KALDI_ASSERT(ConvertStringToReal("InF", &d) && d > 0 && d - d != 0);
186  KALDI_ASSERT(ConvertStringToReal("infinity", &d) && d > 0 && d - d != 0);
187  KALDI_ASSERT(ConvertStringToReal("-infinity", &d) && d < 0 && d - d != 0);
188  KALDI_ASSERT(!ConvertStringToReal("GARBAGE inf", &d));
189  KALDI_ASSERT(!ConvertStringToReal("GARBAGEinf", &d));
190  KALDI_ASSERT(!ConvertStringToReal("infGARBAGE", &d));
191  KALDI_ASSERT(!ConvertStringToReal("inf_GARBAGE", &d));
192  KALDI_ASSERT(!ConvertStringToReal("inf GARBAGE", &d));
193  KALDI_ASSERT(!ConvertStringToReal("GARBAGE infinity", &d));
194  KALDI_ASSERT(!ConvertStringToReal("GARBAGEinfinity", &d));
195  KALDI_ASSERT(!ConvertStringToReal("infinityGARBAGE", &d));
196  KALDI_ASSERT(!ConvertStringToReal("infinity_GARBAGE", &d));
197  KALDI_ASSERT(!ConvertStringToReal("infinity GARBAGE", &d));
198  KALDI_ASSERT(ConvertStringToReal("1.#INF", &d) && d > 0 && d - d != 0);
199  KALDI_ASSERT(ConvertStringToReal("-1.#INF", &d) && d < 0 && d - d != 0);
200  KALDI_ASSERT(ConvertStringToReal("-1.#INF ", &d) && d < 0 && d - d != 0);
201  KALDI_ASSERT(ConvertStringToReal(" -1.#INF ", &d) && d < 0 && d - d != 0);
202  KALDI_ASSERT(!ConvertStringToReal("GARBAGE 1.#INF", &d));
203  KALDI_ASSERT(!ConvertStringToReal("GARBAGE1.#INF", &d));
204  KALDI_ASSERT(!ConvertStringToReal("2.#INF", &d));
205  KALDI_ASSERT(!ConvertStringToReal("-2.#INF", &d));
206  KALDI_ASSERT(!ConvertStringToReal("1.#INFGARBAGE", &d));
207  KALDI_ASSERT(!ConvertStringToReal("1.#INF_GARBAGE", &d));
208 
209  KALDI_ASSERT(ConvertStringToReal("nan", &d) && d != d);
210  KALDI_ASSERT(ConvertStringToReal("+nan", &d) && d != d);
211  KALDI_ASSERT(ConvertStringToReal("-nan", &d) && d != d);
212  KALDI_ASSERT(ConvertStringToReal("Nan", &d) && d != d);
213  KALDI_ASSERT(ConvertStringToReal("NAN", &d) && d != d);
214  KALDI_ASSERT(ConvertStringToReal("NaN", &d) && d != d);
215  KALDI_ASSERT(ConvertStringToReal(" NaN", &d) && d != d);
216  KALDI_ASSERT(ConvertStringToReal("NaN ", &d) && d != d);
217  KALDI_ASSERT(ConvertStringToReal(" NaN ", &d) && d != d);
218  KALDI_ASSERT(ConvertStringToReal("1.#QNAN", &d) && d != d);
219  KALDI_ASSERT(ConvertStringToReal("-1.#QNAN", &d) && d != d);
220  KALDI_ASSERT(ConvertStringToReal("1.#QNAN ", &d) && d != d);
221  KALDI_ASSERT(ConvertStringToReal(" 1.#QNAN ", &d) && d != d);
222  KALDI_ASSERT(!ConvertStringToReal("GARBAGE nan", &d));
223  KALDI_ASSERT(!ConvertStringToReal("GARBAGEnan", &d));
224  KALDI_ASSERT(!ConvertStringToReal("nanGARBAGE", &d));
225  KALDI_ASSERT(!ConvertStringToReal("nan_GARBAGE", &d));
226  KALDI_ASSERT(!ConvertStringToReal("nan GARBAGE", &d));
227  KALDI_ASSERT(!ConvertStringToReal("GARBAGE 1.#QNAN", &d));
228  KALDI_ASSERT(!ConvertStringToReal("GARBAGE1.#QNAN", &d));
229  KALDI_ASSERT(!ConvertStringToReal("2.#QNAN", &d));
230  KALDI_ASSERT(!ConvertStringToReal("-2.#QNAN", &d));
231  KALDI_ASSERT(!ConvertStringToReal("-1.#QNAN_GARBAGE", &d));
232  KALDI_ASSERT(!ConvertStringToReal("-1.#QNANGARBAGE", &d));
233 }
bool ConvertStringToReal(const std::string &str, T *out)
ConvertStringToReal converts a string into either float or double and returns false if there was any ...
Definition: text-utils.cc:238
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestCopyMapKeysToSet()

void kaldi::TestCopyMapKeysToSet ( )

Definition at line 158 of file stl-utils-test.cc.

References CopyMapKeysToSet(), CopyMapKeysToVector(), CopyVectorToSet(), rnnlm::i, KALDI_ASSERT, and Rand().

Referenced by main().

158  {
159  for (int p = 0; p < 100; p++) {
160  std::map<int, int> mp;
161  int sz = Rand() % 20;
162  for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
163  std::vector<int> v;
164  std::set<int> s;
165  CopyMapKeysToVector(mp, &v);
166  CopyMapKeysToSet(mp, &s);
167  std::set<int> s2;
168  CopyVectorToSet(v, &s2);
169  KALDI_ASSERT(s == s2);
170  }
171 }
void CopyMapKeysToVector(const std::map< A, B > &m, std::vector< A > *v)
Copies the keys in a map to a vector.
Definition: stl-utils.h:126
void CopyVectorToSet(const std::vector< A > &v, std::set< A > *s)
Copies the contents of a vector to a set.
Definition: stl-utils.h:172
void CopyMapKeysToSet(const std::map< A, B > &m, std::set< A > *s)
Copies the keys in a map to a set.
Definition: stl-utils.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestCopyMapKeysToVector()

void kaldi::TestCopyMapKeysToVector ( )

Definition at line 130 of file stl-utils-test.cc.

References CopyMapKeysToVector(), rnnlm::i, KALDI_ASSERT, and Rand().

Referenced by main().

130  {
131  for (int p = 0; p < 100; p++) {
132  std::map<int, int> mp;
133  int sz = Rand() % 20;
134  for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
135  std::vector<int> v;
136  CopyMapKeysToVector(mp, &v);
137  KALDI_ASSERT(mp.size() == v.size());
138  for (size_t i = 0;i < v.size();i++) KALDI_ASSERT(mp.count(v[i]) == 1);
139  }
140 }
void CopyMapKeysToVector(const std::map< A, B > &m, std::vector< A > *v)
Copies the keys in a map to a vector.
Definition: stl-utils.h:126
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestCopyMapToVector()

void kaldi::TestCopyMapToVector ( )

Definition at line 116 of file stl-utils-test.cc.

References CopyMapToVector(), rnnlm::i, KALDI_ASSERT, and Rand().

Referenced by main().

116  {
117  for (int p = 0; p < 100; p++) {
118  std::map<int, int> mp;
119  int sz = Rand() % 20;
120  for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
121  std::vector<std::pair<int, int> > v;
122  CopyMapToVector(mp, &v);
123  KALDI_ASSERT(mp.size() == v.size());
124  for (size_t i = 0;i < v.size();i++)
125  KALDI_ASSERT(mp[v[i].first] == v[i].second);
126  }
127 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void CopyMapToVector(const std::map< A, B > &m, std::vector< std::pair< A, B > > *v)
Copies the (key, value) pairs in a map to a vector of pairs.
Definition: stl-utils.h:112

◆ TestCopyMapValuesToSet()

void kaldi::TestCopyMapValuesToSet ( )

Definition at line 174 of file stl-utils-test.cc.

References CopyMapValuesToSet(), CopyMapValuesToVector(), CopyVectorToSet(), rnnlm::i, KALDI_ASSERT, and Rand().

Referenced by main().

174  {
175  for (int p = 0; p < 100; p++) {
176  std::map<int, int> mp;
177  int sz = Rand() % 20;
178  for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
179  std::vector<int> v;
180  std::set<int> s;
181  CopyMapValuesToVector(mp, &v);
182  CopyMapValuesToSet(mp, &s);
183  std::set<int> s2;
184  CopyVectorToSet(v, &s2);
185  KALDI_ASSERT(s == s2);
186  }
187 }
void CopyMapValuesToSet(const std::map< A, B > &m, std::set< B > *s)
Copies the values in a map to a set.
Definition: stl-utils.h:161
void CopyVectorToSet(const std::vector< A > &v, std::set< A > *s)
Copies the contents of a vector to a set.
Definition: stl-utils.h:172
void CopyMapValuesToVector(const std::map< A, B > &m, std::vector< B > *v)
Copies the values in a map to a vector.
Definition: stl-utils.h:138
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestCopyMapValuesToVector()

void kaldi::TestCopyMapValuesToVector ( )

Definition at line 142 of file stl-utils-test.cc.

References CopyMapValuesToVector(), rnnlm::i, KALDI_ASSERT, and Rand().

Referenced by main().

142  {
143  for (int p = 0; p < 100; p++) {
144  std::map<int, int> mp;
145  int sz = Rand() % 20;
146  for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
147  std::vector<int> v;
148  CopyMapValuesToVector(mp, &v);
149  KALDI_ASSERT(mp.size() == v.size());
150  int i = 0;
151  for (std::map<int, int>::iterator iter = mp.begin(); iter != mp.end();
152  iter++) {
153  KALDI_ASSERT(v[i++] == iter->second);
154  }
155  }
156 }
void CopyMapValuesToVector(const std::map< A, B > &m, std::vector< B > *v)
Copies the values in a map to a vector.
Definition: stl-utils.h:138
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestCopySetToVector()

void kaldi::TestCopySetToVector ( )

Definition at line 103 of file stl-utils-test.cc.

References CopySetToVector(), rnnlm::i, KALDI_ASSERT, and Rand().

Referenced by main().

103  {
104  for (int p = 0; p < 100; p++) {
105  std::set<int> st;
106  int sz = Rand() % 20;
107  for (int i = 0;i < sz;i++) st.insert(Rand() % 10);
108  std::vector<int> v;
109  CopySetToVector(st, &v);
110  KALDI_ASSERT(st.size() == v.size());
111  for (size_t i = 0;i < v.size();i++) KALDI_ASSERT(st.count(v[i]) != 0);
112  }
113 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestCuFindRowMaxId()

static void kaldi::TestCuFindRowMaxId ( int32  dim)
static

Definition at line 368 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::CopyFromMat(), CuArrayBase< T >::CopyToVec(), Timer::Elapsed(), CuMatrixBase< Real >::FindRowMaxId(), KALDI_ASSERT, KALDI_LOG, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), and MatrixBase< Real >::SetRandn().

368  {
369 
370  int32 dimM = dim, dimN = dimM + Rand() % 5;
371 
372  Matrix<Real> Hi(dimM, dimN);
373  Hi.SetRandn();
374 
375  CuMatrix<Real> Di(dimM, dimN);
376  Di.CopyFromMat(Hi);
377 
378  std::vector<int32> Hmax(dimM);
379  CuArray<int32> Dmax(dimN);
380 
381  BaseFloat time_in_secs = 0.025;
382  int iter = 0;
383  Timer tim;
384  for (;tim.Elapsed() < time_in_secs; iter++)
385  Di.FindRowMaxId(&Dmax);
386 
387 
388  BaseFloat fdim = dim;
389  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
390  KALDI_LOG << "For CuMatrix::FindRowMaxId" << NameOf<Real>() << ", for dim = "
391  << dim << ", speed was " << gflops << " gigaflops.";
392 
393 
394  // on cpu
395  for(MatrixIndexT r=0; r<Hi.NumRows(); r++) {
396  Real max=-1.0e+20; int32 idx=-1;
397  for(MatrixIndexT c=0; c<Hi.NumCols(); c++) {
398  if(Hi(r,c) > max) { idx=c; max=Hi(r,c); }
399  }
400  Hmax[r] = idx;
401  }
402  std::vector<int32> Hmax2(dimM);
403  Dmax.CopyToVec(&Hmax2);
404 
405  KALDI_ASSERT(Hmax == Hmax2);
406 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixAddDiagVecMat()

void kaldi::TestCuMatrixAddDiagVecMat ( int32  dim,
MatrixTransposeType  trans 
)

Definition at line 265 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::AddDiagVecMat(), Timer::Elapsed(), KALDI_LOG, kTrans, and CuVectorBase< Real >::SetRandn().

265  {
266  BaseFloat time_in_secs = 0.015;
267  CuMatrix<Real> M(dim, dim), N(dim, dim);
268  CuVector<Real> v(dim);
269  M.SetRandn();
270  v.SetRandn();
271  Timer tim;
272  int32 iter = 0;
273  for (;tim.Elapsed() < time_in_secs; iter++)
274  N.AddDiagVecMat(1.0, v, M, trans, 0.0);
275 
276  BaseFloat fdim = dim;
277  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
278  KALDI_LOG << "For CuMatrix::AddDiagVecMat" << NameOf<Real>()
279  << (trans == kTrans ? "[trans]" : "[no-trans]")
280  << ", for dim = " << dim << ", speed was "
281  << gflops << " gigaflops.";
282 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixAddMat()

void kaldi::TestCuMatrixAddMat ( int32  dim,
int32  num_row_blocks,
int32  num_col_blocks 
)

Definition at line 169 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, rnnlm::j, KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

170  {
171  BaseFloat time_in_secs = 0.025;
172  CuMatrix<Real> A(dim, dim), B(dim * num_row_blocks, dim * num_col_blocks);
173  A.SetRandn();
174  B.SetRandn();
175  Timer tim;
176  int32 iter = 0;
177  for (;tim.Elapsed() < time_in_secs; iter++) {
178  for (int32 i = 0; i < num_row_blocks; i++) {
179  for (int32 j = 0; j < num_col_blocks; j++) {
180  A.AddMat(0.0, CuSubMatrix<Real>(B, i * dim, dim, j * dim, dim));
181  }
182  }
183  }
184  BaseFloat fdim = dim;
185  BaseFloat gflops = (fdim * fdim * num_row_blocks * num_col_blocks * iter)
186  / (tim.Elapsed() * 1.0e+09);
187  KALDI_LOG << "For CuMatrix::AddMat" << NameOf<Real>() << ", for dim = "
188  << dim << "numRowBlocks = "<< num_row_blocks << "numColBlocks = "
189  << num_col_blocks << ", speed was " << gflops << " gigaflops.";
190 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
This class is used for a piece of a CuMatrix.
Definition: matrix-common.h:70
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixAddMatBlocks()

void kaldi::TestCuMatrixAddMatBlocks ( int32  dim,
int32  num_row_blocks,
int32  num_col_blocks 
)

Definition at line 192 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

194  {
195  BaseFloat time_in_secs = 0.025;
196  CuMatrix<Real> A(dim, dim), B(dim * num_row_blocks, dim * num_col_blocks);
197  A.SetRandn();
198  B.SetRandn();
199  Timer tim;
200  int32 iter = 0;
201  for (;tim.Elapsed() < time_in_secs; iter++) {
202  A.AddMatBlocks(0.0, B);
203  }
204  BaseFloat fdim = dim;
205  BaseFloat gflops = (fdim * fdim * num_row_blocks * num_col_blocks * iter)
206  / (tim.Elapsed() * 1.0e+09);
207  KALDI_LOG << "For CuMatrix::AddMatBlocks" << NameOf<Real>() << ", for dim = "
208  << dim << ", numRowBlocks = "<< num_row_blocks << ", numColBlocks = "
209  << num_col_blocks << ", speed was " << gflops << " gigaflops.";
210 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixAddRowRanges()

void kaldi::TestCuMatrixAddRowRanges ( int32  dim)

Definition at line 958 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

958  {
959  BaseFloat time_in_secs = 0.025;
960  CuMatrix<Real> M(dim, dim), N(dim, dim);
961  M.SetRandn();
962  N.SetRandn();
963 
964  std::vector<Int32Pair> indexes(dim);
965  for (int32 i = 0; i < dim; i++) {
966  indexes[i].first = i;
967  indexes[i].second = i + 1;
968  }
969  CuArray<Int32Pair> indexes_cuda(indexes);
970 
971  Timer tim;
972  int32 iter = 0;
973  for (; tim.Elapsed() < time_in_secs; iter++) {
974  M.AddRowRanges(N, indexes_cuda);
975  }
976 
977  BaseFloat fdim = dim;
978  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
979  KALDI_LOG << "For CuMatrix::AddRowRanges" << NameOf<Real>() << ", for dim = "
980  << dim << ", speed was " << gflops << " gigaflops.";
981 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixAddRows1()

void kaldi::TestCuMatrixAddRows1 ( int32  dim)

Definition at line 886 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

886  {
887  BaseFloat time_in_secs = 0.025;
888  CuMatrix<Real> M(dim, dim), N(dim, dim);
889  M.SetRandn();
890  N.SetRandn();
891 
892  std::vector<int32> reorder(dim);
893  for (int32 i = 0; i < dim; i++) {
894  reorder[i] = i;
895  }
896  CuArray<int32> reorder_cuda(reorder);
897 
898  Timer tim;
899  int32 iter = 0;
900  for (; tim.Elapsed() < time_in_secs; iter++) {
901  M.AddRows(0.5, N, reorder_cuda);
902  }
903 
904  BaseFloat fdim = dim;
905  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
906  KALDI_LOG << "For CuMatrix::AddRows" << NameOf<Real>() << ", for dim = "
907  << dim << ", speed was " << gflops << " gigaflops.";
908 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixAddRows2()

void kaldi::TestCuMatrixAddRows2 ( int32  dim)

Definition at line 910 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, CuMatrixBase< Real >::RowData(), and CuMatrixBase< Real >::SetRandn().

910  {
911  BaseFloat time_in_secs = 0.025;
912  CuMatrix<Real> M(dim, dim), N(dim, dim);
913  M.SetRandn();
914  N.SetRandn();
915 
916  std::vector<const Real*> reorder_src(dim, NULL);
917  for (int32 i = 0; i < dim; i++) {
918  reorder_src[i] = N.RowData(i);
919  }
920  CuArray<const Real*> reorder_src_cuda(reorder_src);
921 
922  Timer tim;
923  int32 iter = 0;
924  for (; tim.Elapsed() < time_in_secs; iter++) {
925  M.AddRows(0.5, reorder_src_cuda);
926  }
927 
928  BaseFloat fdim = dim;
929  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
930  KALDI_LOG << "For CuMatrix::AddRows" << NameOf<Real>() << ", for dim = "
931  << dim << ", speed was " << gflops << " gigaflops.";
932 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
Class CuArray represents a vector of an integer or struct of type T.
Definition: cu-array.h:32
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixAddToRows()

void kaldi::TestCuMatrixAddToRows ( int32  dim)

Definition at line 934 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, CuMatrixBase< Real >::RowData(), and CuMatrixBase< Real >::SetRandn().

934  {
935  BaseFloat time_in_secs = 0.025;
936  CuMatrix<Real> M(dim, dim), N(dim, dim);
937  M.SetRandn();
938  N.SetRandn();
939 
940  std::vector<Real*> reorder_dst(dim, NULL);
941  for (int32 i = 0; i < dim; i++) {
942  reorder_dst[i] = N.RowData(i);
943  }
944  CuArray<Real*> reorder_dst_cuda(reorder_dst);
945 
946  Timer tim;
947  int32 iter = 0;
948  for (; tim.Elapsed() < time_in_secs; iter++) {
949  M.AddToRows(0.5, reorder_dst_cuda);
950  }
951 
952  BaseFloat fdim = dim;
953  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
954  KALDI_LOG << "For CuMatrix::AddToRows" << NameOf<Real>() << ", for dim = "
955  << dim << ", speed was " << gflops << " gigaflops.";
956 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
Class CuArray represents a vector of an integer or struct of type T.
Definition: cu-array.h:32
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCholesky()

void kaldi::TestCuMatrixCholesky ( int32  dim)

Definition at line 652 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::AddToDiag(), CuMatrixBase< Real >::Cholesky(), Timer::Elapsed(), and KALDI_LOG.

652  {
653  BaseFloat time_in_secs = 0.025;
654 
655  CuMatrix<Real> M(dim, dim);
656  M.AddToDiag(100.0);
657  Timer tim;
658  int32 iter = 0;
659  for (;tim.Elapsed() < time_in_secs; iter++)
660  M.Cholesky();
661 
662  BaseFloat fdim = dim;
663  BaseFloat gflops = (fdim * fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
664  KALDI_LOG << "For CuMatrix::Cholesky" << NameOf<Real>()
665  << ", for dim = " << dim << ", speed was " << gflops << " gigaflops.";
666 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCompObjfAndDeriv()

static void kaldi::TestCuMatrixCompObjfAndDeriv ( int32  dim)
static

Definition at line 308 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::Add(), CuMatrixBase< Real >::ApplyFloor(), CuMatrixBase< Real >::ApplyLog(), ApproxEqual(), CuMatrix< Real >::CompObjfAndDeriv(), Timer::Elapsed(), rnnlm::i, CuMatrixBase< Real >::InvertElements(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, kTrans, Rand(), RandUniform(), CuMatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::SetZero(), and TraceMatMat().

308  {
309  BaseFloat time_in_secs = 0.025;
310  // Previously tested for larger dims, but test was slow.
311 
312  int32 n_r = dim, n_c = dim + Rand() % 5;
313 
314  CuMatrix<Real> A(n_r, n_c), B(n_r, n_c);
315  B.SetRandn();
316  B.Add(1.0);
317  B.ApplyFloor(1.0e-10);
318 
319  std::vector<MatrixElement<Real> > labels;
320  for(int i = 0; i < n_r; i++) {
321  for(int j = 0; j < n_c; j++) {
322  // have approximately one weight per row of the matrix.
323  if (Rand() % n_c == 0) {
324  A(i, j) = RandUniform();
325  MatrixElement<Real> t = {i, j, A(i, j)};
326  labels.push_back(t);
327  }
328  }
329  }
330  CuMatrix<Real> C(n_r, n_c);
331 
332  int iter = 0;
333  Timer tim;
334  Real a = 0.0, b = 0.0;
335  for (;tim.Elapsed() < time_in_secs; iter++)
336  C.CompObjfAndDeriv(labels, B, &a, &b);
337 
338  BaseFloat gflops = (n_r * n_c * iter) / (tim.Elapsed() * 1.0e+09);
339  KALDI_LOG << "For CuMatrix::CompObjfAndDeriv" << NameOf<Real>() << ", for dim = "
340  << dim << ", speed was " << gflops << " gigaflops.";
341 
342 
343  // do it one more time for correctness test.
344  C.SetZero();
345  C.CompObjfAndDeriv(labels, B, &a, &b);
346 
347  KALDI_ASSERT(ApproxEqual(b, A.Sum()));
348 
349  // repeat the real test.
350  Real sum2; // sum(i, j) A(i, j) log(B(i, j));
351  {
352  CuMatrix<Real> Bcopy(B);
353  Bcopy.ApplyLog();
354  sum2 = TraceMatMat(Bcopy, A, kTrans);
355  }
356 
357  KALDI_ASSERT(ApproxEqual(a, sum2));
358 
359  B.InvertElements();
360  A.MulElements(B); // each element of A is now A(i, j) / B(i, j);
361  KALDI_ASSERT(ApproxEqual(A, C));
362 
363 
364 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ TestCuMatrixCopyFromSp()

void kaldi::TestCuMatrixCopyFromSp ( int32  dim)

Definition at line 712 of file cu-matrix-speed-test.cc.

References AssertEqual(), CuMatrixBase< Real >::CopyFromSp(), Timer::Elapsed(), KALDI_LOG, and CuPackedMatrix< Real >::SetRandn().

712  {
713  BaseFloat time_in_secs = 0.025;
714  CuSpMatrix<Real> S(dim);
715  S.SetRandn();
716  CuMatrix<Real> M(dim, dim);
717 
718  Timer tim;
719  int32 iter = 0;
720  for (; tim.Elapsed() < time_in_secs; iter++) {
721  M.CopyFromSp(S);
722  }
723  SpMatrix<Real> S_cpu(S);
724  Matrix<Real> M_cpu(S_cpu);
725  Matrix<Real> M2_cpu(M);
726  AssertEqual(M_cpu, M2_cpu);
727 
728  BaseFloat fdim = dim;
729  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
730  KALDI_LOG << "For CuMatrix::CopyFromSp" << NameOf<Real>() << ", for dim = "
731  << dim << ", speed was " << gflops << " gigaflops.";
732 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCopyFromTp()

void kaldi::TestCuMatrixCopyFromTp ( int32  dim,
MatrixTransposeType  trans 
)

Definition at line 688 of file cu-matrix-speed-test.cc.

References AssertEqual(), CuMatrixBase< Real >::CopyFromTp(), Timer::Elapsed(), KALDI_LOG, kNoTrans, and CuPackedMatrix< Real >::SetRandn().

688  {
689  BaseFloat time_in_secs = 0.025;
690  CuTpMatrix<Real> T(dim);
691  T.SetRandn();
692  CuMatrix<Real> M(dim, dim);
693 
694  Timer tim;
695  int32 iter = 0;
696  for (; tim.Elapsed() < time_in_secs; iter++) {
697  M.CopyFromTp(T, trans);
698  }
699  TpMatrix<Real> T_cpu(T);
700  Matrix<Real> M_cpu(T_cpu, trans);
701  Matrix<Real> M2_cpu(M);
702  AssertEqual(M_cpu, M2_cpu);
703 
704  BaseFloat fdim = dim;
705  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
706  KALDI_LOG << "For CuMatrix::CopyFromTp" << (trans == kNoTrans ? "[NoTrans]":"[Trans]")
707  << NameOf<Real>() << ", for dim = "
708  << dim << ", speed was " << gflops << " gigaflops.";
709 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
Packed symetric matrix class.
Definition: matrix-common.h:63
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCopyLowerToUpper()

void kaldi::TestCuMatrixCopyLowerToUpper ( int32  dim)

Definition at line 670 of file cu-matrix-speed-test.cc.

References AssertEqual(), CuMatrixBase< Real >::CopyLowerToUpper(), Timer::Elapsed(), KALDI_LOG, kTrans, and CuMatrixBase< Real >::SetRandn().

670  {
671  BaseFloat time_in_secs = 0.025;
672  CuMatrix<Real> M(dim, dim);
673  M.SetRandn();
674  Timer tim;
675  int32 iter = 0;
676  for (; tim.Elapsed() < time_in_secs; iter++) {
677  M.CopyLowerToUpper();
678  }
679  CuMatrix<Real> M2(M, kTrans);
680  AssertEqual(M, M2);
681  BaseFloat fdim = dim;
682  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
683  KALDI_LOG << "For CuMatrix::CopyLowerToUpper" << NameOf<Real>() << ", for dim = "
684  << dim << ", speed was " << gflops << " gigaflops.";
685 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCopyRows1()

void kaldi::TestCuMatrixCopyRows1 ( int32  dim)

Definition at line 814 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

814  {
815  BaseFloat time_in_secs = 0.025;
816  CuMatrix<Real> M(dim, dim), N(dim, dim);
817  M.SetRandn();
818  N.SetRandn();
819 
820  std::vector<int32> reorder(dim);
821  for (int32 i = 0; i < dim; i++) {
822  reorder[i] = i;
823  }
824  CuArray<int32> reorder_cuda(reorder);
825 
826  Timer tim;
827  int32 iter = 0;
828  for (; tim.Elapsed() < time_in_secs; iter++) {
829  M.CopyRows(N, reorder_cuda);
830  }
831 
832  BaseFloat fdim = dim;
833  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
834  KALDI_LOG << "For CuMatrix::CopyRows" << NameOf<Real>() << ", for dim = "
835  << dim << ", speed was " << gflops << " gigaflops.";
836 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCopyRows2()

void kaldi::TestCuMatrixCopyRows2 ( int32  dim)

Definition at line 838 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, CuMatrixBase< Real >::RowData(), and CuMatrixBase< Real >::SetRandn().

838  {
839  BaseFloat time_in_secs = 0.025;
840  CuMatrix<Real> M(dim, dim), N(dim, dim);
841  M.SetRandn();
842  N.SetRandn();
843 
844  std::vector<const Real*> reorder_src(dim, NULL);
845  for (int32 i = 0; i < dim; i++) {
846  reorder_src[i] = N.RowData(i);
847  }
848  CuArray<const Real*> reorder_src_cuda(reorder_src);
849 
850  Timer tim;
851  int32 iter = 0;
852  for (; tim.Elapsed() < time_in_secs; iter++) {
853  M.CopyRows(reorder_src_cuda);
854  }
855 
856  BaseFloat fdim = dim;
857  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
858  KALDI_LOG << "For CuMatrix::CopyRows" << NameOf<Real>() << ", for dim = "
859  << dim << ", speed was " << gflops << " gigaflops.";
860 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
Class CuArray represents a vector of an integer or struct of type T.
Definition: cu-array.h:32
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCopyToRows()

void kaldi::TestCuMatrixCopyToRows ( int32  dim)

Definition at line 862 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, CuMatrixBase< Real >::RowData(), and CuMatrixBase< Real >::SetRandn().

862  {
863  BaseFloat time_in_secs = 0.025;
864  CuMatrix<Real> M(dim, dim), N(dim, dim);
865  M.SetRandn();
866  N.SetRandn();
867 
868  std::vector<Real*> reorder_dst(dim, NULL);
869  for (int32 i = 0; i < dim; i++) {
870  reorder_dst[i] = N.RowData(i);
871  }
872  CuArray<Real*> reorder_dst_cuda(reorder_dst);
873 
874  Timer tim;
875  int32 iter = 0;
876  for (; tim.Elapsed() < time_in_secs; iter++) {
877  M.CopyToRows(reorder_dst_cuda);
878  }
879 
880  BaseFloat fdim = dim;
881  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
882  KALDI_LOG << "For CuMatrix::CopyToRows" << NameOf<Real>() << ", for dim = "
883  << dim << ", speed was " << gflops << " gigaflops.";
884 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
Class CuArray represents a vector of an integer or struct of type T.
Definition: cu-array.h:32
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixCopyUpperToLower()

void kaldi::TestCuMatrixCopyUpperToLower ( int32  dim)

Definition at line 736 of file cu-matrix-speed-test.cc.

References AssertEqual(), CuMatrixBase< Real >::CopyUpperToLower(), Timer::Elapsed(), KALDI_LOG, kTrans, kUndefined, CuMatrixBase< Real >::SetRandn(), and TestCuMatrixResize().

736  {
737  BaseFloat time_in_secs = 0.025;
738  CuMatrix<Real> M(dim, dim);
739  M.SetRandn();
740  Timer tim;
741  int32 iter = 0;
742  for (; tim.Elapsed() < time_in_secs; iter++) {
743  M.CopyUpperToLower();
744  }
745  CuMatrix<Real> M2(M, kTrans);
746  AssertEqual(M, M2);
747  BaseFloat fdim = dim;
748  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
749  KALDI_LOG << "For CuMatrix::CopyUpperToLower" << NameOf<Real>() << ", for dim = "
750  << dim << ", speed was " << gflops << " gigaflops.";
751 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixDiffGroupPnorm()

void kaldi::TestCuMatrixDiffGroupPnorm ( int32  dim)

Definition at line 553 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), CuMatrixBase< Real >::GroupPnorm(), KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

553  {
554  BaseFloat time_in_secs = 0.025;
555  int32 group_size = 8;
556  CuMatrix<Real> iv(dim, dim), ov(dim, dim / group_size);
557  CuMatrix<Real> id(dim, dim), od(dim, dim / group_size);
558  iv.SetRandn();
559  od.SetRandn();
560  ov.GroupPnorm(iv, 2.0);
561  Timer tim;
562  int32 iter = 0;
563 
564  for (; tim.Elapsed() < time_in_secs; iter++)
565  id.DiffGroupPnorm(iv, ov, od, 2.0);
566 
567  BaseFloat fdim = dim;
568  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
569  KALDI_LOG << "For CuMatrix::DiffGroupPnorm" << NameOf<Real>() << ", for dim = "
570  << dim << ", speed was " << gflops << " gigaflops.";
571 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixDiffLogSoftmax()

void kaldi::TestCuMatrixDiffLogSoftmax ( int32  dim)

Definition at line 482 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

482  {
483  BaseFloat time_in_secs = 0.025;
484  CuMatrix<Real> M(dim, dim), N(dim, dim), L(dim, dim);
485  M.SetRandn();
486  N.SetRandn();
487  L.SetRandn();
488  Timer tim;
489  int32 iter = 0;
490  for (; tim.Elapsed() < time_in_secs; iter++) {
491  N.DiffLogSoftmaxPerRow(M, L);
492  }
493 
494  BaseFloat fdim = dim;
495  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
496  KALDI_LOG << "For CuMatrix::DiffLogSoftmaxPerRow" << NameOf<Real>() << ", for dim = "
497  << dim << ", speed was " << gflops << " gigaflops.";
498 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixDiffSoftmax()

void kaldi::TestCuMatrixDiffSoftmax ( int32  dim)

Definition at line 464 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

464  {
465  BaseFloat time_in_secs = 0.025;
466  CuMatrix<Real> M(dim, dim), N(dim, dim), L(dim, dim);
467  M.SetRandn();
468  N.SetRandn();
469  L.SetRandn();
470  Timer tim;
471  int32 iter = 0;
472  for (; tim.Elapsed() < time_in_secs; iter++) {
473  N.DiffSoftmaxPerRow(M, L);
474  }
475 
476  BaseFloat fdim = dim;
477  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
478  KALDI_LOG << "For CuMatrix::DiffSoftmaxPerRow" << NameOf<Real>() << ", for dim = "
479  << dim << ", speed was " << gflops << " gigaflops.";
480 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixDivRowsVec()

void kaldi::TestCuMatrixDivRowsVec ( int32  dim)

Definition at line 97 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::DivRowsVec(), Timer::Elapsed(), KALDI_LOG, CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

97  {
98  BaseFloat time_in_secs = 0.025;
99  CuMatrix<Real> M(dim, dim);
100  CuVector<Real> V(dim);
101  M.SetRandn();
102  V.SetRandn();
103 
104  Timer tim;
105  int32 iter = 0;
106  for (; tim.Elapsed() < time_in_secs; iter++) {
107  M.DivRowsVec(V);
108  }
109 
110  BaseFloat fdim = dim;
111  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
112  KALDI_LOG<< "For CuMatrix::DivRowsVec" << NameOf<Real>() << ", for dim = "
113  << dim << ", speed was " << gflops << " gigaflops.";
114 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixGroupMax()

void kaldi::TestCuMatrixGroupMax ( int32  dim)

Definition at line 573 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), CuMatrixBase< Real >::GroupMax(), and KALDI_LOG.

573  {
574  BaseFloat time_in_secs = 0.025;
575  int32 group_size = 4;
576  CuMatrix<Real> M(dim, dim), N(dim, dim / group_size);
577  M.SetRandn();
578  Timer tim;
579  int32 iter = 0;
580  for (;tim.Elapsed() < time_in_secs; iter++)
581  N.GroupMax(M);
582 
583  BaseFloat fdim = dim;
584  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
585  KALDI_LOG << "For CuMatrix::GroupMax" << NameOf<Real>() << ", for dim = "
586  << dim << ", speed was " << gflops << " gigaflops.";
587 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixGroupMaxAllGroupSizes()

void kaldi::TestCuMatrixGroupMaxAllGroupSizes ( int32  dim)

Definition at line 589 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), CuMatrixBase< Real >::GroupMax(), KALDI_LOG, kUndefined, and CuMatrixBase< Real >::SetRandn().

589  {
590  BaseFloat time_in_secs = 0.025;
591  CuMatrix<Real> M(dim, dim);
592  M.SetRandn();
593  Timer tim;
594  int32 iter = 0;
595  for (; tim.Elapsed() < time_in_secs;) {
596  for (int group_size = 1; group_size <= dim; group_size++) {
597  if (dim % group_size == 0) {
598  CuMatrix<Real> N(dim, dim / group_size, kUndefined);
599  N.GroupMax(M);
600  iter++;
601  }
602  }
603  }
604 
605  BaseFloat fdim = dim;
606  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
607  KALDI_LOG << "For CuMatrix::GroupMax (all group sizes)" << NameOf<Real>()
608  << ", for dim = " << dim << ", speed was " << gflops
609  << " gigaflops.";
610 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixGroupMaxDeriv()

void kaldi::TestCuMatrixGroupMaxDeriv ( int32  dim)

Definition at line 612 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), CuMatrixBase< Real >::GroupMaxDeriv(), and KALDI_LOG.

612  {
613  BaseFloat time_in_secs = 0.025;
614  int32 group_size = 4;
615  CuMatrix<Real> M(dim, dim), N(dim, dim / group_size), O(dim, dim);
616  M.SetRandn();
617  N.GroupMax(M);
618  Timer tim;
619  int32 iter = 0;
620 
621  for (;tim.Elapsed() < time_in_secs; iter++)
622  O.GroupMaxDeriv(M, N);
623 
624  BaseFloat fdim = dim;
625  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
626  KALDI_LOG << "For CuMatrix::GroupMaxDeriv" << NameOf<Real>() << ", for dim = "
627  << dim << ", speed was " << gflops << " gigaflops.";
628 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixGroupPnorm()

void kaldi::TestCuMatrixGroupPnorm ( int32  dim)

Definition at line 536 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), CuMatrixBase< Real >::GroupPnorm(), and KALDI_LOG.

536  {
537  BaseFloat time_in_secs = 0.025;
538  int32 group_size = 4;
539  CuMatrix<Real> M(dim, dim), N(dim, dim / group_size);
540  M.SetRandn();
541  Timer tim;
542  int32 iter = 0;
543  for (;tim.Elapsed() < time_in_secs; iter++)
544  N.GroupPnorm(M, 2.0);
545 
546  BaseFloat fdim = dim;
547  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
548  KALDI_LOG << "For CuMatrix::GroupPnorm" << NameOf<Real>() << ", for dim = "
549  << dim << ", speed was " << gflops << " gigaflops.";
550 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixHeaviside()

void kaldi::TestCuMatrixHeaviside ( int32  dim)

Definition at line 427 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::ApplyHeaviside(), Timer::Elapsed(), KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

427  {
428  BaseFloat time_in_secs = 0.025;
429  CuMatrix<Real> M(dim, dim), N(dim, dim);
430  M.SetRandn();
431  N.SetRandn();
432  Timer tim;
433  int32 iter = 0;
434  for (;tim.Elapsed() < time_in_secs; iter++) {
435  N.ApplyHeaviside();
436  }
437 
438  BaseFloat fdim = dim;
439  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
440  KALDI_LOG << "For CuMatrix::Heaviside" << NameOf<Real>() << ", for dim = "
441  << dim << ", speed was " << gflops << " gigaflops.";
442 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixLogSoftmax()

void kaldi::TestCuMatrixLogSoftmax ( int32  dim)

Definition at line 518 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::LogSoftMaxPerRow(), and CuMatrixBase< Real >::SetRandn().

518  {
519  BaseFloat time_in_secs = 0.025;
520  CuMatrix<Real> M(dim, dim), N(dim, dim);
521  M.SetRandn();
522  N.SetRandn();
523  Timer tim;
524  int32 iter = 0;
525  for (;tim.Elapsed() < time_in_secs; iter++) {
526  N.LogSoftMaxPerRow(M);
527  }
528 
529  BaseFloat fdim = dim;
530  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
531  KALDI_LOG << "For CuMatrix::LogSoftmax" << NameOf<Real>() << ", for dim = "
532  << dim << ", speed was " << gflops << " gigaflops.";
533 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixLookup()

void kaldi::TestCuMatrixLookup ( int32  dim)

Definition at line 782 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), Int32Pair::first, rnnlm::j, KALDI_LOG, CuMatrixBase< Real >::Lookup(), Rand(), Int32Pair::second, and CuMatrixBase< Real >::SetRandn().

782  {
783  BaseFloat time_in_secs = 0.025;
784  int32 dimM = dim, dimN = dim;
785  CuMatrix<Real> H(dimM, dimN);
786  H.SetRandn();
787  std::vector<Int32Pair> indices;
788  std::vector<Real> reference;
789  std::vector<Real> output;
790  // Generates the indices and the reference.
791  int32 num_index = dim * dim;
792  output.resize(num_index);
793  for (int32 j = 0; j < num_index; j++) {
794  MatrixIndexT r = Rand() % dimM;
795  MatrixIndexT c = Rand() % dimN;
796 
797  Int32Pair tmp_pair;
798  tmp_pair.first = r;
799  tmp_pair.second = c;
800  indices.push_back(tmp_pair);
801  reference.push_back(H(r, c));
802  }
803  Timer tim;
804  int32 iter = 0;
805  for (; tim.Elapsed()< time_in_secs; iter++)
806  H.Lookup(indices, &(output[0]));
807 
808  BaseFloat fdim = dim;
809  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
810  KALDI_LOG << "For CuMatrix::Lookup" << NameOf<Real>() << ", for dim = "
811  << dim << ", speed was " << gflops << " gigaflops.";
812 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
int32_cuda second
Definition: cu-matrixdim.h:80
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32_cuda first
Definition: cu-matrixdim.h:79

◆ TestCuMatrixMatMat()

void kaldi::TestCuMatrixMatMat ( int32  dim)

Definition at line 212 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::AddMatMat(), Timer::Elapsed(), KALDI_LOG, and kNoTrans.

212  {
213  BaseFloat time_in_secs = 0.025;
214  CuMatrix<Real> M(dim, dim), N(dim, dim), O(dim, dim);
215  M.SetRandn();
216  N.SetRandn();
217  Timer tim;
218  int32 iter = 0;
219  for (;tim.Elapsed() < time_in_secs; iter++) {
220  O.AddMatMat(1.0, M, kNoTrans, N, kNoTrans, 0.0);
221  }
222 
223  BaseFloat fdim = dim;
224  BaseFloat gflops = (fdim * fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
225  KALDI_LOG << "For CuMatrix::AddMatMat" << NameOf<Real>() << ", for dim = "
226  << dim << ", speed was " << gflops << " gigaflops.";
227 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixMatMatBatched()

void kaldi::TestCuMatrixMatMatBatched ( int32  dim,
int32  batchCount 
)

Definition at line 229 of file cu-matrix-speed-test.cc.

References AddMatMatBatched(), Timer::Elapsed(), rnnlm::i, KALDI_LOG, kNoTrans, and CuMatrixBase< Real >::SetRandn().

229  {
230  std::vector<CuMatrix<Real>* > a(batchCount), b(batchCount), c(batchCount);
231  std::vector<CuSubMatrix<Real>* > A, B, C;
232 
233  for (int32 i = 0; i < batchCount; i++) {
234  // first create a Matrix intance and then creat a SubMatrix instance from that
235  a[i] = new CuMatrix<Real>(dim, dim);
236  b[i] = new CuMatrix<Real>(dim, dim);
237  c[i] = new CuMatrix<Real>(dim, dim);
238  a[i]->SetRandn();
239  b[i]->SetRandn();
240  A.push_back(new CuSubMatrix<Real>(*(a[i]), 0, a[i]->NumRows(), 0,
241  a[i]->NumCols()));
242  B.push_back(new CuSubMatrix<Real>(*(b[i]), 0, b[i]->NumRows(), 0,
243  b[i]->NumCols()));
244  C.push_back(new CuSubMatrix<Real>(*(c[i]), 0, c[i]->NumRows(), 0,
245  c[i]->NumCols()));
246  }
247  BaseFloat time_in_secs = 0.025;
248  Timer tim;
249  int32 iter = 0;
250  for (;tim.Elapsed() < time_in_secs; iter++) {
251  AddMatMatBatched(static_cast<Real>(1.0), C, A, kNoTrans, B, kNoTrans,
252  static_cast<Real>(0.0));
253  }
254  for (int32 i = 0; i< batchCount; i++) {
255  delete a[i]; delete b[i]; delete c[i];
256  delete A[i]; delete B[i]; delete C[i];
257  }
258 
259  BaseFloat fdim = dim;
260  BaseFloat gflops = (fdim * fdim * fdim * iter * batchCount) / (tim.Elapsed() * 1.0e+09);
261  KALDI_LOG << "For CuMatrix::AddMatMatBatched" << NameOf<Real>() << ", for dim = " << dim
262  << ", batchSize = " << batchCount << ", speed was " << gflops << " gigaflops.";
263 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
void AddMatMatBatched(const Real alpha, std::vector< CuSubMatrix< Real > * > &C, const std::vector< CuSubMatrix< Real > * > &A, MatrixTransposeType transA, const std::vector< CuSubMatrix< Real > * > &B, MatrixTransposeType transB, const Real beta)
Does multiple matrix multiplications, executing them in parallel using cuBLAS&#39;s gemmBatched if we are...
Definition: cu-matrix.cc:2207
float BaseFloat
Definition: kaldi-types.h:29
This class is used for a piece of a CuMatrix.
Definition: matrix-common.h:70
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixMax()

void kaldi::TestCuMatrixMax ( int32  dim)

Definition at line 63 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::Max(), and CuMatrixBase< Real >::SetRandn().

63  {
64  BaseFloat time_in_secs = 0.025;
65  CuMatrix<Real> M(dim, dim);
66  M.SetRandn();
67 
68  Timer tim;
69  int32 iter = 0;
70  Real result = 0;
71  for (; tim.Elapsed() < time_in_secs; iter++) {
72  result = M.Max();
73  }
74  BaseFloat fdim = dim;
75  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
76  KALDI_LOG<< "For CuMatrix::TestCuMatrixMax" << NameOf<Real>() << ", for dim = "
77  << dim << ", speed was " << gflops << " gigaflops, result = " << result;
78 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixMin()

void kaldi::TestCuMatrixMin ( int32  dim)

Definition at line 80 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::Min(), and CuMatrixBase< Real >::SetRandn().

80  {
81  BaseFloat time_in_secs = 0.025;
82  CuMatrix<Real> M(dim, dim);
83  M.SetRandn();
84 
85  Timer tim;
86  int32 iter = 0;
87  Real result = 0;
88  for (; tim.Elapsed() < time_in_secs; iter++) {
89  result = M.Min();
90  }
91  BaseFloat fdim = dim;
92  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
93  KALDI_LOG<< "For CuMatrix::TestCuMatrixMin" << NameOf<Real>() << ", for dim = "
94  << dim << ", speed was " << gflops << " gigaflops, result = " << result;
95 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixMulRowsGroupMat()

void kaldi::TestCuMatrixMulRowsGroupMat ( int32  dim)

Definition at line 445 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, and CuMatrixBase< Real >::SetRandn().

445  {
446  BaseFloat time_in_secs = 0.025;
447 
448  int32 group_size = 5;
449  CuMatrix<Real> M(dim, dim * group_size), N(dim, dim);
450  M.SetRandn();
451  N.SetRandn();
452  Timer tim;
453  int32 iter = 0;
454  for (;tim.Elapsed() < time_in_secs; iter++) {
455  M.MulRowsGroupMat(N);
456  }
457 
458  BaseFloat fdim = dim;
459  BaseFloat gflops = (fdim * fdim * group_size * iter) / (tim.Elapsed() * 1.0e+09);
460  KALDI_LOG << "For CuMatrix::MulRowsGroupMat" << NameOf<Real>() << ", for dim = "
461  << dim << ", speed was " << gflops << " gigaflops.";
462 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixResize()

void TestCuMatrixResize ( int32  size_multiple)

Definition at line 41 of file cu-device-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, kUndefined, and RandInt().

Referenced by TestCuMatrixCopyUpperToLower().

41  {
42  int32 num_matrices = 256;
43  BaseFloat time_in_secs = 0.2;
44 
45  std::vector<std::pair<int32, int32> > sizes(num_matrices);
46 
47  for (int32 i = 0; i < num_matrices; i++) {
48  int32 num_rows = RandInt(1, 10);
49  num_rows *= num_rows;
50  num_rows *= size_multiple;
51  int32 num_cols = RandInt(1, 10);
52  num_cols *= num_cols;
53  num_cols *= size_multiple;
54  sizes[i].first = num_rows;
55  sizes[i].second = num_rows;
56  }
57 
58  std::vector<CuMatrix<BaseFloat> > matrices(num_matrices);
59 
60  Timer tim;
61  size_t num_floats_processed = 0;
62  for (;tim.Elapsed() < time_in_secs; ) {
63  int32 matrix = RandInt(0, num_matrices - 1);
64  if (matrices[matrix].NumRows() == 0) {
65  int32 num_rows = sizes[matrix].first,
66  num_cols = sizes[matrix].second;
67  matrices[matrix].Resize(num_rows, num_cols, kUndefined);
68  num_floats_processed += num_rows * num_cols;
69  } else {
70  matrices[matrix].Resize(0, 0);
71  }
72  }
73 
74  BaseFloat gflops = num_floats_processed / (tim.Elapsed() * 1.0e+09);
75 
76  KALDI_LOG << "For CuMatrix::Resize" << NameOf<Real>() << ", for size_multiple = "
77  << size_multiple << ", speed was " << gflops << " gigaflops.";
78 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestCuMatrixSetZeroAboveDiag()

void kaldi::TestCuMatrixSetZeroAboveDiag ( int32  dim)

Definition at line 767 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetZeroAboveDiag().

767  {
768  BaseFloat time_in_secs = 0.025;
769  CuMatrix<Real> M(dim, dim);
770  M.SetRandn();
771  Timer tim;
772  int32 iter = 0;
773  for (; tim.Elapsed() < time_in_secs; iter++)
774  M.SetZeroAboveDiag();
775  BaseFloat fdim = dim;
776  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
777  KALDI_LOG << "For CuMatrix::SetZeroAboveDiag" << NameOf<Real>() << ", for dim = "
778  << dim << ", speed was " << gflops << " gigaflops.";
779 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixSigmoid()

void kaldi::TestCuMatrixSigmoid ( int32  dim)

Definition at line 410 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::Sigmoid().

410  {
411  BaseFloat time_in_secs = 0.025;
412  CuMatrix<Real> M(dim, dim), N(dim, dim);
413  M.SetRandn();
414  N.SetRandn();
415  Timer tim;
416  int32 iter = 0;
417  for (;tim.Elapsed() < time_in_secs; iter++) {
418  N.Sigmoid(M);
419  }
420 
421  BaseFloat fdim = dim;
422  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
423  KALDI_LOG << "For CuMatrix::Sigmoid" << NameOf<Real>() << ", for dim = "
424  << dim << ", speed was " << gflops << " gigaflops.";
425 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixSoftmax()

void kaldi::TestCuMatrixSoftmax ( int32  dim)

Definition at line 500 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SoftMaxPerRow().

500  {
501  BaseFloat time_in_secs = 0.025;
502  CuMatrix<Real> M(dim, dim), N(dim, dim);
503  M.SetRandn();
504  N.SetRandn();
505  Timer tim;
506  int32 iter = 0;
507  for (;tim.Elapsed() < time_in_secs; iter++) {
508  N.SoftMaxPerRow(M);
509  }
510 
511  BaseFloat fdim = dim;
512  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
513  KALDI_LOG << "For CuMatrix::Softmax" << NameOf<Real>() << ", for dim = "
514  << dim << ", speed was " << gflops << " gigaflops.";
515 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixSum()

void kaldi::TestCuMatrixSum ( int32  dim)

Definition at line 46 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::Sum().

46  {
47  BaseFloat time_in_secs = 0.025;
48  CuMatrix<Real> M(dim, dim);
49  M.SetRandn();
50 
51  Timer tim;
52  int32 iter = 0;
53  Real result = 0;
54  for (; tim.Elapsed() < time_in_secs; iter++) {
55  result = M.Sum();
56  }
57  BaseFloat fdim = dim;
58  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
59  KALDI_LOG<< "For CuMatrix::TestCuMatrixSum" << NameOf<Real>() << ", for dim = "
60  << dim << ", speed was " << gflops << " gigaflops, result = " << result;
61 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixTraceMatMat()

void kaldi::TestCuMatrixTraceMatMat ( int32  dim)

Definition at line 630 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, kNoTrans, kTrans, rnnlm::n, CuMatrixBase< Real >::SetRandn(), and TraceMatMat().

630  {
631  for (int32 n = 0; n < 2; n++) {
632  MatrixTransposeType trans = (n == 0 ? kNoTrans : kTrans);
633  BaseFloat time_in_secs = 0.02;
634 
635  CuMatrix<Real> M(dim, dim), N(dim, dim);
636  M.SetRandn();
637  N.SetRandn();
638  Timer tim;
639  int32 iter = 0;
640  for (;tim.Elapsed() < time_in_secs; iter++) {
641  TraceMatMat(M, N, trans);
642  }
643  BaseFloat fdim = dim;
644  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
645  KALDI_LOG << "For CuMatrix::TraceMatMat" << NameOf<Real>()
646  << (trans == kTrans ? " [transposed]" : "") << ", for dim = "
647  << dim << ", speed was " << gflops << " gigaflops.";
648  }
649 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
MatrixTransposeType
Definition: matrix-common.h:32
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixTransposeCross()

void kaldi::TestCuMatrixTransposeCross ( int32  dim)

Definition at line 148 of file cu-matrix-speed-test.cc.

References AssertEqual(), CuMatrixBase< Real >::CopyFromMat(), Timer::Elapsed(), KALDI_LOG, and kTrans.

148  {
149  BaseFloat time_in_secs = 0.025;
150  CuMatrix<float> Mf(dim / 2, dim), ref(dim, dim / 2);
151  CuMatrix<Real> Md(dim, dim / 2);
152  Mf.SetRandn();
153  ref = Mf;
154 
155  Timer tim;
156  int32 iter = 0;
157  for (; tim.Elapsed() < time_in_secs; iter++) {
158  Md.CopyFromMat(Mf, kTrans);
159  Mf.CopyFromMat(Md, kTrans);
160  }
161  BaseFloat fdim = dim;
162  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
163  KALDI_LOG<< "For CuMatrix::TransposeCross" << NameOf<Real>() << ", for dim = "
164  << dim << ", speed was " << gflops << " gigaflops.";
165 
166  AssertEqual(ref, Mf);
167 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixTransposeNS()

void kaldi::TestCuMatrixTransposeNS ( int32  dim)

Definition at line 116 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::SetRandn(), and CuMatrix< Real >::Transpose().

116  {
117  BaseFloat time_in_secs = 0.025;
118  CuMatrix<Real> M(dim, dim / 2);
119  M.SetRandn();
120 
121  Timer tim;
122  int32 iter = 0;
123  for (; tim.Elapsed() < time_in_secs; iter++) {
124  M.Transpose();
125  }
126  BaseFloat fdim = dim;
127  BaseFloat gflops = (fdim * fdim * iter / 2) / (tim.Elapsed() * 1.0e+09);
128  KALDI_LOG<< "For CuMatrix::TransposeNS" << NameOf<Real>() << ", for dim = "
129  << dim << ", speed was " << gflops << " gigaflops.";
130 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuMatrixTransposeS()

void kaldi::TestCuMatrixTransposeS ( int32  dim)

Definition at line 132 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuMatrixBase< Real >::SetRandn(), and CuMatrix< Real >::Transpose().

132  {
133  BaseFloat time_in_secs = 0.025;
134  CuMatrix<Real> M(dim, dim);
135  M.SetRandn();
136 
137  Timer tim;
138  int32 iter = 0;
139  for (; tim.Elapsed() < time_in_secs; iter++) {
140  M.Transpose();
141  }
142  BaseFloat fdim = dim;
143  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
144  KALDI_LOG<< "For CuMatrix::TransposeS" << NameOf<Real>() << ", for dim = "
145  << dim << ", speed was " << gflops << " gigaflops.";
146 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuSparseMatrixTraceMatSmat()

void kaldi::TestCuSparseMatrixTraceMatSmat ( int32  dim)

Definition at line 983 of file cu-matrix-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, kNoTrans, kTrans, rnnlm::n, Rand(), CuMatrixBase< Real >::SetRandn(), and TraceMatSmat().

983  {
984  for (int32 n = 0; n < 2; n++) {
985  MatrixTransposeType trans = (n == 0 ? kNoTrans : kTrans);
986  BaseFloat time_in_secs = 0.02;
987 
988  CuMatrix<Real> M(dim, dim);
989  M.SetRandn();
990 
991  std::vector<std::vector<std::pair<MatrixIndexT, Real> > > pairs(dim);
992  for (auto && row : pairs) {
993  row.push_back( { MatrixIndexT(Rand() % dim), Real(Rand() % dim) });
994  }
995  SparseMatrix<Real> Ncpu(dim, pairs);
996  CuSparseMatrix<Real> N(Ncpu);
997 
998  Timer tim;
999  int32 iter = 0;
1000  for (;tim.Elapsed() < time_in_secs; iter++) {
1001  TraceMatSmat(M, N, trans);
1002  }
1003  BaseFloat fdim = dim;
1004  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
1005  KALDI_LOG << "For CuSparseMatrix::TraceMatSmat" << NameOf<Real>()
1006  << (trans == kTrans ? " [transposed]" : "") << ", for dim = "
1007  << dim << ", speed was " << gflops << " gigaflops.";
1008  }
1009 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
MatrixTransposeType
Definition: matrix-common.h:32
Real TraceMatSmat(const MatrixBase< Real > &A, const SparseMatrix< Real > &B, MatrixTransposeType trans)
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorAddColSumMat()

void kaldi::TestCuVectorAddColSumMat ( int32  dim,
MatrixTransposeType  trans 
)

Definition at line 266 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::AddColSumMat(), Timer::Elapsed(), KALDI_LOG, kTrans, CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

266  {
267  BaseFloat time_in_secs = 0.02;
268  CuVector<Real> v(dim);
269  v.SetRandn();
270  CuMatrix<Real> N(dim, dim);
271  N.SetRandn();
272 
273  Timer tim;
274  int32 iter = 0;
275 
276  for (;tim.Elapsed() < time_in_secs; iter++) {
277  v.AddColSumMat(1.0, N, 0.5);
278  }
279 
280  BaseFloat fdim = dim;
281  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
282  KALDI_LOG << "For CuVector::AddColSumMat" << NameOf<Real>()
283  << (trans == kTrans ? "[trans]" : "[no-trans]") << ", for dim = "
284  << dim << ", speed was " << gflops << " gigaflops.";
285 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorAddDiagMat2()

void kaldi::TestCuVectorAddDiagMat2 ( int32  dim,
MatrixTransposeType  trans 
)

Definition at line 222 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::AddDiagMat2(), Timer::Elapsed(), KALDI_LOG, kTrans, CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

222  {
223  BaseFloat time_in_secs = 0.02;
224  CuVector<Real> v(dim);
225  v.SetRandn();
226  CuMatrix<Real> N(dim, dim);
227  N.SetRandn();
228 
229  Timer tim;
230  int32 iter = 0;
231 
232  for (;tim.Elapsed() < time_in_secs; iter++) {
233  v.AddDiagMat2(1.0, N, trans, 0.0);
234  }
235 
236  BaseFloat fdim = dim;
237  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
238  KALDI_LOG << "For CuVector::AddDiagMat2" << NameOf<Real>()
239  << (trans == kTrans ? "[trans]" : "[no-trans]") << ", for dim = "
240  << dim << ", speed was " << gflops << " gigaflops.";
241 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorAddDiagMat2OnVariousShapes()

void kaldi::TestCuVectorAddDiagMat2OnVariousShapes ( int32  dim,
MatrixTransposeType  trans 
)

Definition at line 196 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::AddDiagMat2(), Timer::Elapsed(), KALDI_LOG, kNoTrans, kTrans, CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

197  {
198  BaseFloat time_in_secs = 0.02;
199  int32 size = 1024 * 32;
200  CuVector<Real> v(trans == kNoTrans ? size / dim : dim);
201  v.SetRandn();
202  CuMatrix<Real> N(size / dim, dim);
203  N.SetRandn();
204 
205  Timer tim;
206  int32 iter = 0;
207 
208  for (; tim.Elapsed() < time_in_secs; iter++) {
209  v.AddDiagMat2(1.0, N, trans, 0.0);
210  }
211 
212  BaseFloat fdim = size;
213  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
214  KALDI_LOG << "For CuVector::AddDiagMat2Shapes" << NameOf<Real>()
215  << (trans == kTrans ? "[trans]" : "[no-trans]") << ", for dim = ("
216  << size / dim << ", " << dim << "), speed was " << gflops
217  << " gigaflops.";
218 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorAddDiagMatMat()

void kaldi::TestCuVectorAddDiagMatMat ( int32  dim,
MatrixTransposeType  transN,
MatrixTransposeType  transO 
)

Definition at line 170 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::AddDiagMatMat(), Timer::Elapsed(), KALDI_LOG, kNoTrans, CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

172  {
173  BaseFloat time_in_secs = 0.02;
174  CuVector<Real> v(dim);
175  v.SetRandn();
176  CuMatrix<Real> N(dim, dim), O(dim, dim);
177  N.SetRandn();
178  O.SetRandn();
179 
180  Timer tim;
181  int32 iter = 0;
182 
183  for (;tim.Elapsed() < time_in_secs; iter++) {
184  v.AddDiagMatMat(1.0, N, transN, O, transO, 1.0);
185  }
186 
187  BaseFloat fdim = dim;
188  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
189  KALDI_LOG << "For CuVector::AddDiagMatMat" << NameOf<Real>()
190  << (transN == kNoTrans ? "[no-trans],":"[trans],")
191  << (transO == kNoTrans ? "[no-trans],":"[trans],")
192  << " for dim = "<< dim << ", speed was " << gflops << " gigaflops.";
193 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorAddDiagMatMatShape()

void kaldi::TestCuVectorAddDiagMatMatShape ( int32  num_rows,
int32  num_cols,
MatrixTransposeType  transM,
MatrixTransposeType  transN 
)

Definition at line 372 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::AddDiagMatMat(), Timer::Elapsed(), KALDI_LOG, kNoTrans, kTrans, CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

374  {
375  BaseFloat time_in_secs = 0.02;
376  CuVector<Real> v(transM == kTrans ? num_cols : num_rows);
377  v.SetRandn();
378  CuMatrix<Real> M(num_rows, num_cols);
379  CuMatrix<Real> N(transM != transN ? num_rows : num_cols,
380  transM != transN ? num_cols : num_rows);
381  M.SetRandn();
382  N.SetRandn();
383 
384  Timer tim;
385  int32 iter = 0;
386 
387  for (;tim.Elapsed() < time_in_secs; iter++) {
388  v.AddDiagMatMat(1.0, M, transM, N, transN, 1.0);
389  }
390 
391  BaseFloat fnr = num_rows;
392  BaseFloat fnc = num_cols;
393  BaseFloat gflops = (fnr * fnc * iter) / (tim.Elapsed() * 1.0e+09);
394  KALDI_LOG << "For CuVector::AddDiagMatMat" << NameOf<Real>()
395  << (transM == kNoTrans ? "[no-trans],":"[trans],")
396  << (transN == kNoTrans ? "[no-trans],":"[trans],")
397  << " for dim = "<< num_rows << ", " << num_cols
398  << ", speed was " << gflops << " gigaflops.";
399 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorAddRowSumMat()

void kaldi::TestCuVectorAddRowSumMat ( int32  dim,
MatrixTransposeType  trans 
)

Definition at line 244 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::AddRowSumMat(), Timer::Elapsed(), KALDI_LOG, kTrans, CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

244  {
245  BaseFloat time_in_secs = 0.02;
246  CuVector<Real> v(dim);
247  v.SetRandn();
248  CuMatrix<Real> N(dim, dim);
249  N.SetRandn();
250 
251  Timer tim;
252  int32 iter = 0;
253 
254  for (;tim.Elapsed() < time_in_secs; iter++) {
255  v.AddRowSumMat(1.0, N, 0.5);
256  }
257 
258  BaseFloat fdim = dim;
259  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
260  KALDI_LOG << "For CuVector::AddRowSumMat" << NameOf<Real>()
261  << (trans == kTrans ? "[trans]" : "[no-trans]") << ", for dim = "
262  << dim << ", speed was " << gflops << " gigaflops.";
263 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorApplyCeiling()

void kaldi::TestCuVectorApplyCeiling ( int32  dim)

Definition at line 330 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::ApplyCeiling(), Timer::Elapsed(), KALDI_LOG, RandInt(), and CuVectorBase< Real >::SetRandn().

330  {
331  BaseFloat time_in_secs = 0.02;
332  CuVector<Real> v(dim);
333  v.SetRandn();
334  Real threshold = RandInt(-35000, 35000) / Real(100);
335 
336  Timer tim;
337  int32 iter = 0;
338  for (;tim.Elapsed() < time_in_secs; iter++) {
339  MatrixIndexT dummy_count;
340  v.ApplyCeiling(threshold, &dummy_count);
341  }
342 
343  BaseFloat fdim = dim;
344  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
345  KALDI_LOG << "For CuVector::ApplyCeiling" << NameOf<Real>() << ", for dim = "
346  << dim << ", speed was " << gflops << " gigaflops.";
347 
348 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestCuVectorApplyCeilingNoCount()

void kaldi::TestCuVectorApplyCeilingNoCount ( int32  dim)

Definition at line 351 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::ApplyCeiling(), Timer::Elapsed(), KALDI_LOG, RandInt(), and CuVectorBase< Real >::SetRandn().

351  {
352  BaseFloat time_in_secs = 0.02;
353  CuVector<Real> v(dim);
354  v.SetRandn();
355  Real threshold = RandInt(-35000, 35000) / Real(100);
356 
357  Timer tim;
358  int32 iter = 0;
359  for (;tim.Elapsed() < time_in_secs; iter++) {
360  v.ApplyCeiling(threshold, nullptr);
361  }
362 
363  BaseFloat fdim = dim;
364  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
365  KALDI_LOG << "For CuVector::ApplyCeiling (no count variety)" << NameOf<Real>()
366  << ", for dim = " << dim << ", speed was " << gflops
367  << " gigaflops.";
368 
369 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestCuVectorApplyFloor()

void kaldi::TestCuVectorApplyFloor ( int32  dim)

Definition at line 288 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::ApplyFloor(), Timer::Elapsed(), KALDI_LOG, RandInt(), and CuVectorBase< Real >::SetRandn().

288  {
289  BaseFloat time_in_secs = 0.02;
290  CuVector<Real> v(dim);
291  v.SetRandn();
292  Real threshold = RandInt(-35000, 35000) / Real(100);
293 
294  Timer tim;
295  int32 iter = 0;
296  for (;tim.Elapsed() < time_in_secs; iter++) {
297  MatrixIndexT dummy_count;
298  v.ApplyFloor(threshold, &dummy_count);
299  }
300 
301  BaseFloat fdim = dim;
302  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
303  KALDI_LOG << "For CuVector::ApplyFloor" << NameOf<Real>() << ", for dim = "
304  << dim << ", speed was " << gflops << " gigaflops.";
305 
306 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestCuVectorApplyFloorNoCount()

void kaldi::TestCuVectorApplyFloorNoCount ( int32  dim)

Definition at line 309 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::ApplyFloor(), Timer::Elapsed(), KALDI_LOG, RandInt(), and CuVectorBase< Real >::SetRandn().

309  {
310  BaseFloat time_in_secs = 0.02;
311  CuVector<Real> v(dim);
312  v.SetRandn();
313  Real threshold = RandInt(-35000, 35000) / Real(100);
314 
315  Timer tim;
316  int32 iter = 0;
317  for (;tim.Elapsed() < time_in_secs; iter++) {
318  v.ApplyFloor(threshold, nullptr);
319  }
320 
321  BaseFloat fdim = dim;
322  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
323  KALDI_LOG << "For CuVector::ApplyFloor (no count variety)" << NameOf<Real>()
324  << ", for dim = " << dim << ", speed was " << gflops
325  << " gigaflops.";
326 
327 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestCuVectorCopyFromVec()

void kaldi::TestCuVectorCopyFromVec ( int32  dim)

Definition at line 79 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::CopyFromVec(), CU1DBLOCK, CuVectorBase< Real >::Data(), CuVectorBase< Real >::Dim(), Timer::Elapsed(), KALDI_LOG, kUndefined, CuVectorBase< Real >::SetRandn(), and VectorBase< Real >::Sum().

79  {
80  BaseFloat time_in_secs = 0.02;
81  CuVector<Real> M(dim);
82  M.SetRandn();
83 
84  Timer tim;
85  int32 iter = 0;
86  for (;tim.Elapsed() < time_in_secs; iter++) {
87  CuVector<OtherReal> v(dim);
88  v.CopyFromVec(M);
89  }
90 
91  BaseFloat fdim = dim;
92  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
93  KALDI_LOG << "For CuVector::CopyFromVec" << NameOf<Real>() << " to "
94  << NameOf<OtherReal>() << ", for dim = "
95  << dim << ", speed was " << gflops << " gigaflops.";
96 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorSoftmax()

void kaldi::TestCuVectorSoftmax ( int32  dim)

Definition at line 44 of file cu-vector-speed-test.cc.

References CuVectorBase< Real >::ApplySoftMax(), Timer::Elapsed(), KALDI_LOG, and CuVectorBase< Real >::SetRandn().

44  {
45  BaseFloat time_in_secs = 0.02;
46  CuVector<Real> M(dim);
47  M.SetRandn();
48 
49  Timer tim;
50  int32 iter = 0;
51  for (;tim.Elapsed() < time_in_secs; iter++) {
52  M.ApplySoftMax();
53  }
54 
55  BaseFloat fdim = dim;
56  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
57  KALDI_LOG << "For CuVector::Softmax" << NameOf<Real>() << ", for dim = "
58  << dim << ", speed was " << gflops << " gigaflops.";
59 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorSum()

void kaldi::TestCuVectorSum ( int32  dim)

Definition at line 62 of file cu-vector-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuVectorBase< Real >::SetRandn(), and CuVectorBase< Real >::Sum().

62  {
63  BaseFloat time_in_secs = 0.02;
64  CuVector<Real> M(dim);
65  M.SetRandn();
66 
67  Timer tim;
68  int32 iter = 0;
69  for (;tim.Elapsed() < time_in_secs; iter++) {
70  M.Sum();
71  }
72 
73  BaseFloat fdim = dim;
74  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
75  KALDI_LOG << "For CuVector::Sum" << NameOf<Real>() << ", for dim = "
76  << dim << ", speed was " << gflops << " gigaflops.";
77 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestCuVectorVecVecOne()

void kaldi::TestCuVectorVecVecOne ( int32  dim)

Definition at line 148 of file cu-vector-speed-test.cc.

References Timer::Elapsed(), KALDI_LOG, CuVectorBase< Real >::Set(), CuVectorBase< Real >::SetRandn(), and VecVec().

148  {
149  BaseFloat time_in_secs = 0.02;
150  CuVector<Real> M(dim);
151  M.SetRandn();
152 
153  Timer tim;
154  int32 iter = 0;
155  for (;tim.Elapsed() < time_in_secs; iter++) {
156  CuVector<Real> ones(dim);
157  ones.Set(1.0);
158  VecVec(M, ones);
159  }
160 
161  BaseFloat fdim = dim;
162  BaseFloat gflops = (fdim * iter) / (tim.Elapsed() * 1.0e+09);
163  KALDI_LOG << "For CuVector::VecVecOne" << NameOf<Real>() << ", for dim = "
164  << dim << ", speed was " << gflops << " gigaflops.";
165 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestDistance()

static void kaldi::TestDistance ( )
static

Definition at line 117 of file cluster-utils-test.cc.

References AssertEqual(), and ScalarClusterable::Objf().

Referenced by main().

117  {
118  ScalarClusterable a(1.0), b(2.5);
119  AssertEqual(a.Objf(), 0.0);
120  AssertEqual(b.Objf(), 0.0);
121  AssertEqual(a.ObjfPlus(b), -a.Distance(b)); // since distance is negated objf-change, and original objfs were zero.
122 } // end namespace kaldi
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
ScalarClusterable clusters scalars with x^2 loss.

◆ TestDoTableSplit()

void kaldi::TestDoTableSplit ( )

Definition at line 206 of file build-tree-utils-test.cc.

References DoTableSplit(), rnnlm::i, KALDI_ASSERT, EventMap::Lookup(), EventMap::Map(), RandInt(), and TrivialTree().

Referenced by main().

206  {
207  EventValueType numvals = 11;
208  for (size_t iter = 0;iter < 10;iter++) {
209  BuildTreeStatsType stats;
210  int32 nKeys = 3;
211  EventKeyType k = RandInt(-1, nKeys-2); // key we will split on.
212  std::set<EventValueType> all_vals;
213  for (size_t i = 0;i < 10;i++) {
214  EventType evec;
215  for (EventKeyType kk = -1;kk < nKeys-1;kk++) {
216  EventValueType v = RandInt(0, numvals);
217  if (kk == k) all_vals.insert(v);
218  evec.push_back(std::make_pair(kk, v));
219  }
220  stats.push_back(std::pair<EventType, Clusterable*>(evec, (Clusterable*) NULL));
221  }
222  int32 nleaves = 0;
223  EventMap *trivial_map = TrivialTree(&nleaves);
224 
225  EventMap *table_map = DoTableSplit(*trivial_map, k, stats, &nleaves);
226  KALDI_ASSERT(nleaves <= numvals);
227  for (size_t i = 0;i < 10;i++) {
228  size_t idx1 = RandInt(0, stats.size()-1), idx2 = RandInt(0, stats.size()-1);
229  EventAnswerType ans1;
230  table_map->Map(stats[idx1].first, &ans1);
231  EventAnswerType ans2;
232  table_map->Map(stats[idx2].first, &ans2);
233 
234  EventValueType val1, val2;
235  bool b = EventMap::Lookup(stats[idx1].first, k, &val1)
236  && EventMap::Lookup(stats[idx2].first, k, &val2);
237  KALDI_ASSERT(b);
238  KALDI_ASSERT(val1 >= 0 );
239  KALDI_ASSERT( (val1 == val2) == (ans1 == ans2) );
240  }
241  for (EventValueType i = 0;i < numvals+1;i++) {
242  if (all_vals.count(i) == 0) {
243  EventType v; v.push_back(std::make_pair(k, i));
244  EventAnswerType ans;
245  bool b = table_map->Map(v, &ans);
246  KALDI_ASSERT(!b); // check it maps stuff we never saw to undefined.
247  }
248  }
249  delete trivial_map;
250  delete table_map;
251  }
252 }
kaldi::int32 int32
virtual bool Map(const EventType &event, EventAnswerType *ans) const =0
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95
EventMap * DoTableSplit(const EventMap &orig, EventKeyType key, const BuildTreeStatsType &stats, int32 *num_leaves)
DoTableSplit does a complete split on this key (e.g.

◆ TestEditDistance()

void kaldi::TestEditDistance ( )

Definition at line 26 of file edit-distance-test.cc.

References KALDI_ASSERT, and LevenshteinEditDistance().

Referenced by main().

26  {
27  std::vector<int32> a;
28  std::vector<int32> b;
30 
31  a.push_back(1);
33 
34  b.push_back(1);
36 
37  b.push_back(2);
39 
40  a.push_back(2);
42 
43  a.push_back(3);
44  a.push_back(4);
45  b.push_back(4);
46 
48 
49  a.push_back(5);
50 
52 
53  b.push_back(6);
54 
56 
57  a.push_back(1);
58  b.push_back(1);
59 
61 
62  b.push_back(10);
63 
65 }
int32 LevenshteinEditDistance(const std::vector< T > &a, const std::vector< T > &b)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestEditDistance2()

void kaldi::TestEditDistance2 ( )

Definition at line 112 of file edit-distance-test.cc.

References KALDI_ASSERT, LevenshteinEditDistance(), Rand(), and swap().

Referenced by main().

112  {
113  std::vector<int32> hyp;
114  std::vector<int32> ref;
115  int32 ins, del, sub, total_cost;
116  // initialize hypothesis
117  hyp.push_back(1);
118  hyp.push_back(3);
119  hyp.push_back(4);
120  hyp.push_back(5);
121  // initialize reference
122  ref.push_back(2);
123  ref.push_back(3);
124  ref.push_back(4);
125  ref.push_back(5);
126  ref.push_back(6);
127  ref.push_back(7);
128  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
129  KALDI_ASSERT(total_cost == 3 && ins == 0 && del == 2 && sub == 1);
130 
131  std::swap(hyp, ref);
132  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
133  KALDI_ASSERT(total_cost == 3 && ins == 2 && del == 0 && sub == 1);
134 
135  hyp.clear();
136  ref.clear();
137  hyp.push_back(1);
138  ref.push_back(1);
139  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
140  KALDI_ASSERT(total_cost == 0 && ins+del+sub == 0);
141  hyp.push_back(2);
142  ref.push_back(3);
143  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
144  KALDI_ASSERT(total_cost == 1 && ins == 0 && del == 0 && sub == 1);
145  // randomized test
146  size_t num = 0;
147  for (; num < 1000; num ++) {
148  int32 hyp_len = Rand()%11;
149  int32 ref_len = Rand()%3;
150  hyp.resize(hyp_len);
151  ref.resize(ref_len);
152 
153  int32 index = 0;
154  for (; index < hyp_len; index ++)
155  hyp[index] = Rand()%4;
156  for (index = 0; index < ref_len; index ++)
157  ref[index] = Rand()%4;
158  // current version
159  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
160  // previous version
161  int32 total_cost2 = LevenshteinEditDistance(hyp, ref);
162  // verify both are the same
163  KALDI_ASSERT(total_cost == total_cost2);
164  KALDI_ASSERT(ins+del+sub == total_cost);
165  KALDI_ASSERT(del-ins == static_cast<int32>(ref.size() -hyp.size()));
166  }
167  return;
168 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
kaldi::int32 int32
int32 LevenshteinEditDistance(const std::vector< T > &a, const std::vector< T > &b)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestEditDistance2String()

void kaldi::TestEditDistance2String ( )

Definition at line 172 of file edit-distance-test.cc.

References KALDI_ASSERT, LevenshteinEditDistance(), Rand(), and swap().

Referenced by main().

172  {
173  std::vector<std::string> hyp;
174  std::vector<std::string> ref;
175  int32 ins, del, sub, total_cost;
176  // initialize hypothesis
177  hyp.push_back("1");
178  hyp.push_back("3");
179  hyp.push_back("4");
180  hyp.push_back("5");
181  // initialize reference
182  ref.push_back("2");
183  ref.push_back("3");
184  ref.push_back("4");
185  ref.push_back("5");
186  ref.push_back("6");
187  ref.push_back("7");
188  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
189  KALDI_ASSERT(total_cost == 3 && ins == 0 && del == 2 && sub == 1);
190 
191  std::swap(hyp, ref);
192  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
193  KALDI_ASSERT(total_cost == 3 && ins == 2 && del == 0 && sub == 1);
194 
195  hyp.clear();
196  ref.clear();
197  hyp.push_back("1");
198  ref.push_back("1");
199  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
200  KALDI_ASSERT(total_cost == 0 && ins+del+sub == 0);
201  hyp.push_back("2");
202  ref.push_back("3");
203  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
204  KALDI_ASSERT(total_cost == 1 && ins == 0 && del == 0 && sub == 1);
205  // randomized test
206  size_t num = 0;
207  for (; num < 1000; num ++) {
208  int32 hyp_len = Rand()%11;
209  int32 ref_len = Rand()%3;
210  hyp.resize(hyp_len);
211  ref.resize(ref_len);
212 
213  int32 index = 0;
214  for (; index < hyp_len; index ++)
215  hyp[index] = Rand()%4;
216  for (index = 0; index < ref_len; index ++)
217  ref[index] = Rand()%4;
218  // current version
219  total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
220  // previous version
221  int32 total_cost2 = LevenshteinEditDistance(hyp, ref);
222  // verify both are the same
223  KALDI_ASSERT(total_cost == total_cost2);
224  KALDI_ASSERT(ins+del+sub == total_cost);
225  KALDI_ASSERT(del-ins == static_cast<int32>(ref.size() -hyp.size()));
226  }
227  return;
228 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
kaldi::int32 int32
int32 LevenshteinEditDistance(const std::vector< T > &a, const std::vector< T > &b)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestEditDistanceString()

void kaldi::TestEditDistanceString ( )

Definition at line 68 of file edit-distance-test.cc.

References KALDI_ASSERT, and LevenshteinEditDistance().

Referenced by main().

68  {
69  std::vector<std::string> a;
70  std::vector<std::string> b;
72 
73  a.push_back("1");
75 
76  b.push_back("1");
78 
79  b.push_back("2");
81 
82  a.push_back("2");
84 
85  a.push_back("3");
86  a.push_back("4");
87  b.push_back("4");
88 
90 
91  a.push_back("5");
92 
94 
95  b.push_back("6");
96 
98 
99  a.push_back("1");
100  b.push_back("1");
101 
103 
104  b.push_back("10");
105 
107 }
int32 LevenshteinEditDistance(const std::vector< T > &a, const std::vector< T > &b)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestEnsureClusterableVectorNotNull()

static void kaldi::TestEnsureClusterableVectorNotNull ( )
static

Definition at line 147 of file cluster-utils-test.cc.

References DeletePointers(), EnsureClusterableVectorNotNull(), and KALDI_ASSERT.

Referenced by main().

147  {
148  ScalarClusterable a(1.0), b(2.5);
149  std::vector<Clusterable*> vec(4);
150  vec[1] = a.Copy(); vec[3] = a.Copy();
152  KALDI_ASSERT(vec[0] != NULL && vec[2] != NULL && vec[0]->Objf() == 0 && vec[2]->Objf() == 0 && vec[0] != vec[2] && vec[0] != vec[1]);
153  DeletePointers(&vec);
154 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
void EnsureClusterableVectorNotNull(std::vector< Clusterable *> *stats)
Fills in any (NULL) holes in "stats" vector, with empty stats, because certain algorithms require non...
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
ScalarClusterable clusters scalars with x^2 loss.

◆ TestEventMap()

void kaldi::TestEventMap ( )

Definition at line 27 of file event-map-test.cc.

References GetTreeStructure(), rnnlm::i, KALDI_ASSERT, TableEventMap::Map(), EventMap::MaxResult(), and Rand().

Referenced by main().

27  {
28  typedef EventKeyType KeyType;
29  typedef EventValueType ValueType;
30  typedef EventAnswerType AnswerType;
31 
32 
33  ConstantEventMap *C0a = new ConstantEventMap(0);
34  {
35  int32 num_leaves;
36  std::vector<int32> parents;
37  bool a = GetTreeStructure(*C0a, &num_leaves, &parents);
38  KALDI_ASSERT(a && parents.size() == 1 && parents[0] == 0);
39  }
40  ConstantEventMap *C1b = new ConstantEventMap(1);
41  {
42  int32 num_leaves;
43  std::vector<int32> parents;
44  bool a = GetTreeStructure(*C1b, &num_leaves, &parents);
45  KALDI_ASSERT(!a); // since C1b's leaves don't start from 0.
46  }
47 
48  std::vector<EventMap*> tvec;
49  tvec.push_back(C0a);
50  tvec.push_back(C1b);
51 
52  TableEventMap *T1 = new TableEventMap(1, tvec); // takes ownership of C0a, C1b
53  KALDI_ASSERT(T1->MaxResult() == 1);
54 
55  {
56  int32 num_leaves;
57  std::vector<int32> parents;
58  bool a = GetTreeStructure(*T1, &num_leaves, &parents);
59  KALDI_ASSERT(a && parents.size() == 3 && parents[0] == 2
60  && parents[1] == 2 && parents[2] == 2);
61  }
62 
63  ConstantEventMap *C0c = new ConstantEventMap(0);
64  ConstantEventMap *C1d = new ConstantEventMap(1);
65 
66  std::map<ValueType, EventMap*> tmap;
67  tmap[0] = C0c; tmap[1] = C1d;
68  TableEventMap *T2 = new TableEventMap(1, tmap); // takes ownership of pointers C0c and C1d.
69 
70  std::vector<ValueType> vec;
71  vec.push_back(4);
72  vec.push_back(5);
73 
74 
75  ConstantEventMap *D1 = new ConstantEventMap(10); // owned by D3 below
76  ConstantEventMap *D2 = new ConstantEventMap(15); // owned by D3 below
77 
78  SplitEventMap *D3 = new SplitEventMap(1, vec, D1, D2);
79 
80  // Test different initializer for TableEventMap where input maps ints to ints.
81  for (size_t i = 0;i < 100;i++) {
82  size_t nElems = Rand() % 10; // num of value->answer pairs.
83  std::map<ValueType, AnswerType> init_map;
84  for (size_t i = 0;i < nElems;i++) {
85  init_map[Rand() % 10] = Rand() % 5;
86  }
87  EventKeyType key = Rand() % 10;
88  TableEventMap T3(key, init_map);
89  for (size_t i = 0; i < 10; i++) {
90  EventType vec;
91  vec.push_back(std::make_pair(key, (ValueType) i));
92  AnswerType ans;
93  // T3.Map(vec, &ans);
94  if (init_map.count(i) == 0) {
95  KALDI_ASSERT( ! T3.Map(vec, &ans) ); // false
96  } else {
97  bool b = T3.Map(vec, &ans);
98  KALDI_ASSERT(b);
99  KALDI_ASSERT(ans == init_map[i]); // true
100  }
101  }
102  }
103 
104  delete T1;
105  delete T2;
106  delete D3;
107 }
bool GetTreeStructure(const EventMap &map, int32 *num_leaves, std::vector< int32 > *parents)
This function gets the tree structure of the EventMap "map" in a convenient form. ...
Definition: event-map.cc:429
virtual EventAnswerType MaxResult() const
Definition: event-map.h:142
kaldi::int32 int32
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51

◆ TestEventMapIo()

void kaldi::TestEventMapIo ( bool  binary)

Definition at line 178 of file event-map-test.cc.

References CopySetToVector(), KALDI_ASSERT, Rand(), RandomEventMap(), EventMap::Read(), and EventMap::Write().

Referenced by main().

178  {
179  for (size_t p = 0; p < 20; p++) {
180  int32 max_key = 10;
181  int32 num_keys = 1 + (Rand() % (max_key - 1));
182  std::set<EventKeyType> key_set;
183  // - 5 to allow negative keys. These are allowed.
184  while (key_set.size() < (size_t)num_keys) key_set.insert( (Rand() % (2*max_key)) - 5);
185  std::vector<EventKeyType> key_vec;
186  CopySetToVector(key_set, &key_vec);
187  EventMap *rand_map = RandomEventMap(key_vec);
188 
189  std::ostringstream str_out;
190  EventMap::Write(str_out, binary, rand_map);
191 
192 
193  if (p < 1) {
194  std::cout << "Random map is: "<<str_out.str()<<'\n';
195  }
196 
197  std::istringstream str_in(str_out.str());
198 
199  EventMap *read_map = EventMap::Read(str_in, binary);
200  std::ostringstream str2_out;
201  EventMap::Write(str2_out, binary, read_map);
202 
203  // Checking we can write the map, read it in, and get the same string form.
204  KALDI_ASSERT(str_out.str() == str2_out.str());
205  delete read_map;
206  delete rand_map;
207  }
208 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
EventMap * RandomEventMap(const std::vector< EventKeyType > &keys)

◆ TestEventMapMapValues()

void kaldi::TestEventMapMapValues ( )

Definition at line 270 of file event-map-test.cc.

References rnnlm::i, KALDI_ASSERT, kMaxVal, EventMap::Map(), EventMap::MapValues(), Rand(), and RandomEventMap().

Referenced by main().

270  {
271  std::vector<EventKeyType> keys;
272  keys.push_back(1); // these keys are
273  keys.push_back(2); // hardwired into the code below, do not change
274  EventMap *em = RandomEventMap(keys);
275  EventType empty_event;
276 
277  unordered_set<EventKeyType> mapped_keys;
278  unordered_map<EventKeyType,EventKeyType> value_map;
279  if (Rand() % 2 == 0) mapped_keys.insert(1);
280  if (Rand() % 2 == 0) mapped_keys.insert(2);
281 
282  EventValueType v_offset = Rand() % kMaxVal;
283  for (EventValueType v = 0; v < kMaxVal; v++)
284  value_map[v] = (v + v_offset) % kMaxVal;
285 
286  EventMap *mapped_em = em->MapValues(mapped_keys, value_map);
287 
288  for (int32 i = 0; i < 10; i++) {
289  EventType event, mapped_event;
290  for (int32 key = 1; key <= 2; key++) {
291  if (Rand() % 2 == 0) {
292  EventValueType value = Rand() % kMaxVal;
293  event.push_back(std::make_pair(key, value));
294  EventValueType mapped_value;
295  if (mapped_keys.count(key) == 0) mapped_value = value;
296  else mapped_value = value_map[value];
297  mapped_event.push_back(std::make_pair(key, mapped_value));
298  }
299  }
300  EventAnswerType answer, answer2;
301  if (em->Map(event, &answer)) {
302  bool ret = mapped_em->Map(mapped_event, &answer2);
303  KALDI_ASSERT(ret);
304  KALDI_ASSERT(answer == answer2);
305  }
306  }
307  delete em;
308  delete mapped_em;
309 }
const int32 kMaxVal
kaldi::int32 int32
virtual bool Map(const EventType &event, EventAnswerType *ans) const =0
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
virtual EventMap * MapValues(const unordered_set< EventKeyType > &keys_to_map, const unordered_map< EventValueType, EventValueType > &value_map) const =0
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
EventMap * RandomEventMap(const std::vector< EventKeyType > &keys)

◆ TestEventMapPrune()

void kaldi::TestEventMapPrune ( )

Definition at line 210 of file event-map-test.cc.

References EventMap::Copy(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, EventMap::Map(), EventMap::MultiMap(), EventMap::Prune(), Rand(), RandomEventMap(), and SortAndUniq().

Referenced by main().

210  {
211  const EventAnswerType no_ans = -10;
212  std::vector<EventKeyType> keys;
213  keys.push_back(1); // these keys are
214  keys.push_back(2); // hardwired into the code below, do not change
215  EventMap *em = RandomEventMap(keys);
216  EventType empty_event;
217  std::vector<EventAnswerType> all_answers;
218  em->MultiMap(empty_event, &all_answers);
219  SortAndUniq(&all_answers);
220  std::vector<EventMap*> new_leaves;
221  std::vector<EventAnswerType> mapping;
222  for (size_t i = 0; i < all_answers.size(); i++) {
223  EventAnswerType ans = all_answers[i];
224  KALDI_ASSERT(ans >= 0);
225  new_leaves.resize(ans + 1, NULL);
226  mapping.resize(ans + 1, no_ans);
227  EventAnswerType map_to;
228  if (Rand() % 2 == 0) map_to = -1;
229  else map_to = Rand() % 20;
230  new_leaves[ans] = new ConstantEventMap(map_to);
231  mapping[ans] = map_to;
232  }
233  EventMap *mapped_em = em->Copy(new_leaves),
234  *pruned_em = mapped_em->Prune();
235  for (size_t i = 0; i < new_leaves.size(); i++)
236  delete new_leaves[i];
237  for (int32 i = 0; i < 10; i++) {
238  EventType event;
239  for (int32 key = 1; key <= 2; key++) {
240  if (Rand() % 2 == 0) {
241  EventValueType value = Rand() % 20;
242  event.push_back(std::make_pair(key, value));
243  }
244  }
245  EventAnswerType answer, answer2;
246  if (em->Map(event, &answer)) {
247  bool ret;
248  if (pruned_em == NULL) ret = false;
249  else ret = pruned_em->Map(event, &answer2);
250  KALDI_ASSERT(answer >= 0);
251  EventAnswerType mapped_ans = mapping[answer];
252  KALDI_ASSERT(mapped_ans != no_ans);
253  if (mapped_ans == -1) {
254  if (ret == false)
255  KALDI_LOG << "Answer was correctly pruned away.";
256  else
257  KALDI_LOG << "Answer was not pruned away [but this is not required]";
258  } else {
259  KALDI_ASSERT(ret == true);
260  KALDI_ASSERT(answer2 == mapped_ans);
261  KALDI_LOG << "Answers match " << answer << " -> " << answer2;
262  }
263  }
264  }
265  delete em;
266  delete mapped_em;
267  delete pruned_em;
268 }
kaldi::int32 int32
void SortAndUniq(std::vector< T > *vec)
Sorts and uniq&#39;s (removes duplicates) from a vector.
Definition: stl-utils.h:39
virtual bool Map(const EventType &event, EventAnswerType *ans) const =0
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
virtual EventMap * Copy(const std::vector< EventMap *> &new_leaves) const =0
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
virtual EventMap * Prune() const =0
EventMap * RandomEventMap(const std::vector< EventKeyType > &keys)
virtual void MultiMap(const EventType &event, std::vector< EventAnswerType > *ans) const =0
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TestEventTypeIo()

void kaldi::TestEventTypeIo ( bool  binary)

Definition at line 110 of file event-map-test.cc.

References Output::Close(), rnnlm::i, KALDI_ASSERT, Rand(), ReadEventType(), Output::Stream(), Input::Stream(), and WriteEventType().

Referenced by main().

110  {
111  for (size_t p = 0; p < 20; p++) {
112  EventType event_vec;
113  size_t size = Rand() % 20;
114  event_vec.resize(size);
115  for (size_t i = 0;i < size;i++) {
116  event_vec[i].first = Rand() % 10 + (i > 0 ? event_vec[i-1].first : 0);
117  event_vec[i].second = Rand() % 20;
118  }
119 
120 
121  {
122  const char *filename = "tmpf";
123  Output ko(filename, binary);
124  std::ostream &outfile = ko.Stream();
125  WriteEventType(outfile, binary, event_vec);
126  ko.Close();
127 
128  {
129  bool binary_in;
130  Input ki(filename, &binary_in);
131  std::istream &infile = ki.Stream();
132  EventType evec2;
133  evec2.push_back(std::pair<EventKeyType, EventValueType>(1, 1)); // make it nonempty.
134  ReadEventType(infile, binary_in, &evec2);
135  KALDI_ASSERT(evec2 == event_vec);
136  }
137  }
138  }
139 
140  unlink("tmpf");
141 }
void WriteEventType(std::ostream &os, bool binary, const EventType &evec)
Definition: event-map.cc:228
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
void ReadEventType(std::istream &is, bool binary, EventType *evec)
Definition: event-map.cc:239
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestFindAllKeys()

void kaldi::TestFindAllKeys ( )

Definition at line 148 of file build-tree-utils-test.cc.

References CopyMapKeysToSet(), CopyMapToVector(), CopySetToVector(), FindAllKeys(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, kAllKeysInsistIdentical, kAllKeysIntersection, kAllKeysUnion, and RandInt().

Referenced by main().

148  {
149  for (size_t iter = 0;iter < 10;iter++) {
150  BuildTreeStatsType stats;
151  std::set<EventKeyType> all_keys_union;
152  std::set<EventKeyType> all_keys_intersection;
153 
154  for (size_t i = 0;i < 3;i++) {
155  std::map<EventKeyType, EventValueType> key_vals;
156  for (size_t j = 0;j < 5;j++) {
157  EventKeyType k = RandInt(-2, 1);
158  EventValueType v = RandInt(0, 10);
159  key_vals[k] = v;
160  }
161  EventType evec;
162  CopyMapToVector(key_vals, &evec);
163  stats.push_back(std::pair<EventType, Clusterable*>(evec, (Clusterable*) NULL));
164  std::set<EventKeyType> s;
165  CopyMapKeysToSet(key_vals, &s);
166  if (i == 0) { all_keys_union = s; all_keys_intersection = s; }
167  else {
168  std::set<EventKeyType> new_intersection;
169  for (std::set<EventKeyType>::iterator iter = s.begin(); iter != s.end(); iter++) {
170  all_keys_union.insert(*iter);
171  if (all_keys_intersection.count(*iter) != 0) new_intersection.insert(*iter);
172  }
173  all_keys_intersection = new_intersection;
174  }
175  }
176 
177  { // test in union mode.
178  std::vector<EventKeyType> keys1, keys2;
179  CopySetToVector(all_keys_union, &keys1);
180  FindAllKeys(stats, kAllKeysUnion, &keys2);
181  KALDI_ASSERT(keys1 == keys2);
182  }
183  { // test in intersection mode.
184  std::vector<EventKeyType> keys1, keys2;
185  CopySetToVector(all_keys_intersection, &keys1);
186  FindAllKeys(stats, kAllKeysIntersection, &keys2);
187  KALDI_ASSERT(keys1 == keys2);
188  }
189  { // test in insist-same mode.
190  std::vector<EventKeyType> keys1, keys2;
191  CopySetToVector(all_keys_intersection, &keys1);
192  try {
193  FindAllKeys(stats, kAllKeysInsistIdentical, &keys2); // note, it SHOULD throw an exception here.
194  // This is for testing purposes. It gets caught.
195  KALDI_ASSERT(keys1 == keys2);
196  KALDI_ASSERT(all_keys_union == all_keys_intersection);
197  } catch(...) { // it should throw exception if all keys are not the same.
198  KALDI_LOG << "Ignore previous error.";
199  KALDI_ASSERT(all_keys_union != all_keys_intersection);
200  }
201  }
202  }
203 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
void FindAllKeys(const BuildTreeStatsType &stats, AllKeysType keys_type, std::vector< EventKeyType > *keys_out)
FindAllKeys puts in *keys the (sorted, unique) list of all key identities in the stats.
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
void CopyMapKeysToSet(const std::map< A, B > &m, std::set< A > *s)
Copies the keys in a map to a set.
Definition: stl-utils.h:150
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
#define KALDI_LOG
Definition: kaldi-error.h:153
void CopyMapToVector(const std::map< A, B > &m, std::vector< std::pair< A, B > > *v)
Copies the (key, value) pairs in a map to a vector of pairs.
Definition: stl-utils.h:112
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestFmpe()

void kaldi::TestFmpe ( )

Definition at line 79 of file fmpe-test.cc.

References Fmpe::AccStats(), MatrixBase< Real >::AddMat(), Fmpe::ComputeFeatures(), GetFeatDeriv(), GetGmmLike(), rnnlm::i, kaldi::unittest::InitRandDiagGmm(), MatrixBase< Real >::IsZero(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, kTrans, FmpeUpdateOptions::learning_rate, MatrixBase< Real >::NumCols(), DiagGmm::NumGauss(), MatrixBase< Real >::NumRows(), Rand(), RandGauss(), Fmpe::Read(), Output::Stream(), Input::Stream(), TraceMatMat(), Fmpe::Update(), and Fmpe::Write().

Referenced by main().

79  {
80  int32 dim = 10 + (Rand() % 10);
81  int32 num_comp = 10 + (Rand() % 10);
82  DiagGmm gmm;
83  unittest::InitRandDiagGmm(dim, num_comp, &gmm);
84 
85  int32 num_frames = 20;
86  Matrix<BaseFloat> feats(num_frames, dim);
87 
88  for (int32 i = 0; i < num_frames; i++)
89  for (int32 j = 0; j < dim; j++)
90  feats(i, j) = RandGauss();
91 
92  FmpeOptions opts; // Default.
93  {
94  Fmpe fmpe(gmm, opts);
95  {
96  bool binary = (Rand() % 2 == 1);
97  Output ko("tmpf", binary);
98  fmpe.Write(ko.Stream(), binary);
99  }
100  }
101  Fmpe fmpe(gmm, opts);
102  {
103  bool binary_in;
104  Input ki("tmpf", &binary_in);
105  fmpe.Read(ki.Stream(), binary_in);
106  }
107 
108  // We'll first be testing that the feature derivative is
109  // accurate, by measuring a small random offset in feature space.
110  {
111  Matrix<BaseFloat> deriv;
112  Matrix<BaseFloat> random_offset(feats.NumRows(), feats.NumCols());
113  for (int32 i = 0; i < feats.NumRows(); i++)
114  for (int32 j = 0; j < feats.NumCols(); j++)
115  random_offset(i, j) = 1.0e-03 * RandGauss();
116  BaseFloat like_before = GetGmmLike(gmm, feats);
117  feats.AddMat(1.0, random_offset);
118  BaseFloat like_after = GetGmmLike(gmm, feats);
119  feats.AddMat(-1.0, random_offset); // undo the change.
120  GetFeatDeriv(gmm, feats, &deriv);
121  BaseFloat change1 = like_after - like_before,
122  change2 = TraceMatMat(random_offset, deriv, kTrans);
123  KALDI_LOG << "Random offset led to like change "
124  << change1 << " (manually), and " << change2
125  << " (derivative)";
126  // note: not making this threshold smaller, as don't want
127  // spurious failures. Seems to be OK though.
128  KALDI_ASSERT( fabs(change1-change2) < 0.15*fabs(change1+change2));
129  }
130 
131  std::vector<std::vector<int32> > gselect(feats.NumRows()); // make it have all Gaussians...
132  for (int32 i = 0; i < feats.NumRows(); i++)
133  for (int32 j = 0; j < gmm.NumGauss(); j++)
134  gselect[i].push_back(j);
135 
136  Matrix<BaseFloat> fmpe_offset;
137  // Check that the fMPE feature offset is zero.
138  fmpe.ComputeFeatures(feats, gselect, &fmpe_offset);
139  KALDI_ASSERT(fmpe_offset.IsZero());
140 
141  // Note: we're just using the ML objective function here.
142  // This is just to make sure the derivatives are all computed
143  // correctly.
144  BaseFloat like_before_update = GetGmmLike(gmm, feats);
145  // Now get stats for update.
146  FmpeStats stats(fmpe);
147  Matrix<BaseFloat> deriv;
148  GetFeatDeriv(gmm, feats, &deriv);
149  fmpe.AccStats(feats, gselect, deriv, NULL, &stats);
150  FmpeUpdateOptions update_opts;
151  update_opts.learning_rate = 0.001; // so linear assumption is more valid.
152  BaseFloat delta = fmpe.Update(update_opts, stats);
153 
154  fmpe.ComputeFeatures(feats, gselect, &fmpe_offset);
155  feats.AddMat(1.0, fmpe_offset);
156 
157  BaseFloat like_after_update = GetGmmLike(gmm, feats);
158 
159  BaseFloat delta2 = like_after_update - like_before_update;
160  KALDI_LOG << "Change predicted by fMPE Update function is "
161  << delta << ", change computed directly is "
162  << delta2;
163  KALDI_ASSERT(fabs(delta-delta2) < 0.15 * fabs(delta+delta2));
164 
165  unlink("tmpf");
166 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
void InitRandDiagGmm(int32 dim, int32 num_comp, DiagGmm *gmm)
BaseFloat GetGmmLike(const DiagGmm &gmm, const Matrix< BaseFloat > &feats)
Definition: fmpe-test.cc:71
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
void GetFeatDeriv(const DiagGmm &gmm, const Matrix< BaseFloat > &feats, Matrix< BaseFloat > *deriv)
Definition: fmpe-test.cc:32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TestGenRandContextDependency()

void kaldi::TestGenRandContextDependency ( )

Definition at line 74 of file context-dep-test.cc.

References Output::Close(), CopySetToVector(), GenRandContextDependency(), ContextDependency::GetPdfInfo(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), ContextDependency::Read(), Output::Stream(), Input::Stream(), and ContextDependency::Write().

Referenced by main().

74  {
75  bool binary = (Rand()%2 == 0);
76  size_t num_phones = 1 + Rand() % 10;
77  std::set<int32> phones_set;
78  while (phones_set.size() < num_phones) phones_set.insert(Rand() % (num_phones + 5));
79  std::vector<int32> phones;
80  CopySetToVector(phones_set, &phones);
81  bool ensure_all_covered = (Rand() % 2 == 0);
82  std::vector<int32> phone2num_pdf_classes;
83  ContextDependency *dep = GenRandContextDependency(phones,
84  ensure_all_covered, // false == don't ensure all phones covered.
85  &phone2num_pdf_classes);
86  // stuff here.
87  const char *filename = "tmpf";
88  {
89  Output ko(filename, binary);
90  std::ostream &outfile = ko.Stream();
91  { // Test GetPdfInfo
92  std::vector<std::vector<std::pair<int32, int32> > > pdf_info;
93  dep->GetPdfInfo(phones, phone2num_pdf_classes, &pdf_info);
94  std::vector<bool> all_phones(phones.back()+1, false); // making sure all covered.
95  for (size_t i = 0; i < pdf_info.size(); i++) {
96  KALDI_ASSERT(!pdf_info[i].empty()); // make sure pdf seen.
97  for (size_t j = 0; j < pdf_info[i].size(); j++) {
98  int32 idx = pdf_info[i][j].first;
99  KALDI_ASSERT(static_cast<size_t>(idx) < all_phones.size());
100  all_phones[pdf_info[i][j].first] = true;
101  }
102  }
103  if (ensure_all_covered)
104  for (size_t k = 0; k < phones.size(); k++) KALDI_ASSERT(all_phones[phones[k]]);
105  }
106 
107  dep->Write(outfile, binary);
108  ko.Close();
109  }
110  {
111  bool binary_in;
112  Input ki(filename, &binary_in);
113  std::istream &infile = ki.Stream();
114  ContextDependency dep2;
115  dep2.Read(infile, binary_in);
116 
117  std::ostringstream ostr1, ostr2;
118  dep->Write(ostr1, false);
119  dep2.Write(ostr2, false);
120  KALDI_ASSERT(ostr1.str() == ostr2.str());
121  }
122 
123  delete dep;
124 
125  unlink("tmpf");
126 
127  std::cout << "Note: any \"serious error\" warnings preceding this line are OK.\n";
128 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
ContextDependency * GenRandContextDependency(const std::vector< int32 > &phone_ids, bool ensure_all_covered, std::vector< int32 > *hmm_lengths)
GenRandContextDependency is mainly of use for debugging.
Definition: context-dep.cc:46

◆ TestGenRandStats()

void kaldi::TestGenRandStats ( )

Definition at line 25 of file build-tree-test.cc.

References DeleteBuildTreeStats(), GenRandStats(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_VLOG, kPdfClass, EventMap::Lookup(), Rand(), RandUniform(), WriteBasicType(), WriteBuildTreeStats(), and WriteIntegerVector().

Referenced by main().

25  {
26  for (int32 p = 0; p < 2; p++) {
27  int32 dim = 1 + Rand() % 40;
28  int32 num_phones = 1 + Rand() % 40;
29  int32 num_stats = 1 + (Rand() % 20);
30  int32 N = 2 + Rand() % 2; // 2 or 3.
31  int32 P = Rand() % N;
32  float ctx_dep_prob = 0.5 + 0.5*RandUniform();
33  std::vector<int32> phone_ids(num_phones);
34  for (size_t i = 0;i < (size_t)num_phones;i++)
35  phone_ids[i] = (i == 0 ? (Rand() % 2) : phone_ids[i-1] + 1 + (Rand()%2));
36  int32 max_phone = *std::max_element(phone_ids.begin(), phone_ids.end());
37  std::vector<int32> hmm_lengths(max_phone+1);
38  std::vector<bool> is_ctx_dep(max_phone+1);
39 
40  for (int32 i = 0; i <= max_phone; i++) {
41  hmm_lengths[i] = 1 + Rand() % 3;
42  is_ctx_dep[i] = (RandUniform() < ctx_dep_prob); // true w.p. ctx_dep_prob.
43  }
44  for (size_t i = 0;i < (size_t) num_phones;i++) {
45  KALDI_VLOG(2) << "For idx = "<< i << ", (phone_id, hmm_length, is_ctx_dep) == " << (phone_ids[i]) << " " << (hmm_lengths[phone_ids[i]]) << " " << (is_ctx_dep[phone_ids[i]]);
46  }
47  BuildTreeStatsType stats;
48  // put false for all_covered argument.
49  // if it doesn't really ensure that all are covered with true, this will induce
50  // failure in the test of context-fst.
51  GenRandStats(dim, num_stats, N, P, phone_ids, hmm_lengths, is_ctx_dep, false, &stats);
52  std::cout << "Writing random stats.";
53  std::cout <<"dim = " << dim << '\n';
54  std::cout <<"num_phones = " << num_phones << '\n';
55  std::cout <<"num_stats = " << num_stats << '\n';
56  std::cout <<"N = "<< N << '\n';
57  std::cout <<"P = "<< P << '\n';
58  std::cout << "is-ctx-dep = ";
59  for (size_t i = 0;i < is_ctx_dep.size();i++)
60  WriteBasicType(std::cout, false, static_cast<bool>(is_ctx_dep[i]));
61  std::cout << "hmm_lengths = "; WriteIntegerVector(std::cout, false, hmm_lengths);
62  std::cout << "phone_ids = "; WriteIntegerVector(std::cout, false, phone_ids);
63  std::cout << "Stats are: \n";
64  WriteBuildTreeStats(std::cout, false, stats);
65 
66 
67  // Now check the properties of the stats.
68  for (size_t i = 0;i < stats.size();i++) {
69  EventValueType central_phone;
70  bool b = EventMap::Lookup(stats[i].first, P, &central_phone);
71  KALDI_ASSERT(b);
72  EventValueType position;
73  b = EventMap::Lookup(stats[i].first, kPdfClass, &position);
74  KALDI_ASSERT(b);
75  KALDI_ASSERT(position>=0 && position < hmm_lengths[central_phone]);
76 
77  for (EventKeyType j = 0; j < N; j++) {
78  if (j != P) { // non-"central" phone.
79  EventValueType ctx_phone;
80  b = EventMap::Lookup(stats[i].first, j, &ctx_phone);
81  KALDI_ASSERT(is_ctx_dep[central_phone] == b);
82  }
83  }
84  }
85  DeleteBuildTreeStats(&stats);
86  }
87 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
void GenRandStats(int32 dim, int32 num_stats, int32 N, int32 P, const std::vector< int32 > &phone_ids, const std::vector< int32 > &phone2hmm_length, const std::vector< bool > &is_ctx_dep, bool ensure_all_phones_covered, BuildTreeStatsType *stats_out)
GenRandStats generates random statistics of the form used by BuildTree.
Definition: build-tree.cc:30
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
static const EventKeyType kPdfClass
Definition: context-dep.h:39
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
void WriteIntegerVector(std::ostream &os, bool binary, const std::vector< T > &v)
Function for writing STL vectors of integer types.
Definition: io-funcs-inl.h:198
void WriteBasicType(std::ostream &os, bool binary, T t)
WriteBasicType is the name of the write function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:34
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
void WriteBuildTreeStats(std::ostream &os, bool binary, const BuildTreeStatsType &stats)
Writes BuildTreeStats object. This works even if pointers are NULL.

◆ TestHashList()

void kaldi::TestHashList ( )

Definition at line 29 of file hash-list-test.cc.

References HashList< I, T >::Clear(), count, HashList< I, T >::Delete(), HashList< I, T >::Find(), HashList< I, T >::GetList(), rnnlm::i, HashList< I, T >::Insert(), rnnlm::j, KALDI_ASSERT, Rand(), HashList< I, T >::SetSize(), and swap().

29  {
30  typedef typename HashList<Int, T>::Elem Elem;
31 
32  HashList<Int, T> hash;
33  hash.SetSize(200); // must be called before use.
34  std::map<Int, T> m1;
35  for (size_t j = 0; j < 50; j++) {
36  Int key = Rand() % 200;
37  T val = Rand() % 50;
38  m1[key] = val;
39  Elem *e = hash.Find(key);
40  if (e) e->val = val;
41  else hash.Insert(key, val);
42  }
43 
44 
45  std::map<Int, T> m2;
46 
47  for (int i = 0; i < 100; i++) {
48  m2.clear();
49  for (typename std::map<Int, T>::const_iterator iter = m1.begin();
50  iter != m1.end();
51  iter++) {
52  m2[iter->first + 1] = iter->second;
53  }
54  std::swap(m1, m2);
55 
56  Elem *h = hash.Clear(), *tmp;
57 
58  hash.SetSize(100 + Rand() % 100); // note, SetSize is relatively cheap
59  // operation as long as we are not increasing the size more than it's ever
60  // previously been increased to.
61 
62  for (; h != NULL; h = tmp) {
63  hash.Insert(h->key + 1, h->val);
64  tmp = h->tail;
65  hash.Delete(h); // think of this like calling delete.
66  }
67 
68  // Now make sure h and m2 are the same.
69  const Elem *list = hash.GetList();
70  size_t count = 0;
71  for (; list != NULL; list = list->tail, count++) {
72  KALDI_ASSERT(m1[list->key] == list->val);
73  }
74 
75  for (size_t j = 0; j < 10; j++) {
76  Int key = Rand() % 200;
77  bool found_m1 = (m1.find(key) != m1.end());
78  if (found_m1) m1[key];
79  Elem *e = hash.Find(key);
80  KALDI_ASSERT((e != NULL) == found_m1);
81  if (found_m1)
82  KALDI_ASSERT(m1[key] == e->val);
83  }
84 
85  KALDI_ASSERT(m1.size() == count);
86  }
87 }
Elem * Insert(I key, T val)
Insert inserts a new element into the hashtable/stored list.
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
const size_t count
void SetSize(size_t sz)
SetSize tells the object how many hash buckets to allocate (should typically be at least twice the nu...
Definition: hash-list-inl.h:37
const Elem * GetList() const
Gives the head of the current list to the user.
Definition: hash-list-inl.h:61
Elem * Clear()
Clears the hash and gives the head of the current list to the user; ownership is transferred to the u...
Definition: hash-list-inl.h:46
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Elem * Find(I key)
Find tries to find this element in the current list using the hashtable.
Definition: hash-list-inl.h:72
void Delete(Elem *e)
Think of this like delete().
Definition: hash-list-inl.h:66

◆ TestHmmTopology()

void kaldi::TestHmmTopology ( )

Definition at line 27 of file hmm-topology-test.cc.

References GenRandTopology(), GetDefaultTopology(), KALDI_ASSERT, HmmTopology::MinLength(), Rand(), RandInt(), HmmTopology::Read(), and HmmTopology::Write().

Referenced by main().

27  {
28  bool binary = (Rand()%2 == 0);
29 
30  std::string input_str = "<Topology>\n"
31  "<TopologyEntry>\n"
32  "<ForPhones> 1 2 3 4 5 6 7 8 9 </ForPhones>\n"
33  "<State> 0 <PdfClass> 0\n"
34  "<Transition> 0 0.5\n"
35  "<Transition> 1 0.5\n"
36  "</State> \n"
37  "<State> 1 <PdfClass> 1 \n"
38  "<Transition> 1 0.5\n"
39  "<Transition> 2 0.5\n"
40  "</State> \n"
41  " <State> 2 <PdfClass> 2\n"
42  " <Transition> 2 0.5\n"
43  " <Transition> 3 0.5\n"
44  " </State> \n"
45  " <State> 3 </State>\n"
46  " </TopologyEntry>\n"
47  " <TopologyEntry>\n"
48  " <ForPhones> 10 11 13 </ForPhones>\n"
49  " <State> 0 <PdfClass> 0\n"
50  " <Transition> 0 0.5\n"
51  " <Transition> 1 0.5\n"
52  " </State> \n"
53  " <State> 1 <PdfClass> 1 \n"
54  " <Transition> 1 0.5\n"
55  " <Transition> 2 0.5\n"
56  " </State> \n"
57  " <State> 2 </State>"
58  " </TopologyEntry>\n"
59  " </Topology>\n";
60 
61  std::string chain_input_str = "<Topology>\n"
62  "<TopologyEntry>\n"
63  "<ForPhones> 1 2 3 4 5 6 7 8 9 </ForPhones>\n"
64  " <State> 0 <ForwardPdfClass> 0 <SelfLoopPdfClass> 1\n"
65  " <Transition> 0 0.5\n"
66  " <Transition> 1 0.5\n"
67  " </State> \n"
68  " <State> 1 </State>\n"
69  "</TopologyEntry>\n"
70  "</Topology>\n";
71 
72  HmmTopology topo;
73 
74  if (RandInt(0, 1) == 0) {
75  topo = GenRandTopology();
76  } else {
77  std::istringstream iss(input_str);
78  topo.Read(iss, false);
79  KALDI_ASSERT(topo.MinLength(3) == 3);
80  KALDI_ASSERT(topo.MinLength(11) == 2);
81  }
82 
83  std::ostringstream oss;
84  topo.Write(oss, binary);
85 
86  HmmTopology topo2;
87  // std::cout << oss.str() << '\n' << std::flush;
88  std::istringstream iss2(oss.str());
89  topo2.Read(iss2, binary);
90 
91  { // test equality.
92  std::ostringstream oss1, oss2;
93  topo.Write(oss1, false);
94  topo2.Write(oss2, false);
95  KALDI_ASSERT(oss1.str() == oss2.str());
96  }
97 
98  { // test chain topology
99  HmmTopology chain_topo;
100  std::istringstream chain_iss(chain_input_str);
101  chain_topo.Read(chain_iss, false);
102  KALDI_ASSERT(chain_topo.MinLength(3) == 1);
103  }
104 
105  { // make sure GetDefaultTopology does not crash.
106  std::vector<int32> phones;
107  phones.push_back(1);
108  phones.push_back(2);
109  GetDefaultTopology(phones);
110  }
111 }
HmmTopology GetDefaultTopology(const std::vector< int32 > &phones_in)
This function returns a HmmTopology object giving a normal 3-state topology, covering all phones in t...
HmmTopology GenRandTopology(const std::vector< int32 > &phones_in, const std::vector< int32 > &num_pdf_classes)
This method of generating an arbitrary HmmTopology object allows you to specify the number of pdf-cla...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestInf()

void kaldi::TestInf ( )

Definition at line 242 of file text-utils-test.cc.

References ConvertStringToReal(), rnnlm::d, and KALDI_ASSERT.

242  {
243  Real d;
244  KALDI_ASSERT(ConvertStringToReal(std::to_string(exp(10000)), &d) &&
245  d > 0 && d - d != 0);
246  KALDI_ASSERT(ConvertStringToReal(std::to_string(-exp(10000)), &d) &&
247  d < 0 && d - d != 0);
248 }
bool ConvertStringToReal(const std::string &str, T *out)
ConvertStringToReal converts a string into either float or double and returns false if there was any ...
Definition: text-utils.cc:238
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestIsLine()

void kaldi::TestIsLine ( )

Definition at line 304 of file text-utils-test.cc.

References IsLine(), and KALDI_ASSERT.

Referenced by main().

304  {
305  KALDI_ASSERT(IsLine("a"));
306  KALDI_ASSERT(IsLine("a b"));
307  KALDI_ASSERT(!IsLine("a\nb"));
308  KALDI_ASSERT(!IsLine("a b "));
309  KALDI_ASSERT(!IsLine(" a b"));
310 }
bool IsLine(const std::string &line)
Returns true if "line" is free of characters and unprintable characters, and does not contain leadi...
Definition: text-utils.cc:154
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestIsSorted()

static void kaldi::TestIsSorted ( )
static

Definition at line 26 of file stl-utils-test.cc.

References rnnlm::i, IsSorted(), KALDI_ASSERT, and Rand().

Referenced by main().

26  {
27  for (int i = 0;i < 100;i++) {
28  std::vector<int> vec, vec2;
29  int len = Rand()%5;
30  for (int i = 0;i < len;i++)
31  vec.push_back(Rand() % 10);
32  vec2 = vec;
33  std::sort(vec2.begin(), vec2.end());
34  KALDI_ASSERT(IsSorted(vec) == (vec == vec2));
35  }
36 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
bool IsSorted(const std::vector< T > &vec)
Returns true if the vector is sorted.
Definition: stl-utils.h:47
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestIsSortedAndUniq()

static void kaldi::TestIsSortedAndUniq ( )
static

Definition at line 38 of file stl-utils-test.cc.

References rnnlm::i, IsSortedAndUniq(), KALDI_ASSERT, and Rand().

Referenced by main().

38  {
39  for (int i = 0;i < 100;i++) {
40  std::vector<int> vec, vec2;
41  int len = Rand()%5;
42  for (int i = 0;i < len;i++)
43  vec.push_back(Rand() % 10);
44 
45  if (!IsSortedAndUniq(vec)) {
46  bool ok = false;
47  for (size_t i = 0; i+1 < (size_t)len; i++)
48  if (vec[i] >= vec[i+1]) ok = true; // found out-of-order or dup.
49  KALDI_ASSERT(ok);
50  } else { // is sorted + uniq.
51  for (size_t i = 0; i+1 < (size_t)len; i++)
52  KALDI_ASSERT(vec[i] < vec[i+1]);
53  }
54  }
55 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool IsSortedAndUniq(const std::vector< T > &vec)
Returns true if the vector is sorted and contains each element only once.
Definition: stl-utils.h:63

◆ TestIsToken()

void kaldi::TestIsToken ( )

Definition at line 288 of file text-utils-test.cc.

References IsToken(), and KALDI_ASSERT.

Referenced by main().

288  {
289  KALDI_ASSERT(IsToken("a"));
290  KALDI_ASSERT(IsToken("ab"));
291  KALDI_ASSERT(!IsToken("ab "));
292  KALDI_ASSERT(!IsToken(" ab"));
293  KALDI_ASSERT(!IsToken("a b"));
294  KALDI_ASSERT(IsToken("\231")); // typical non-ASCII printable character,
295  // something with an accent.
296  KALDI_ASSERT(!IsToken("\377")); // character 255, which is a form of space.
297  KALDI_ASSERT(IsToken("a-b,c,d=ef"));
298  KALDI_ASSERT(!IsToken("a\nb"));
299  KALDI_ASSERT(!IsToken("a\tb"));
300  KALDI_ASSERT(!IsToken("ab\t"));
301  KALDI_ASSERT(!IsToken(""));
302 }
bool IsToken(const std::string &token)
Returns true if "token" is nonempty, and all characters are printable and whitespace-free.
Definition: text-utils.cc:105
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestIvectorExtraction()

void kaldi::TestIvectorExtraction ( const IvectorExtractor extractor,
const MatrixBase< BaseFloat > &  feats,
const FullGmm fgmm 
)

Definition at line 85 of file ivector-extractor-test.cc.

References IvectorExtractorUtteranceStats::AccStats(), OnlineIvectorEstimationStats::AccStats(), FullGmm::ComponentPosteriors(), IvectorExtractor::GetAuxf(), OnlineIvectorEstimationStats::GetIvector(), IvectorExtractor::GetIvectorDistribution(), rnnlm::i, IvectorExtractor::IvectorDependentWeights(), IvectorExtractor::IvectorDim(), KALDI_ASSERT, KALDI_LOG, kUndefined, MatrixBase< Real >::NumCols(), IvectorExtractorUtteranceStats::NumFrames(), FullGmm::NumGauss(), IvectorExtractor::NumGauss(), MatrixBase< Real >::NumRows(), OnlineIvectorEstimationStats::ObjfChange(), IvectorExtractor::PriorOffset(), and MatrixBase< Real >::Row().

Referenced by UnitTestIvectorExtractor().

87  {
88  if (extractor.IvectorDependentWeights())
89  return; // Nothing to do as online iVector estimator does not work in this
90  // case.
91  int32 num_frames = feats.NumRows(),
92  feat_dim = feats.NumCols(),
93  num_gauss = extractor.NumGauss(),
94  ivector_dim = extractor.IvectorDim();
95  Posterior post(num_frames);
96 
97  double tot_log_like = 0.0;
98  for (int32 t = 0; t < num_frames; t++) {
99  SubVector<BaseFloat> frame(feats, t);
100  Vector<BaseFloat> posterior(fgmm.NumGauss(), kUndefined);
101  tot_log_like += fgmm.ComponentPosteriors(frame, &posterior);
102  for (int32 i = 0; i < posterior.Dim(); i++)
103  post[t].push_back(std::make_pair(i, posterior(i)));
104  }
105 
106  // The zeroth and 1st-order stats are in "utt_stats".
107  IvectorExtractorUtteranceStats utt_stats(num_gauss, feat_dim,
108  false);
109  utt_stats.AccStats(feats, post);
110 
111  OnlineIvectorEstimationStats online_stats(extractor.IvectorDim(),
112  extractor.PriorOffset(),
113  0.0);
114 
115  for (int32 t = 0; t < num_frames; t++) {
116  online_stats.AccStats(extractor, feats.Row(t), post[t]);
117  }
118 
119  Vector<double> ivector1(ivector_dim), ivector2(ivector_dim);
120 
121  extractor.GetIvectorDistribution(utt_stats, &ivector1, NULL);
122 
123  int32 num_cg_iters = -1; // for testing purposes, compute it exactly.
124  online_stats.GetIvector(num_cg_iters, &ivector2);
125 
126  KALDI_LOG << "ivector1 = " << ivector1;
127  KALDI_LOG << "ivector2 = " << ivector2;
128 
129  // objf change vs. default iVector. note, here I'm using objf
130  // and auxf pretty much interchangeably :-(
131  double objf_change2 = online_stats.ObjfChange(ivector2) *
132  utt_stats.NumFrames();
133 
134  Vector<double> ivector_baseline(ivector_dim);
135  ivector_baseline(0) = extractor.PriorOffset();
136  double objf_change1 = extractor.GetAuxf(utt_stats, ivector1) -
137  extractor.GetAuxf(utt_stats, ivector_baseline);
138  KALDI_LOG << "objf_change1 = " << objf_change1
139  << ", objf_change2 = " << objf_change2;
140 
141  KALDI_ASSERT(ivector1.ApproxEqual(ivector2));
142 }
double PriorOffset() const
The distribution over iVectors, in our formulation, is not centered at zero; its first dimension has ...
BaseFloat ComponentPosteriors(const VectorBase< BaseFloat > &data, VectorBase< BaseFloat > *posterior) const
Computes the posterior probabilities of all Gaussian components given a data point.
Definition: full-gmm.cc:719
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
bool IvectorDependentWeights() const
double GetAuxf(const IvectorExtractorUtteranceStats &utt_stats, const VectorBase< double > &mean, const SpMatrix< double > *var=NULL) const
Returns the log-likelihood objective function, summed over frames, for this distribution of iVectors ...
kaldi::int32 int32
This class helps us to efficiently estimate iVectors in situations where the data is coming in frame ...
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
int32 NumGauss() const
Returns the number of mixture components in the GMM.
Definition: full-gmm.h:58
void GetIvectorDistribution(const IvectorExtractorUtteranceStats &utt_stats, VectorBase< double > *mean, SpMatrix< double > *var) const
Gets the distribution over ivectors (or at least, a Gaussian approximation to it).
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
These are the stats for a particular utterance, i.e.
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ TestIvectorExtractorIO()

void kaldi::TestIvectorExtractorIO ( const IvectorExtractor extractor)

Definition at line 28 of file ivector-extractor-test.cc.

References KALDI_ASSERT, Rand(), IvectorExtractor::Read(), and IvectorExtractor::Write().

Referenced by UnitTestIvectorExtractor().

28  {
29  std::ostringstream ostr;
30  bool binary = (Rand() % 2 == 0);
31  extractor.Write(ostr, binary);
32  std::istringstream istr(ostr.str());
33  IvectorExtractor extractor2;
34  extractor2.Read(istr, binary);
35  std::ostringstream ostr2;
36  extractor2.Write(ostr2, binary);
37  KALDI_ASSERT(ostr.str() == ostr2.str());
38 }
void Write(std::ostream &os, bool binary) const
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Read(std::istream &is, bool binary)

◆ TestIvectorExtractorStatsIO()

void kaldi::TestIvectorExtractorStatsIO ( IvectorExtractorStats stats)

Definition at line 39 of file ivector-extractor-test.cc.

References IvectorExtractorStats::Add(), KALDI_ASSERT, Rand(), IvectorExtractorStats::Read(), and IvectorExtractorStats::Write().

Referenced by UnitTestIvectorExtractor().

39  {
40  std::ostringstream ostr;
41  bool binary = (Rand() % 2 == 0);
42  stats.Write(ostr, binary);
43  std::istringstream istr(ostr.str());
44  IvectorExtractorStats stats2;
45  stats2.Read(istr, binary);
46  std::ostringstream ostr2;
47  stats2.Write(ostr2, binary);
48 
49  if (binary) {
50  // this was failing in text mode, due to differences like
51  // 8.2244e+06 vs 8.22440e+06
52  KALDI_ASSERT(ostr.str() == ostr2.str());
53  }
54 
55  { // Test I/O of IvectorExtractorStats and that it works identically with the "add"
56  // mechanism. We only test this with binary == true; otherwise it's not
57  // identical due to limited precision.
58  std::ostringstream ostr;
59  bool binary = true;
60  stats.Write(ostr, binary);
61  IvectorExtractorStats stats2;
62  {
63  std::istringstream istr(ostr.str());
64  stats2.Read(istr, binary);
65  }
66  {
67  std::istringstream istr(ostr.str());
68  stats2.Read(istr, binary, true); // add to existing.
69  }
70  IvectorExtractorStats stats3(stats);
71  stats3.Add(stats);
72 
73  std::ostringstream ostr2;
74  stats2.Write(ostr2, false);
75 
76  std::ostringstream ostr3;
77  stats3.Write(ostr3, false);
78 
79  //if (binary) {
80  // KALDI_ASSERT(ostr2.str() == ostr3.str());
81  //}
82  }
83 }
IvectorExtractorStats is a class used to update the parameters of the ivector extractor.
void Read(std::istream &is, bool binary, bool add=false)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Write(std::ostream &os, bool binary)

◆ TestLatticeTable()

void kaldi::TestLatticeTable ( bool  binary)

Definition at line 99 of file kaldi-lattice-test.cc.

References TableWriter< Holder >::Close(), rnnlm::i, KALDI_ASSERT, RandLattice(), RandomAccessTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

99  {
100  LatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
101  int N = 10;
102  std::vector<Lattice*> lat_vec(N);
103  for (int i = 0; i < N; i++) {
104  char buf[2];
105  buf[0] = '0' + i;
106  buf[1] = '\0';
107  std::string key = "key" + std::string(buf);
108  Lattice *fst = RandLattice();
109  lat_vec[i] = fst;
110  writer.Write(key, *fst);
111  }
112  writer.Close();
113 
114  RandomAccessLatticeReader reader("ark:tmpf");
115  for (int i = 0; i < N; i++) {
116  char buf[2];
117  buf[0] = '0' + i;
118  buf[1] = '\0';
119  std::string key = "key" + std::string(buf);
120  const Lattice &fst = reader.Value(key);
121  KALDI_ASSERT(fst::Equal(fst, *(lat_vec[i])));
122  delete lat_vec[i];
123  }
124 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Lattice * RandLattice()

◆ TestLatticeTableCross()

void kaldi::TestLatticeTableCross ( bool  binary)

Definition at line 128 of file kaldi-lattice-test.cc.

References TableWriter< Holder >::Close(), fst::ConvertLattice(), rnnlm::i, KALDI_ASSERT, Rand(), RandLattice(), RandomAccessTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

128  {
129  LatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
130  int N = 10;
131  std::vector<Lattice*> lat_vec(N);
132  for (int i = 0; i < N; i++) {
133  char buf[2];
134  buf[0] = '0' + i;
135  buf[1] = '\0';
136  std::string key = "key" + std::string(buf);
137  Lattice *fst = RandLattice();
138  lat_vec[i] = fst;
139  writer.Write(key, *fst);
140  }
141  writer.Close();
142 
143  RandomAccessCompactLatticeReader reader("ark:tmpf");
144  for (int i = 0; i < N; i++) {
145  char buf[2];
146  buf[0] = '0' + i;
147  buf[1] = '\0';
148  std::string key = "key" + std::string(buf);
149  const CompactLattice &fst = reader.Value(key);
150  Lattice fst2;
151  ConvertLattice(fst, &fst2);
152  KALDI_ASSERT(fst::RandEquivalent(fst2, *(lat_vec[i]), 5, 0.01, Rand(), 10));
153  delete lat_vec[i];
154  }
155 }
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Lattice * RandLattice()

◆ TestLevenshteinAlignment()

void kaldi::TestLevenshteinAlignment ( )

Definition at line 231 of file edit-distance-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, LevenshteinAlignment(), LevenshteinEditDistance(), and Rand().

Referenced by main().

231  {
232  for (size_t i = 0; i < 100; i++) {
233  size_t a_sz = Rand() % 5, b_sz = Rand() % 5;
234  std::vector<int32> a, b;
235  for (size_t j = 0; j < a_sz; j++) a.push_back(Rand() % 10);
236  for (size_t j = 0; j < b_sz; j++) b.push_back(Rand() % 10);
237  int32 eps_sym = -1;
238  std::vector<std::pair<int32, int32> > ans;
239 
240  int32 e1 = LevenshteinEditDistance(a, b),
241  e2 = LevenshteinAlignment(a, b, eps_sym, &ans);
242  KALDI_ASSERT(e1 == e2);
243 
244  std::vector<int32> a2, b2;
245  for (size_t i = 0; i < ans.size(); i++) {
246  if (ans[i].first != eps_sym) a2.push_back(ans[i].first);
247  if (ans[i].second != eps_sym) b2.push_back(ans[i].second);
248  }
249  KALDI_ASSERT(a == a2);
250  KALDI_ASSERT(b == b2);
251  }
252 }
int32 LevenshteinAlignment(const std::vector< T > &a, const std::vector< T > &b, T eps_symbol, std::vector< std::pair< T, T > > *output)
kaldi::int32 int32
int32 LevenshteinEditDistance(const std::vector< T > &a, const std::vector< T > &b)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestLocateSymbolRange()

void kaldi::TestLocateSymbolRange ( )

Definition at line 52 of file kaldi-error-test.cc.

References VerifySymbolRange().

Referenced by main().

52  {
53  VerifySymbolRange("", false, "");
55  R"TRACE(./kaldi-error-test(_ZN5kaldi13UnitTestErrorEv+0xb) [0x804965d])TRACE",
56  true, "_ZN5kaldi13UnitTestErrorEv");
57  // It is ok thread_start is not found because it is a C symbol.
59  R"TRACE(31 libsystem_pthread.dylib 0x00007fff6fe4e40d thread_start + 13)TRACE",
60  false, "");
62  R"TRACE(0 server 0x000000010f67614d _ZNK5kaldi13MessageLogger10LogMessageEv + 813)TRACE",
63  true, "_ZNK5kaldi13MessageLogger10LogMessageEv");
65  R"TRACE(29 libsystem_pthread.dylib 0x00007fff6fe4f2eb _pthread_body + 126)TRACE",
66  true, "_pthread_body");
67 }
void VerifySymbolRange(const std::string &trace, const bool want_found, const std::string &want_symbol)

◆ TestMergePairVectorSumming()

void kaldi::TestMergePairVectorSumming ( )

Definition at line 220 of file stl-utils-test.cc.

References rnnlm::i, IsSorted(), KALDI_ASSERT, MergePairVectorSumming(), and Rand().

Referenced by main().

220  {
221  for (int p = 0; p < 100; p++) {
222  std::vector<std::pair<int32, int16> > v;
223  std::map<int32, int16> m;
224  int sz = Rand() % 10;
225  for (size_t i = 0; i < sz; i++) {
226  int32 key = Rand() % 10;
227  int16 val = (Rand() % 5) - 2;
228  v.push_back(std::make_pair(key, val));
229  if (m.count(key) == 0) m[key] = val;
230  else
231  m[key] += val;
232  }
235  for (size_t i = 0; i < v.size(); i++) {
236  KALDI_ASSERT(v[i].second == m[v[i].first]);
237  KALDI_ASSERT(v[i].second != 0.0);
238  if (i > 0) KALDI_ASSERT(v[i].first > v[i-1].first);
239  }
240  for (std::map<int32, int16>::const_iterator iter = m.begin();
241  iter != m.end(); ++iter) {
242  if (iter->second != 0) {
243  size_t i;
244  for (i = 0; i < v.size(); i++)
245  if (v[i].first == iter->first) break;
246  KALDI_ASSERT(i != v.size()); // Or we didn't find this
247  // key in v.
248  }
249  }
250  }
251 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
bool IsSorted(const std::vector< T > &vec)
Returns true if the vector is sorted.
Definition: stl-utils.h:47
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void MergePairVectorSumming(std::vector< std::pair< I, F > > *vec)
For a vector of pair<I, F> where I is an integer and F a floating-point or integer type...
Definition: stl-utils.h:288

◆ TestMinimizeCompactLattice()

void kaldi::TestMinimizeCompactLattice ( )

Definition at line 47 of file minimize-lattice-test.cc.

References KALDI_ASSERT, fst::MinimizeCompactLattice(), fst::PushCompactLatticeStrings(), fst::PushCompactLatticeWeights(), Rand(), and RandDeterministicCompactLattice().

Referenced by main().

47  {
49  CompactLattice clat2(*clat);
50  BaseFloat delta = (Rand() % 2 == 0 ? 1.0 : 1.0e-05);
51 
52  // Minimization will only work well on determinized and pushed lattices.
55 
56  MinimizeCompactLattice(&clat2, delta);
57  KALDI_ASSERT(fst::RandEquivalent(*clat, clat2, 5, delta, Rand(), 10));
58 
59  delete clat;
60 }
CompactLattice * RandDeterministicCompactLattice()
bool PushCompactLatticeStrings(MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, IntType > > > *clat)
This function pushes the transition-ids as far towards the start as they will go. ...
bool PushCompactLatticeWeights(MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, IntType > > > *clat)
This function pushes the weights in the CompactLattice so that all states except possibly the start s...
float BaseFloat
Definition: kaldi-types.h:29
bool MinimizeCompactLattice(MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, IntType > > > *clat, float delta)
This function minimizes the compact lattice.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestMonophoneContextDependency()

void kaldi::TestMonophoneContextDependency ( )

Definition at line 56 of file context-dep-test.cc.

References CopySetToVector(), ContextDependency::GetPdfInfo(), rnnlm::i, KALDI_ASSERT, MonophoneContextDependency(), and Rand().

Referenced by main().

56  {
57  std::set<int32> phones_set;
58  for (size_t i = 1; i <= 20; i++) phones_set.insert(1 + Rand() % 30);
59  std::vector<int32> phones;
60  CopySetToVector(phones_set, &phones);
61  std::vector<int32> phone2num_classes(1 + *std::max_element(phones.begin(), phones.end()));
62  for (size_t i = 0; i < phones.size(); i++)
63  phone2num_classes[phones[i]] = 3;
64  ContextDependency *cd = MonophoneContextDependency(phones,
65  phone2num_classes);
66 
67  std::vector<std::vector<std::pair<int32, int32> > > pdf_info;
68  cd->GetPdfInfo(phones, phone2num_classes, &pdf_info);
69  KALDI_ASSERT(pdf_info.size() == phones.size() * 3 &&
70  pdf_info[Rand() % pdf_info.size()].size() == 1);
71  delete cd;
72 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
ContextDependency * MonophoneContextDependency(const std::vector< int32 > &phones, const std::vector< int32 > &phone2num_pdf_classes)
Definition: context-dep.cc:331
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestNan()

void kaldi::TestNan ( )

Definition at line 236 of file text-utils-test.cc.

References ConvertStringToReal(), rnnlm::d, and KALDI_ASSERT.

236  {
237  Real d;
238  KALDI_ASSERT(ConvertStringToReal(std::to_string(sqrt(-1)), &d) && d != d);
239 }
bool ConvertStringToReal(const std::string &str, T *out)
ConvertStringToReal converts a string into either float or double and returns false if there was any ...
Definition: text-utils.cc:238
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestObjfMinus()

static void kaldi::TestObjfMinus ( )
static

Definition at line 107 of file cluster-utils-test.cc.

References AssertEqual(), and ScalarClusterable::Objf().

Referenced by main().

107  {
108  ScalarClusterable a(1.0), b(2.5);
109  AssertEqual(a.Objf(), 0.0);
110  AssertEqual(b.Objf(), 0.0);
111  a.Add(b);
112  AssertEqual(a.ObjfMinus(b), 0.0);
113  a.Add(b);
114  AssertEqual(a.ObjfMinus(b), -0.5 * (1.0-2.5)*(1.0-2.5));
115 }
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
ScalarClusterable clusters scalars with x^2 loss.

◆ TestObjfPlus()

static void kaldi::TestObjfPlus ( )
static

Definition at line 95 of file cluster-utils-test.cc.

References AssertEqual(), KALDI_LOG, and ScalarClusterable::Objf().

Referenced by main().

95  {
96  ScalarClusterable a(1.0), b(2.5);
97  AssertEqual(a.Objf(), (BaseFloat)0.0);
98  AssertEqual(b.Objf(), (BaseFloat)0.0);
99  AssertEqual( a.ObjfPlus(b), -0.5 * (1.0-2.5)*(1.0-2.5)); // 0.5 because half-distance, squared = 1/4, times two points...
100  KALDI_LOG << "Non-binary Output:";
101  a.Write(std::cerr, false);
102  std::cerr << "\nBinary Output:\n";
103  a.Write(std::cerr, true);
104  std::cerr << "\n";
105 }
float BaseFloat
Definition: kaldi-types.h:29
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
ScalarClusterable clusters scalars with x^2 loss.

◆ TestOnlineAppendFeature()

void kaldi::TestOnlineAppendFeature ( )

Definition at line 290 of file online-feature-test.cc.

References OnlineGenericBaseFeature< C >::AcceptWaveform(), OfflineFeatureTpl< F >::Compute(), WaveData::Data(), FrameExtractionOptions::dither, MfccOptions::frame_opts, PlpOptions::frame_opts, GetOutput(), PlpOptions::htk_compat, rnnlm::i, OnlineGenericBaseFeature< C >::InputFinished(), rnnlm::j, KALDI_ASSERT, MelBanksOptions::low_freq, PlpOptions::mel_opts, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), FrameExtractionOptions::preemph_coeff, RandomSplit(), WaveData::Read(), FrameExtractionOptions::remove_dc_offset, FrameExtractionOptions::round_to_power_of_two, FrameExtractionOptions::samp_freq, WaveData::SampFreq(), PlpOptions::use_energy, and FrameExtractionOptions::window_type.

Referenced by main().

290  {
291  std::ifstream is("../feat/test_data/test.wav", std::ios_base::binary);
292  WaveData wave;
293  wave.Read(is);
294  KALDI_ASSERT(wave.Data().NumRows() == 1);
295  SubVector<BaseFloat> waveform(wave.Data(), 0);
296 
297  // the parametrization object for 1st stream mfcc feature
298  MfccOptions mfcc_op;
299  mfcc_op.frame_opts.dither = 0.0;
300  mfcc_op.frame_opts.preemph_coeff = 0.0;
301  mfcc_op.frame_opts.window_type = "hamming";
302  mfcc_op.frame_opts.remove_dc_offset = false;
303  mfcc_op.frame_opts.round_to_power_of_two = true;
304  mfcc_op.frame_opts.samp_freq = wave.SampFreq();
305  mfcc_op.mel_opts.low_freq = 0.0;
306  mfcc_op.htk_compat = false;
307  mfcc_op.use_energy = false; // C0 not energy.
308  Mfcc mfcc(mfcc_op);
309 
310  // compute mfcc offline
311  Matrix<BaseFloat> mfcc_feats;
312  mfcc.Compute(waveform, 1.0, &mfcc_feats); // vtln not supported
313 
314  // the parametrization object for 2nd stream plp feature
315  PlpOptions plp_op;
316  plp_op.frame_opts.dither = 0.0;
317  plp_op.frame_opts.preemph_coeff = 0.0;
318  plp_op.frame_opts.window_type = "hamming";
319  plp_op.frame_opts.remove_dc_offset = false;
320  plp_op.frame_opts.round_to_power_of_two = true;
321  plp_op.frame_opts.samp_freq = wave.SampFreq();
322  plp_op.mel_opts.low_freq = 0.0;
323  plp_op.htk_compat = false;
324  plp_op.use_energy = false; // C0 not energy.
325  Plp plp(plp_op);
326 
327  // compute plp offline
328  Matrix<BaseFloat> plp_feats;
329  plp.Compute(waveform, 1.0, &plp_feats); // vtln not supported
330 
331  // compare
332  // The test waveform is about 1.44s long, so
333  // we try to break it into from 5 pieces to 9(not essential to do so)
334  for (int32 num_piece = 5; num_piece < 10; num_piece++) {
335  OnlineMfcc online_mfcc(mfcc_op);
336  OnlinePlp online_plp(plp_op);
337  OnlineAppendFeature online_mfcc_plp(&online_mfcc, &online_plp);
338 
339  std::vector<int32> piece_length(num_piece);
340  bool ret = RandomSplit(waveform.Dim(), &piece_length, num_piece);
341  KALDI_ASSERT(ret);
342  int32 offset_start = 0;
343  for (int32 i = 0; i < num_piece; i++) {
344  Vector<BaseFloat> wave_piece(
345  waveform.Range(offset_start, piece_length[i]));
346  online_mfcc.AcceptWaveform(wave.SampFreq(), wave_piece);
347  online_plp.AcceptWaveform(wave.SampFreq(), wave_piece);
348  offset_start += piece_length[i];
349  }
350  online_mfcc.InputFinished();
351  online_plp.InputFinished();
352 
353  Matrix<BaseFloat> online_mfcc_plp_feats;
354  GetOutput(&online_mfcc_plp, &online_mfcc_plp_feats);
355 
356  // compare mfcc_feats & plp_features with online_mfcc_plp_feats
357  KALDI_ASSERT(mfcc_feats.NumRows() == online_mfcc_plp_feats.NumRows()
358  && plp_feats.NumRows() == online_mfcc_plp_feats.NumRows()
359  && mfcc_feats.NumCols() + plp_feats.NumCols()
360  == online_mfcc_plp_feats.NumCols());
361  for (MatrixIndexT i = 0; i < online_mfcc_plp_feats.NumRows(); i++) {
362  for (MatrixIndexT j = 0; j < mfcc_feats.NumCols(); j++) {
363  KALDI_ASSERT(std::abs(mfcc_feats(i, j) - online_mfcc_plp_feats(i, j))
364  < 0.0001*std::max(1.0, static_cast<double>(std::abs(mfcc_feats(i, j))
365  + std::abs(online_mfcc_plp_feats(i, j)))));
366  }
367  for (MatrixIndexT k = 0; k < plp_feats.NumCols(); k++) {
368  KALDI_ASSERT(
369  std::abs(plp_feats(i, k) -
370  online_mfcc_plp_feats(i, mfcc_feats.NumCols() + k))
371  < 0.0001*std::max(1.0, static_cast<double>(std::abs(plp_feats(i, k))
372  +std::abs(online_mfcc_plp_feats(i, mfcc_feats.NumCols() + k)))));
373  }
374  }
375  }
376 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
MfccOptions contains basic options for computing MFCC features.
Definition: feature-mfcc.h:38
void GetOutput(OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
kaldi::int32 int32
BaseFloat SampFreq() const
Definition: wave-reader.h:126
MelBanksOptions mel_opts
Definition: feature-plp.h:44
const Matrix< BaseFloat > & Data() const
Definition: wave-reader.h:124
int32 MatrixIndexT
Definition: matrix-common.h:98
This online-feature class implements combination of two feature streams (such as pitch, plp) into one stream.
FrameExtractionOptions frame_opts
Definition: feature-plp.h:43
FrameExtractionOptions frame_opts
Definition: feature-mfcc.h:39
bool RandomSplit(int32 wav_dim, std::vector< int32 > *piece_dim, int32 num_pieces, int32 trials=5)
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
PlpOptions contains basic options for computing PLP features.
Definition: feature-plp.h:42
This templated class is intended for offline feature extraction, i.e.
This is a templated class for online feature extraction; it&#39;s templated on a class like MfccComputer ...
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ TestOnlineCmnInput()

void kaldi::TestOnlineCmnInput ( )

Definition at line 193 of file online-feat-test.cc.

References VectorBase< Real >::AddRowSumMat(), VectorBase< Real >::AddVec(), MatrixBase< Real >::ApproxEqual(), OnlineCacheInput::GetCachedData(), GetOutput(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::Row(), MatrixBase< Real >::SetRandn(), and VectorBase< Real >::SetZero().

Referenced by main().

193  { // We're also testing OnlineCacheInput here.
194  int32 dim = 2 + Rand() % 5; // dimension of features.
195  int32 num_frames = 10 + Rand() % 10;
196 
197  Matrix<BaseFloat> input_feats(num_frames, dim);
198  input_feats.SetRandn();
199 
200  OnlineMatrixInput matrix_input(input_feats);
201  int32 cmn_window = 10 + Rand() % 20;
202  int32 min_window = 1 + Rand() % (cmn_window - 1);
203  if (Rand() % 3 == 0) min_window = cmn_window;
204 
205  OnlineCmnInput cmn_input(&matrix_input, cmn_window,
206  min_window);
207  OnlineCacheInput cache_input(&cmn_input);
208 
209  Matrix<BaseFloat> output_feats1;
210  GetOutput(&cache_input, &output_feats1);
211 
212  Matrix<BaseFloat> output_feats2(input_feats);
213  for (int32 i = 0; i < output_feats2.NumRows(); i++) {
214  SubVector<BaseFloat> this_row(output_feats2, i);
215  if (i == 0 && min_window == 0) this_row.SetZero();
216  else if (i < min_window) {
217  int32 window_nframes = std::min(min_window, input_feats.NumRows());
218  Vector<BaseFloat> this_sum(dim);
219  SubMatrix<BaseFloat> this_block(input_feats, 0, window_nframes,
220  0, dim);
221  this_sum.AddRowSumMat(1.0, this_block, 0.0);
222  this_row.AddVec(-1.0 / window_nframes, this_sum);
223  } else {
224  int32 window_nframes = std::min(i, cmn_window);
225  Vector<BaseFloat> this_sum(dim);
226  SubMatrix<BaseFloat> this_block(input_feats, i - window_nframes, window_nframes,
227  0, dim);
228  this_sum.AddRowSumMat(1.0, this_block, 0.0);
229  this_row.AddVec(-1.0 / window_nframes, this_sum);
230  }
231  }
232  KALDI_ASSERT(output_feats1.NumRows() == output_feats2.NumRows());
233  for (int32 i = 0; i < output_feats2.NumRows(); i++) {
234  if (!output_feats1.Row(i).ApproxEqual(output_feats2.Row(i))) {
235  KALDI_ERR << "Rows differ " << i << ", " << input_feats.Row(i) << output_feats1.Row(i)
236  << output_feats2.Row(i);
237  }
238  }
239  KALDI_ASSERT(output_feats1.ApproxEqual(output_feats2));
240  Matrix<BaseFloat> output_feats3;
241  cache_input.GetCachedData(&output_feats3);
242  KALDI_ASSERT(output_feats1.ApproxEqual(output_feats3));
243 }
bool ApproxEqual(const MatrixBase< Real > &other, float tol=0.01) const
Returns true if ((*this)-other).FrobeniusNorm() <= tol * (*this).FrobeniusNorm(). ...
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
Sub-matrix representation.
Definition: kaldi-matrix.h:988
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
void GetOutput(OnlineFeatInputItf *a, Matrix< BaseFloat > *output)

◆ TestOnlineDeltaFeature()

void kaldi::TestOnlineDeltaFeature ( )

Definition at line 97 of file online-feature-test.cc.

References MatrixBase< Real >::ApproxEqual(), ComputeDeltas(), GetOutput(), KALDI_ASSERT, DeltaFeaturesOptions::order, and DeltaFeaturesOptions::window.

Referenced by main().

97  {
98  int32 dim = 2 + rand() % 5; // dimension of features.
99  int32 num_frames = 100 + rand() % 100;
101  opts.order = rand() % 3;
102  opts.window = 1 + rand() % 3;
103 
104  int32 output_dim = dim * (1 + opts.order);
105 
106  Matrix<BaseFloat> input_feats(num_frames, dim);
107  input_feats.SetRandn();
108 
109  OnlineMatrixFeature matrix_feats(input_feats);
110  OnlineDeltaFeature delta_feats(opts, &matrix_feats);
111 
112  Matrix<BaseFloat> output_feats1;
113  GetOutput(&delta_feats, &output_feats1);
114 
115  Matrix<BaseFloat> output_feats2(num_frames, output_dim);
116  ComputeDeltas(opts, input_feats, &output_feats2);
117 
118  KALDI_ASSERT(output_feats1.ApproxEqual(output_feats2));
119 }
This class takes a Matrix<BaseFloat> and wraps it as an OnlineFeatureInterface: this can be useful wh...
void GetOutput(OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
bool ApproxEqual(const MatrixBase< Real > &other, float tol=0.01) const
Returns true if ((*this)-other).FrobeniusNorm() <= tol * (*this).FrobeniusNorm(). ...
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void ComputeDeltas(const DeltaFeaturesOptions &delta_opts, const MatrixBase< BaseFloat > &input_features, Matrix< BaseFloat > *output_features)

◆ TestOnlineDeltaInput()

void kaldi::TestOnlineDeltaInput ( )

Definition at line 168 of file online-feat-test.cc.

References MatrixBase< Real >::ApproxEqual(), ComputeDeltas(), GetOutput(), KALDI_ASSERT, DeltaFeaturesOptions::order, Rand(), and DeltaFeaturesOptions::window.

Referenced by main().

168  {
169  int32 dim = 2 + Rand() % 5; // dimension of features.
170  int32 num_frames = 100 + Rand() % 100;
172  opts.order = Rand() % 3;
173  opts.window = 1 + Rand() % 3;
174 
175  int32 output_dim = dim * (1 + opts.order);
176 
177  Matrix<BaseFloat> input_feats(num_frames, dim);
178  input_feats.SetRandn();
179 
180  OnlineMatrixInput matrix_input(input_feats);
181  OnlineDeltaInput delta_input(opts, &matrix_input);
182 
183  Matrix<BaseFloat> output_feats1;
184  GetOutput(&delta_input, &output_feats1);
185 
186  Matrix<BaseFloat> output_feats2(num_frames, output_dim);
187  ComputeDeltas(opts, input_feats, &output_feats2);
188 
189  KALDI_ASSERT(output_feats1.ApproxEqual(output_feats2));
190 }
bool ApproxEqual(const MatrixBase< Real > &other, float tol=0.01) const
Returns true if ((*this)-other).FrobeniusNorm() <= tol * (*this).FrobeniusNorm(). ...
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void ComputeDeltas(const DeltaFeaturesOptions &delta_opts, const MatrixBase< BaseFloat > &input_features, Matrix< BaseFloat > *output_features)
void GetOutput(OnlineFeatInputItf *a, Matrix< BaseFloat > *output)

◆ TestOnlineFeatureMatrix()

void kaldi::TestOnlineFeatureMatrix ( )

Definition at line 110 of file online-feat-test.cc.

References OnlineFeatureMatrix::GetFrame(), OnlineFeatureMatrix::IsValidFrame(), KALDI_ASSERT, OnlineFeatureMatrixOptions::num_tries, Rand(), MatrixBase< Real >::Row(), and MatrixBase< Real >::SetRandn().

Referenced by main().

110  {
111  int32 dim = 2 + Rand() % 5; // dimension of features.
112  int32 num_frames = 100 + Rand() % 100;
113 
114  Matrix<BaseFloat> input_feats(num_frames, dim);
115  input_feats.SetRandn();
116 
117  OnlineMatrixInput matrix_input(input_feats);
119  opts.num_tries = 100; // makes it very unlikely we'll get that many timeouts.
120  OnlineFeatureMatrix online_feature_matrix(opts, &matrix_input);
121 
122  for (int32 frame = 0; frame < num_frames; frame++) {
123  KALDI_ASSERT(online_feature_matrix.IsValidFrame(frame));
124  KALDI_ASSERT(online_feature_matrix.GetFrame(frame).ApproxEqual(input_feats.Row(frame)));
125  }
126  KALDI_ASSERT(!online_feature_matrix.IsValidFrame(num_frames));
127 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestOnlineLdaInput()

void kaldi::TestOnlineLdaInput ( )

Definition at line 131 of file online-feat-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::ApproxEqual(), VectorBase< Real >::CopyColFromMat(), GetOutput(), KALDI_ASSERT, kNoTrans, kTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::SetRandn(), and SpliceFrames().

Referenced by main().

131  {
132  int32 dim = 2 + Rand() % 5; // dimension of features.
133  int32 num_frames = 100 + Rand() % 100;
134  int32 left_context = Rand() % 3, right_context = Rand() % 3;
135  bool have_offset = (Rand() % 2 == 0);
136  int32 lda_input_dim = (dim * (left_context + 1 + right_context)),
137  lda_output_dim = 1 + Rand() % 5; // this can even be more than
138  // the input dim, the class doesn't care.
139 
140  Matrix<BaseFloat> transform(lda_output_dim, lda_input_dim +
141  (have_offset ? 1 : 0));
142  transform.SetRandn();
143  Matrix<BaseFloat> input_feats(num_frames, dim);
144  input_feats.SetRandn();
145 
146  OnlineMatrixInput matrix_input(input_feats);
147  OnlineLdaInput lda_input(&matrix_input, transform, left_context, right_context);
148 
149  Matrix<BaseFloat> output_feats1;
150  GetOutput(&lda_input, &output_feats1);
151  Matrix<BaseFloat> temp_feats;
152  SpliceFrames(input_feats, left_context, right_context, &temp_feats);
153  Matrix<BaseFloat> output_feats2(temp_feats.NumRows(), transform.NumRows());
154  if (!have_offset) {
155  output_feats2.AddMatMat(1.0, temp_feats, kNoTrans, transform, kTrans, 0.0);
156  } else {
157  SubMatrix<BaseFloat> linear_part(transform, 0, transform.NumRows(),
158  0, transform.NumCols() - 1);
159  output_feats2.AddMatMat(1.0, temp_feats, kNoTrans, linear_part, kTrans, 0.0);
160  Vector<BaseFloat> offset(transform.NumRows());
161  offset.CopyColFromMat(transform, transform.NumCols() - 1);
162  output_feats2.AddVecToRows(1.0, offset);
163  }
164  KALDI_ASSERT(output_feats1.ApproxEqual(output_feats2));
165 }
bool ApproxEqual(const MatrixBase< Real > &other, float tol=0.01) const
Returns true if ((*this)-other).FrobeniusNorm() <= tol * (*this).FrobeniusNorm(). ...
kaldi::int32 int32
void AddMatMat(const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void CopyColFromMat(const MatrixBase< OtherReal > &M, MatrixIndexT col)
Extracts a column of the matrix M.
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void SpliceFrames(const MatrixBase< BaseFloat > &input_features, int32 left_context, int32 right_context, Matrix< BaseFloat > *output_features)
Sub-matrix representation.
Definition: kaldi-matrix.h:988
void GetOutput(OnlineFeatInputItf *a, Matrix< BaseFloat > *output)

◆ TestOnlineMatrixCacheFeature()

void kaldi::TestOnlineMatrixCacheFeature ( )

Definition at line 83 of file online-feature-test.cc.

References AssertEqual(), GetOutput(), and MatrixBase< Real >::SetRandn().

Referenced by main().

83  {
84  int32 dim = 2 + rand() % 5; // dimension of features.
85  int32 num_frames = 100 + rand() % 100;
86 
87  Matrix<BaseFloat> input_feats(num_frames, dim);
88  input_feats.SetRandn();
89 
90  OnlineMatrixFeature matrix_feats(input_feats);
91 
92  Matrix<BaseFloat> output_feats;
93  GetOutput(&matrix_feats, &output_feats);
94  AssertEqual(input_feats, output_feats);
95 }
This class takes a Matrix<BaseFloat> and wraps it as an OnlineFeatureInterface: this can be useful wh...
void GetOutput(OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
kaldi::int32 int32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ TestOnlineMatrixInput()

void kaldi::TestOnlineMatrixInput ( )

Definition at line 96 of file online-feat-test.cc.

References AssertEqual(), GetOutput(), Rand(), and MatrixBase< Real >::SetRandn().

Referenced by main().

96  {
97  int32 dim = 2 + Rand() % 5; // dimension of features.
98  int32 num_frames = 100 + Rand() % 100;
99 
100  Matrix<BaseFloat> input_feats(num_frames, dim);
101  input_feats.SetRandn();
102 
103  OnlineMatrixInput matrix_input(input_feats);
104 
105  Matrix<BaseFloat> output_feats;
106  GetOutput(&matrix_input, &output_feats);
107  AssertEqual(input_feats, output_feats);
108 }
kaldi::int32 int32
static void AssertEqual(const Matrix< Real > &A, const Matrix< Real > &B, float tol=0.001)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void GetOutput(OnlineFeatInputItf *a, Matrix< BaseFloat > *output)

◆ TestOnlineMfcc()

void kaldi::TestOnlineMfcc ( )

Definition at line 146 of file online-feature-test.cc.

References OnlineGenericBaseFeature< C >::AcceptWaveform(), AssertEqual(), OfflineFeatureTpl< F >::Compute(), WaveData::Data(), FrameExtractionOptions::dither, MfccOptions::frame_opts, GetOutput(), rnnlm::i, OnlineGenericBaseFeature< C >::InputFinished(), KALDI_ASSERT, MatrixBase< Real >::NumRows(), RandInt(), RandomSplit(), WaveData::Read(), and WaveData::SampFreq().

Referenced by main().

146  {
147  std::ifstream is("../feat/test_data/test.wav", std::ios_base::binary);
148  WaveData wave;
149  wave.Read(is);
150  KALDI_ASSERT(wave.Data().NumRows() == 1);
151  SubVector<BaseFloat> waveform(wave.Data(), 0);
152 
153  // the parametrization object
154  MfccOptions op;
155  op.frame_opts.dither = 0.0;
156  op.frame_opts.preemph_coeff = 0.0;
157  op.frame_opts.window_type = "hamming";
158  op.frame_opts.remove_dc_offset = false;
159  op.frame_opts.round_to_power_of_two = true;
160  op.frame_opts.samp_freq = wave.SampFreq();
161  op.mel_opts.low_freq = 0.0;
162  op.htk_compat = false;
163  op.use_energy = false; // C0 not energy.
164  if (RandInt(0, 1) == 0)
165  op.frame_opts.snip_edges = false;
166  Mfcc mfcc(op);
167 
168  // compute mfcc offline
169  Matrix<BaseFloat> mfcc_feats;
170  mfcc.Compute(waveform, 1.0, &mfcc_feats); // vtln not supported
171 
172  // compare
173  // The test waveform is about 1.44s long, so
174  // we try to break it into from 5 pieces to 9(not essential to do so)
175  for (int32 num_piece = 5; num_piece < 10; num_piece++) {
176  OnlineMfcc online_mfcc(op);
177  std::vector<int32> piece_length(num_piece, 0);
178 
179  bool ret = RandomSplit(waveform.Dim(), &piece_length, num_piece);
180  KALDI_ASSERT(ret);
181 
182  int32 offset_start = 0;
183  for (int32 i = 0; i < num_piece; i++) {
184  Vector<BaseFloat> wave_piece(
185  waveform.Range(offset_start, piece_length[i]));
186  online_mfcc.AcceptWaveform(wave.SampFreq(), wave_piece);
187  offset_start += piece_length[i];
188  }
189  online_mfcc.InputFinished();
190 
191  Matrix<BaseFloat> online_mfcc_feats;
192  GetOutput(&online_mfcc, &online_mfcc_feats);
193 
194  AssertEqual(mfcc_feats, online_mfcc_feats);
195  }
196 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
MfccOptions contains basic options for computing MFCC features.
Definition: feature-mfcc.h:38
void GetOutput(OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
kaldi::int32 int32
BaseFloat SampFreq() const
Definition: wave-reader.h:126
const Matrix< BaseFloat > & Data() const
Definition: wave-reader.h:124
FrameExtractionOptions frame_opts
Definition: feature-mfcc.h:39
bool RandomSplit(int32 wav_dim, std::vector< int32 > *piece_dim, int32 num_pieces, int32 trials=5)
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
This templated class is intended for offline feature extraction, i.e.
This is a templated class for online feature extraction; it&#39;s templated on a class like MfccComputer ...
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestOnlinePlp()

void kaldi::TestOnlinePlp ( )

Definition at line 198 of file online-feature-test.cc.

References OnlineGenericBaseFeature< C >::AcceptWaveform(), AssertEqual(), OfflineFeatureTpl< F >::Compute(), WaveData::Data(), FrameExtractionOptions::dither, PlpOptions::frame_opts, GetOutput(), rnnlm::i, OnlineGenericBaseFeature< C >::InputFinished(), KALDI_ASSERT, MatrixBase< Real >::NumRows(), RandomSplit(), WaveData::Read(), and WaveData::SampFreq().

Referenced by main().

198  {
199  std::ifstream is("../feat/test_data/test.wav", std::ios_base::binary);
200  WaveData wave;
201  wave.Read(is);
202  KALDI_ASSERT(wave.Data().NumRows() == 1);
203  SubVector<BaseFloat> waveform(wave.Data(), 0);
204 
205  // the parametrization object
206  PlpOptions op;
207  op.frame_opts.dither = 0.0;
208  op.frame_opts.preemph_coeff = 0.0;
209  op.frame_opts.window_type = "hamming";
210  op.frame_opts.remove_dc_offset = false;
211  op.frame_opts.round_to_power_of_two = true;
212  op.frame_opts.samp_freq = wave.SampFreq();
213  op.mel_opts.low_freq = 0.0;
214  op.htk_compat = false;
215  op.use_energy = false; // C0 not energy.
216  Plp plp(op);
217 
218  // compute plp offline
219  Matrix<BaseFloat> plp_feats;
220  plp.Compute(waveform, 1.0, &plp_feats); // vtln not supported
221 
222  // compare
223  // The test waveform is about 1.44s long, so
224  // we try to break it into from 5 pieces to 9(not essential to do so)
225  for (int32 num_piece = 5; num_piece < 10; num_piece++) {
226  OnlinePlp online_plp(op);
227  std::vector<int32> piece_length(num_piece);
228  bool ret = RandomSplit(waveform.Dim(), &piece_length, num_piece);
229  KALDI_ASSERT(ret);
230 
231  int32 offset_start = 0;
232  for (int32 i = 0; i < num_piece; i++) {
233  Vector<BaseFloat> wave_piece(
234  waveform.Range(offset_start, piece_length[i]));
235  online_plp.AcceptWaveform(wave.SampFreq(), wave_piece);
236  offset_start += piece_length[i];
237  }
238  online_plp.InputFinished();
239 
240  Matrix<BaseFloat> online_plp_feats;
241  GetOutput(&online_plp, &online_plp_feats);
242 
243  AssertEqual(plp_feats, online_plp_feats);
244  }
245 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
void GetOutput(OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
kaldi::int32 int32
BaseFloat SampFreq() const
Definition: wave-reader.h:126
const Matrix< BaseFloat > & Data() const
Definition: wave-reader.h:124
FrameExtractionOptions frame_opts
Definition: feature-plp.h:43
bool RandomSplit(int32 wav_dim, std::vector< int32 > *piece_dim, int32 num_pieces, int32 trials=5)
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
PlpOptions contains basic options for computing PLP features.
Definition: feature-plp.h:42
This templated class is intended for offline feature extraction, i.e.
This is a templated class for online feature extraction; it&#39;s templated on a class like MfccComputer ...
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ TestOnlineSpliceFrames()

void kaldi::TestOnlineSpliceFrames ( )

Definition at line 121 of file online-feature-test.cc.

References MatrixBase< Real >::ApproxEqual(), GetOutput(), KALDI_ASSERT, OnlineSpliceOptions::left_context, OnlineSpliceOptions::right_context, and SpliceFrames().

Referenced by main().

121  {
122  int32 dim = 2 + rand() % 5; // dimension of features.
123  int32 num_frames = 100 + rand() % 100;
124  OnlineSpliceOptions opts;
125  opts.left_context = 1 + rand() % 4;
126  opts.right_context = 1 + rand() % 4;
127 
128  int32 output_dim = dim * (1 + opts.left_context + opts.right_context);
129 
130  Matrix<BaseFloat> input_feats(num_frames, dim);
131  input_feats.SetRandn();
132 
133  OnlineMatrixFeature matrix_feats(input_feats);
134  OnlineSpliceFrames splice_frame(opts, &matrix_feats);
135 
136  Matrix<BaseFloat> output_feats1;
137  GetOutput(&splice_frame, &output_feats1);
138 
139  Matrix<BaseFloat> output_feats2(num_frames, output_dim);
140  SpliceFrames(input_feats, opts.left_context, opts.right_context,
141  &output_feats2);
142 
143  KALDI_ASSERT(output_feats1.ApproxEqual(output_feats2));
144 }
This class takes a Matrix<BaseFloat> and wraps it as an OnlineFeatureInterface: this can be useful wh...
void GetOutput(OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
bool ApproxEqual(const MatrixBase< Real > &other, float tol=0.01) const
Returns true if ((*this)-other).FrobeniusNorm() <= tol * (*this).FrobeniusNorm(). ...
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void SpliceFrames(const MatrixBase< BaseFloat > &input_features, int32 left_context, int32 right_context, Matrix< BaseFloat > *output_features)

◆ TestOnlineTransform()

void kaldi::TestOnlineTransform ( )

Definition at line 247 of file online-feature-test.cc.

References OnlineGenericBaseFeature< C >::AcceptWaveform(), ApplyAffineTransform(), AssertEqual(), WaveData::Data(), OnlineGenericBaseFeature< C >::Dim(), FrameExtractionOptions::dither, MfccOptions::frame_opts, GetOutput(), rnnlm::i, OnlineGenericBaseFeature< C >::InputFinished(), KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), WaveData::Read(), MatrixBase< Real >::Row(), WaveData::SampFreq(), and MatrixBase< Real >::SetRandn().

Referenced by main().

247  {
248  std::ifstream is("../feat/test_data/test.wav", std::ios_base::binary);
249  WaveData wave;
250  wave.Read(is);
251  KALDI_ASSERT(wave.Data().NumRows() == 1);
252  SubVector<BaseFloat> waveform(wave.Data(), 0);
253 
254  // build online feature interface, take OnlineMfcc as an example
255  MfccOptions op;
256  op.frame_opts.dither = 0.0;
257  op.frame_opts.preemph_coeff = 0.0;
258  op.frame_opts.window_type = "hamming";
259  op.frame_opts.remove_dc_offset = false;
260  op.frame_opts.round_to_power_of_two = true;
261  op.frame_opts.samp_freq = wave.SampFreq();
262  op.mel_opts.low_freq = 0.0;
263  op.htk_compat = false;
264  op.use_energy = false; // C0 not energy.
265  OnlineMfcc online_mfcc(op);
266 
267  online_mfcc.AcceptWaveform(wave.SampFreq(), waveform);
268  online_mfcc.InputFinished();
269  Matrix<BaseFloat> mfcc_feats;
270  GetOutput(&online_mfcc, &mfcc_feats);
271 
272  // Affine transform
273  Matrix<BaseFloat> trans(online_mfcc.Dim(), online_mfcc.Dim() + 1);
274  trans.SetRandn();
275  OnlineTransform online_trans(trans, &online_mfcc);
276 
277  Matrix<BaseFloat> trans_feats;
278  GetOutput(&online_trans, &trans_feats);
279 
280  Matrix<BaseFloat> output_feats(mfcc_feats.NumRows(), mfcc_feats.NumCols());
281  for (int32 i = 0; i < mfcc_feats.NumRows(); i++) {
282  Vector<BaseFloat> vec_tmp(mfcc_feats.Row(i));
283  ApplyAffineTransform(trans, &vec_tmp);
284  output_feats.CopyRowFromVec(vec_tmp, i);
285  }
286 
287  AssertEqual(trans_feats, output_feats);
288 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
MfccOptions contains basic options for computing MFCC features.
Definition: feature-mfcc.h:38
void GetOutput(OnlineFeatureInterface *a, Matrix< BaseFloat > *output)
kaldi::int32 int32
BaseFloat SampFreq() const
Definition: wave-reader.h:126
const Matrix< BaseFloat > & Data() const
Definition: wave-reader.h:124
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
FrameExtractionOptions frame_opts
Definition: feature-mfcc.h:39
void SetRandn()
Sets to random values of a normal distribution.
This online-feature class implements any affine or linear transform.
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void ApplyAffineTransform(const MatrixBase< BaseFloat > &xform, VectorBase< BaseFloat > *vec)
Applies the affine transform &#39;xform&#39; to the vector &#39;vec&#39; and overwrites the contents of &#39;vec&#39;...
This is a templated class for online feature extraction; it&#39;s templated on a class like MfccComputer ...
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ TestPossibleValues()

void kaldi::TestPossibleValues ( )

Definition at line 38 of file build-tree-utils-test.cc.

References CopyMapToVector(), CopySetToVector(), rnnlm::i, rnnlm::j, KALDI_ASSERT, PossibleValues(), and RandInt().

Referenced by main().

38  {
39  BuildTreeStatsType stats;
40  std::map<EventKeyType, std::set<EventValueType> > all_key_vals;
41  for (size_t i = 0;i < 20;i++) {
42  std::map<EventKeyType, EventValueType> key_vals;
43  for (size_t j = 0;j < 20;j++) {
44  EventKeyType k = RandInt(-5, 10);
45  EventValueType v = RandInt(0, 10);
46  if (key_vals.count(k) == 0) {
47  key_vals[ k ] = v;
48  all_key_vals[k].insert(v);
49  }
50  }
51  EventType evec;
52  CopyMapToVector(key_vals, &evec);
53  stats.push_back(std::pair<EventType, Clusterable*>(evec, (Clusterable*)NULL));
54  }
55  for (std::map<EventKeyType, std::set<EventValueType> >::iterator iter = all_key_vals.begin();
56  iter != all_key_vals.end(); iter++) {
57  EventKeyType key = iter->first;
58  std::vector<EventValueType> vals1, vals2;
59  CopySetToVector(iter->second, &vals1);
60  PossibleValues(key, stats, &vals2);
61  if (vals1 != vals2) {
62  printf("vals differ!\n");
63  for (size_t i = 0;i < vals1.size();i++) std::cout << vals1[i] << " ";
64  std::cout<<'\n';
65  for (size_t i = 0;i < vals2.size();i++) std::cout << vals2[i] << " ";
66  std::cout<<'\n';
67  KALDI_ASSERT(0);
68  }
69  }
70 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
bool PossibleValues(EventKeyType key, const BuildTreeStatsType &stats, std::vector< EventValueType > *ans)
Convenience function e.g.
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
void CopyMapToVector(const std::map< A, B > &m, std::vector< std::pair< A, B > > *v)
Copies the (key, value) pairs in a map to a vector of pairs.
Definition: stl-utils.h:112
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestPosteriorIo()

void kaldi::TestPosteriorIo ( )

Definition at line 53 of file posterior-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, RandInt(), RandUniform(), ReadPosterior(), and WritePosterior().

Referenced by main().

53  {
54  int32 post_size = RandInt(0, 5);
55  post_size = post_size * post_size;
56  Posterior post(post_size);
57  for (int32 i = 0; i < post.size(); i++) {
58  int32 s = RandInt(0, 3);
59  for (int32 j = 0; j < s; j++)
60  post[i].push_back(std::pair<int32,BaseFloat>(
61  RandInt(-10, 100), RandUniform()));
62  }
63  bool binary = (RandInt(0, 1) == 0);
64  std::ostringstream os;
65  WritePosterior(os, binary, post);
66  Posterior post2;
67  if (RandInt(0, 1) == 0)
68  post2 = post;
69  std::istringstream is(os.str());
70  ReadPosterior(is, binary, &post2);
71  if (binary) {
72  KALDI_ASSERT(post == post2);
73  } else {
74  KALDI_ASSERT(post.size() == post2.size());
75  for (int32 i = 0; i < post.size(); i++) {
76  KALDI_ASSERT(post[i].size() == post2[i].size());
77  for (int32 j = 0; j < post[i].size(); j++) {
78  KALDI_ASSERT(post[i][j].first == post2[i][j].first &&
79  fabs(post[i][j].second - post2[i][j].second) < 0.01);
80  }
81  }
82  }
83 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void WritePosterior(std::ostream &os, bool binary, const Posterior &post)
stand-alone function for writing a Posterior.
Definition: posterior.cc:32
void ReadPosterior(std::istream &is, bool binary, Posterior *post)
stand-alone function for reading a Posterior.
Definition: posterior.cc:64
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestPushCompactLatticeStrings()

void kaldi::TestPushCompactLatticeStrings ( )

Definition at line 39 of file push-lattice-test.cc.

References KALDI_ASSERT, fst::PushCompactLatticeStrings(), Rand(), RandCompactLattice(), and CompactLatticeWeightTpl< WeightType, IntType >::Zero().

Referenced by main().

39  {
41  CompactLattice clat2(*clat);
43  KALDI_ASSERT(fst::RandEquivalent(*clat, clat2, 5, 0.001, Rand(), 10));
44  for (CompactLatticeArc::StateId s = 0; s < clat2.NumStates(); s++) {
45  if (s == 0)
46  continue; // We don't check state zero, as the "leftover string" stays
47  // there.
48  int32 first_label = -1;
49  bool ok = false;
50  bool first_label_set = false;
51  for (ArcIterator<CompactLattice> aiter(clat2, s); !aiter.Done();
52  aiter.Next()) {
53  if (aiter.Value().weight.String().size() == 0) {
54  ok = true;
55  } else {
56  int32 this_label = aiter.Value().weight.String().front();
57  if (first_label_set) {
58  if (this_label != first_label) ok = true;
59  } else {
60  first_label = this_label;
61  first_label_set = true;
62  }
63  }
64  }
65  if (clat2.Final(s) != CompactLatticeWeight::Zero()) {
66  if (clat2.Final(s).String().size() == 0) ok = true;
67  else {
68  int32 this_label = clat2.Final(s).String().front();
69  if (first_label_set && this_label != first_label) ok = true;
70  }
71  }
72  KALDI_ASSERT(ok);
73  }
74  delete clat;
75 }
fst::StdArc::StateId StateId
CompactLattice * RandCompactLattice()
bool PushCompactLatticeStrings(MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, IntType > > > *clat)
This function pushes the transition-ids as far towards the start as they will go. ...
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestPushCompactLatticeWeights()

void kaldi::TestPushCompactLatticeWeights ( )

Definition at line 77 of file push-lattice-test.cc.

References ApproxEqual(), KALDI_ASSERT, KALDI_ERR, LatticeWeightTpl< BaseFloat >::One(), fst::Plus(), fst::PushCompactLatticeWeights(), Rand(), and RandCompactLattice().

Referenced by main().

77  {
79  CompactLattice clat2(*clat);
81  KALDI_ASSERT(fst::RandEquivalent(*clat, clat2, 5, 0.001, Rand(), 10));
82  for (CompactLatticeArc::StateId s = 0; s < clat2.NumStates(); s++) {
83  if (s == 0)
84  continue; // We don't check state zero, as the "leftover string" stays
85  // there.
86  LatticeWeight sum = clat2.Final(s).Weight();
87  for (ArcIterator<CompactLattice> aiter(clat2, s); !aiter.Done();
88  aiter.Next()) {
89  sum = Plus(sum, aiter.Value().weight.Weight());
90  }
91  if (!ApproxEqual(sum, LatticeWeight::One())) {
92  {
93  fst::FstPrinter<CompactLatticeArc> printer(clat2, NULL, NULL,
94  NULL, true, true, "\t");
95  printer.Print(&std::cerr, "<unknown>");
96  }
97  {
98  fst::FstPrinter<CompactLatticeArc> printer(*clat, NULL, NULL,
99  NULL, true, true, "\t");
100  printer.Print(&std::cerr, "<unknown>");
101  }
102  KALDI_ERR << "Bad lattice being pushed.";
103  }
104  }
105  delete clat;
106 }
fst::StdArc::StateId StateId
LatticeWeightTpl< FloatType > Plus(const LatticeWeightTpl< FloatType > &w1, const LatticeWeightTpl< FloatType > &w2)
CompactLattice * RandCompactLattice()
bool PushCompactLatticeWeights(MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, IntType > > > *clat)
This function pushes the weights in the CompactLattice so that all states except possibly the start s...
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ TestQuestionsInitRand()

void kaldi::TestQuestionsInitRand ( )

Definition at line 640 of file build-tree-utils-test.cc.

References EventMap::Check(), CopySetToVector(), Questions::GetQuestionsOf(), Questions::HasQuestionsForKey(), rnnlm::i, QuestionsForKey::initial_questions, Questions::InitRand(), rnnlm::j, KALDI_ASSERT, KALDI_ERR, kAllKeysIntersection, kAllKeysUnion, Rand(), Questions::Read(), and Questions::Write().

Referenced by main().

640  {
641  // testing Questions::InitRand() function. Also testing I/O of Questions class.
642  for (int32 p = 0;p < 10;p++) {
643  std::vector<EventKeyType> keys_all, keys_some;
644  {
645  std::set<EventKeyType> keys_all_set, keys_some_set;
646  int32 num_all = Rand() % 3, num_some = Rand() % 3;
647  for (int32 i = 0;i < num_all;i++) keys_all_set.insert(Rand() % 10);
648  for (int32 i = 0;i < num_some;i++) {
649  int32 k = Rand() % 10;
650  if (keys_all_set.count(k) == 0) keys_some_set.insert(k);
651  }
652  CopySetToVector(keys_all_set, &keys_all);
653  CopySetToVector(keys_some_set, &keys_some);
654  }
655  std::set<EventKeyType> keys_all_saw_set;
656  // Now we have two distinct sets of keys keys_all and keys_some.
657  // We now create the Clusterable* stuff.
658  BuildTreeStatsType dummy_stats; // dummy because the Clusterable *pointers are actually NULL.
659  size_t n_stats = Rand() % 100;
660  // make sure we sometimes have empty or just one stats: may find extra bugs.
661  if (n_stats > 90) n_stats = 0;
662  if (n_stats > 80) n_stats = 1;
663 
664  for (size_t i = 0;i < n_stats;i++) { // Create stats...
665  EventType evec;
666  for (size_t j = 0;j < keys_all.size();j++) {
667  evec.push_back(std::make_pair( keys_all[j], (EventValueType)(Rand() % 10)));
668  keys_all_saw_set.insert(keys_all[j]);
669  }
670  for (size_t j = 0;j < keys_some.size();j++)
671  if (Rand() % 2 == 0) { // randomly w.p. 1/2
672  evec.push_back(std::make_pair( keys_some[j], (EventValueType)(Rand() % 10)));
673  keys_all_saw_set.insert(keys_some[j]);
674  }
675  std::sort(evec.begin(), evec.end()); // sorts on keys.
676  EventMap::Check(evec);
677  dummy_stats.push_back(std::make_pair(evec, (Clusterable*)NULL));
678  }
679  Questions qo; // all default.
680  bool intersection = (p%2 == 0);
681  int32 num_quest = Rand() % 10, num_iters = rand () % 5;
682  qo.InitRand(dummy_stats, num_quest, num_iters, intersection ? kAllKeysIntersection : kAllKeysUnion);
683 
684  for (int i = 0; i < 2; i++) {
685  // Here, test I/O of questions class.
686  bool binary = (i == 0);
687  std::ostringstream oss;
688  qo.Write(oss, binary);
689 
690  std::istringstream iss(oss.str());
691  Questions qo2;
692  qo2.Read(iss, binary);
693 
694  std::ostringstream oss2;
695  qo2.Write(oss2, binary);
696 
697  if (oss.str() != oss2.str()) {
698  KALDI_ERR << "Questions I/O failure: " << oss.str() << " vs. " << oss2.str();
699  }
700  }
701 
702  if (n_stats > 0) {
703  if (p < 2) {
704  for (size_t i = 0;i < keys_all.size();i++) {
705  KALDI_ASSERT(qo.HasQuestionsForKey(keys_all[i]));
706  const QuestionsForKey &opts = qo.GetQuestionsOf(keys_all[i]);
707  std::cout << "num-quest: "<< opts.initial_questions.size() << '\n';
708  for (size_t j = 0;j < opts.initial_questions.size();j++) {
709  for (size_t k = 0;k < opts.initial_questions[j].size();k++)
710  std::cout << opts.initial_questions[j][k] <<" ";
711  std::cout << '\n';
712  }
713  }
714  }
715  if (intersection) {
716  for (size_t i = 0;i < keys_all.size();i++) {
717  KALDI_ASSERT(qo.HasQuestionsForKey(keys_all[i]));
718  qo.GetQuestionsOf(keys_all[i]);
719  }
720  } else { // union: expect to see all keys that were in the data.
721  for (std::set<int32>::iterator iter = keys_all_saw_set.begin(); iter != keys_all_saw_set.end(); iter++) {
722  KALDI_ASSERT(qo.HasQuestionsForKey(*iter));
723  }
724  }
725  }
726  }
727 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
This class defines, for each EventKeyType, a set of initial questions that it tries and also a number...
const QuestionsForKey & GetQuestionsOf(EventKeyType key) const
kaldi::int32 int32
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
void InitRand(const BuildTreeStatsType &stats, int32 num_quest, int32 num_iters_refine, AllKeysType all_keys_type)
InitRand attempts to generate "reasonable" random questions.
QuestionsForKey is a class used to define the questions for a key, and also options that allow us to ...
std::vector< std::vector< EventValueType > > initial_questions
void Read(std::istream &is, bool binary)
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
bool HasQuestionsForKey(EventKeyType key) const
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
void Write(std::ostream &os, bool binary) const

◆ TestRecyclingVector()

void kaldi::TestRecyclingVector ( )

Definition at line 378 of file online-feature-test.cc.

References RecyclingVector::At(), rnnlm::i, KALDI_ASSERT, RecyclingVector::PushBack(), VectorBase< Real >::Set(), and RecyclingVector::Size().

Referenced by main().

378  {
379  RecyclingVector full_vec;
380  RecyclingVector shrinking_vec(10);
381  for (int i = 0; i != 100; ++i) {
382  Vector <BaseFloat> data(1);
383  data.Set(i);
384  full_vec.PushBack(new Vector<BaseFloat>(data));
385  shrinking_vec.PushBack(new Vector<BaseFloat>(data));
386  }
387  KALDI_ASSERT(full_vec.Size() == 100);
388  KALDI_ASSERT(shrinking_vec.Size() == 100);
389 
390  // full_vec should contain everything
391  for (int i = 0; i != 100; ++i) {
392  Vector <BaseFloat> *data = full_vec.At(i);
393  KALDI_ASSERT(data != nullptr);
394  KALDI_ASSERT((*data)(0) == static_cast<BaseFloat>(i));
395  }
396 
397  // shrinking_vec may throw an exception for the first 90 elements
398  int caught_exceptions = 0;
399  for (int i = 0; i != 90; ++i) {
400  try {
401  shrinking_vec.At(i);
402  } catch (const std::runtime_error &) {
403  ++caught_exceptions;
404  }
405  }
406  // it may actually store a bit more elements for performance efficiency considerations
407  KALDI_ASSERT(caught_exceptions >= 80);
408 
409  // shrinking_vec should contain the last 10 elements
410  for (int i = 90; i != 100; ++i) {
411  Vector <BaseFloat> *data = shrinking_vec.At(i);
412  KALDI_ASSERT(data != nullptr);
413  KALDI_ASSERT((*data)(0) == static_cast<BaseFloat>(i));
414  }
415 }
void PushBack(Vector< BaseFloat > *item)
The ownership of the item is passed to this collection - do not delete the item.
int Size() const
This method returns the size as if no "recycling" had happened, i.e.
This class serves as a storage for feature vectors with an option to limit the memory usage by removi...
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Vector< BaseFloat > * At(int index) const
The ownership is being retained by this collection - do not delete the item.

◆ TestRefineClusters()

static void kaldi::TestRefineClusters ( )
static

Definition at line 286 of file cluster-utils-test.cc.

References AssertEqual(), DeletePointers(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, rnnlm::n, RefineClustersOptions::num_iters, Rand(), RandUniform(), RefineClusters(), SumClusterableObjf(), and RefineClustersOptions::top_n.

Referenced by main().

286  {
287  for (size_t n = 0;n < 4;n++) {
288  // Test it by creating a random clustering and verifying that it does not make it worse, and
289  // if done with the optimal parameters, makes it optimal.
290  size_t n_clust = Rand() % 10;
291  std::vector<Clusterable*> points;
292  for (size_t j = 0;j < n_clust;j++) {
293  size_t n_points = 1 + Rand() % 5;
294  BaseFloat clust_center = (BaseFloat)j;
295  for (size_t k = 0;k < n_points;k++) points.push_back(new ScalarClusterable(clust_center + RandUniform()*0.01));
296  }
297  std::vector<Clusterable*> clusters(n_clust);
298  std::vector<int32> assignments(points.size());
299  for (size_t i = 0;i < clusters.size();i++) clusters[i] = new ScalarClusterable();
300  // assign each point to a random cluster.
301  for (size_t i = 0;i < points.size();i++) {
302  assignments[i] = Rand() % n_clust;
303  clusters[assignments[i]]->Add(*(points[i]));
304  }
305  BaseFloat points_objf = SumClusterableObjf(points),
306  clust_objf_before = SumClusterableObjf(clusters),
307  clust_objf_after;
308 
309  KALDI_ASSERT(points_objf >= clust_objf_before -
310  (std::abs(points_objf)+std::abs(clust_objf_before))*0.001);
311 
313  cfg.num_iters = 10000; // very large.
314  cfg.top_n = 2 + (Rand() % 20);
315  BaseFloat impr = RefineClusters(points, &clusters, &assignments, cfg);
316 
317  clust_objf_after = SumClusterableObjf(clusters);
318  KALDI_LOG << "TestRefineClusters: objfs are: "<<points_objf<<" "<<clust_objf_before<<" "<<clust_objf_after<<", impr = "<<impr<<'\n';
319  if (cfg.top_n >=(int32) n_clust) { // check exact.
320  KALDI_ASSERT(clust_objf_after <= 0.01*points.size());
321  }
322  AssertEqual(clust_objf_after - clust_objf_before, impr);
323  DeletePointers(&clusters);
324  DeletePointers(&points);
325 
326  }
327 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
BaseFloat RefineClusters(const std::vector< Clusterable *> &points, std::vector< Clusterable *> *clusters, std::vector< int32 > *assignments, RefineClustersOptions cfg)
RefineClusters is mainly used internally by other clustering algorithms.
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
#define KALDI_LOG
Definition: kaldi-error.h:153
ScalarClusterable clusters scalars with x^2 loss.

◆ TestReverseVector()

void kaldi::TestReverseVector ( )

Definition at line 204 of file stl-utils-test.cc.

References rnnlm::i, KALDI_ASSERT, Rand(), and ReverseVector().

Referenced by main().

204  {
205  for (int p = 0; p < 100; p++) {
206  std::vector<int> vec;
207  int sz = Rand() % 5;
208  for (int i = 0;i < sz;i++)
209  vec.push_back(Rand() % 4);
210  std::vector<int> vec2(vec), vec3(vec);
211  ReverseVector(&vec2);
212  ReverseVector(&vec2);
213  KALDI_ASSERT(vec2 == vec);
214  ReverseVector(&vec3);
215  for (size_t i = 0; i < vec.size(); i++)
216  KALDI_ASSERT(vec[i] == vec3[vec.size()-1-i]);
217  }
218 }
void ReverseVector(std::vector< T > *vec)
Reverses the contents of a vector.
Definition: stl-utils.h:264
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestSetOfNumbers()

void kaldi::TestSetOfNumbers ( bool  binary)

Definition at line 30 of file const-integer-set-test.cc.

References ConstIntegerSet< I >::begin(), ConstIntegerSet< I >::count(), ConstIntegerSet< I >::end(), rnnlm::i, ConstIntegerSet< I >::Init(), KALDI_ASSERT, Rand(), ConstIntegerSet< I >::Read(), ConstIntegerSet< I >::size(), Input::Stream(), swap(), and ConstIntegerSet< I >::Write().

30  {
31  std::set<Int> baseline_set;
32  size_t n_in_set = (Rand() % 3) * 50 + (Rand() % 4); // may be less than this.
33  size_t max = (Int) (Rand() % 100) + 1;
34  for (size_t i = 0; i < n_in_set; i++) {
35  Int to_add((Int) (Rand() % max));
36  baseline_set.insert(to_add);
37  }
38 
39  std::vector<Int> vector_set;
40  for (typename std::set<Int>::iterator iter = baseline_set.begin();
41  iter!= baseline_set.end();iter++)
42  vector_set.push_back(*iter);
43  if (vector_set.size() != 0) {
44  for (size_t i = 0;i < 10;i++) // randomize order.
45  std::swap(vector_set[Rand()%vector_set.size()],
46  vector_set[Rand()%vector_set.size()]);
47  }
48 
49  ConstIntegerSet<Int> my_set1(baseline_set);
50 
51  ConstIntegerSet<Int> my_set2(vector_set);
52 
53  ConstIntegerSet<Int> my_set3;
54  my_set3.Init(baseline_set);
55 
56  ConstIntegerSet<Int> my_set4;
57  my_set4.Init(vector_set);
58 
59  {
60  my_set4.Write(Output("tmpf", binary).Stream(), binary);
61  }
62 
63  ConstIntegerSet<Int> my_set5;
64  {
65  bool binary_in;
66  Input ki("tmpf", &binary_in);
67  my_set5.Read(ki.Stream(), binary_in);
68  }
69 
70 
71  // if (enable_iterators) {
72  size_t sz = baseline_set.size(), sz1 = my_set1.size(), sz2 = my_set2.size(),
73  sz3 = my_set3.size(), sz4 = my_set4.size(), sz5 = my_set5.size();
74  KALDI_ASSERT(sz == sz1 && sz == sz2 && sz == sz3 && sz == sz4 && sz == sz5);
75  // }
76  for (size_t i = 0;i < 100;i++) {
77  Int some_int;
78  if (i%2 == 0 && vector_set.size() != 0)
79  some_int = vector_set[Rand()%vector_set.size()];
80  else
81  some_int = Rand() % max;
82  bool in_baseline = (baseline_set.count(some_int) != 0);
83  bool in_my_set1 = (my_set1.count(some_int) != 0);
84  bool in_my_set2 = (my_set2.count(some_int) != 0);
85  bool in_my_set3 = (my_set3.count(some_int) != 0);
86  bool in_my_set4 = (my_set4.count(some_int) != 0);
87  bool in_my_set5 = (my_set5.count(some_int) != 0);
88 
89  if (in_baseline) {
90  KALDI_ASSERT(in_my_set1&&in_my_set2&&in_my_set3&&in_my_set4&&in_my_set5);
91  } else {
92  KALDI_ASSERT(!in_my_set1&&!in_my_set2&&!in_my_set3&&!in_my_set4&&
93  !in_my_set5);
94  }
95  }
96 
97  // if (enable_iterators) {
98  typename std::set<Int>::iterator baseline_iter = baseline_set.begin();
99  typename ConstIntegerSet<Int>::iterator my_iter1 = my_set1.begin();
100  typename ConstIntegerSet<Int>::iterator my_iter2 = my_set2.begin();
101  typename ConstIntegerSet<Int>::iterator my_iter3 = my_set3.begin();
102  typename ConstIntegerSet<Int>::iterator my_iter4 = my_set4.begin();
103  typename ConstIntegerSet<Int>::iterator my_iter5 = my_set5.begin();
104  while (baseline_iter != baseline_set.end()) {
105  KALDI_ASSERT(my_iter1 != my_set1.end());
106  KALDI_ASSERT(my_iter2 != my_set2.end());
107  KALDI_ASSERT(my_iter3 != my_set3.end());
108  KALDI_ASSERT(my_iter4 != my_set4.end());
109  KALDI_ASSERT(my_iter5 != my_set5.end());
110  KALDI_ASSERT(*baseline_iter == *my_iter1);
111  KALDI_ASSERT(*baseline_iter == *my_iter2);
112  KALDI_ASSERT(*baseline_iter == *my_iter3);
113  KALDI_ASSERT(*baseline_iter == *my_iter4);
114  KALDI_ASSERT(*baseline_iter == *my_iter5);
115  baseline_iter++;
116  my_iter1++;
117  my_iter2++;
118  my_iter3++;
119  my_iter4++;
120  my_iter5++;
121  }
122  KALDI_ASSERT(my_iter1 == my_set1.end());
123  KALDI_ASSERT(my_iter2 == my_set2.end());
124  KALDI_ASSERT(my_iter3 == my_set3.end());
125  KALDI_ASSERT(my_iter4 == my_set4.end());
126  KALDI_ASSERT(my_iter5 == my_set5.end());
127  // }
128 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
void Write(std::ostream &os, bool binary) const
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void Read(std::istream &is, bool binary)
void Init(const std::vector< I > &input)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
iterator begin() const
std::vector< I >::const_iterator iterator

◆ TestShareEventMapLeaves()

void kaldi::TestShareEventMapLeaves ( )

Definition at line 535 of file build-tree-utils-test.cc.

References CopySetToVector(), DeleteBuildTreeStats(), DoTableSplitMultiple(), rnnlm::i, Questions::InitRand(), rnnlm::j, KALDI_ASSERT, KALDI_WARN, kAllKeysInsistIdentical, MakeEventPair(), EventMap::MultiMap(), PossibleValues(), Rand(), RandGauss(), RandUniform(), ShareEventMapLeaves(), SortAndUniq(), SplitDecisionTree(), and TrivialTree().

Referenced by main().

535  {
536  // this is modified from TestClusterEventMapRestricted() [rather arbitrarily].
537 
538 
539  int32 num_keys = 1 + Rand() % 4;
540  std::vector<EventKeyType> keys;
541 
542  { // randomly choose keys. Will always define all of them.
543  std::set<EventKeyType> keys_set;
544  while (keys_set.size() < (size_t)num_keys)
545  keys_set.insert( (Rand() % (num_keys + 10)) - 3 );
546  CopySetToVector(keys_set, &keys);
547  }
548 
549 
550  BuildTreeStatsType stats;
551 
552  int32 n_stats = 1 + (Rand() % 10);
553  n_stats *= n_stats; // up to 81 stats.
554 
555  for (size_t i = 0; i < (size_t)n_stats; i++) {
556  EventType evec;
557 
558  for (size_t j = 0; j < keys.size(); j++) {
559  EventValueType val = Rand() % 100;
560  evec.push_back(std::make_pair(keys[j], val));
561  }
562  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(new ScalarClusterable(RandGauss()))));
563  }
564 
565  std::vector<EventKeyType> special_keys;
566  for (size_t i = 0; i < keys.size(); i++)
567  if (RandUniform() < 0.5) special_keys.push_back(keys[i]);
568 
569 
570  int32 nleaves = 0;
571  EventMap *trivial_map = TrivialTree(&nleaves);
572 
573 
574  // We do a complete split on these keys.
575  EventMap *table_split_map = DoTableSplitMultiple(*trivial_map, special_keys,
576  stats, &nleaves);
577 
578  std::cout << "TestClusterEventMapRestricted: after splitting on "<<special_keys.size()<<" keys, nleaves = " <<nleaves<<'\n';
579  // We now do decision tree split.
580  int nleaves_after_table_split = nleaves;
581  Questions qo; // all default.
582  int32 num_quest = Rand() % 10, num_iters = rand () % 5;
583  qo.InitRand(stats, num_quest, num_iters, kAllKeysInsistIdentical);
584  float thresh = 0.001;
585  int32 max_leaves = 100;
586  BaseFloat impr;
587  BaseFloat smallest_split;
588  EventMap *split_tree = SplitDecisionTree(*table_split_map, stats, qo, thresh, max_leaves,
589  &nleaves, &impr, &smallest_split);
590  KALDI_ASSERT((nleaves <= max_leaves || nleaves == nleaves_after_table_split) && smallest_split >= thresh);
591 
592  std::cout << "TestShareEventMapLeaves: after building decision tree, " <<nleaves<<'\n';
593 
594  if (special_keys.size() == 0) {
595  KALDI_WARN << "TestShareEventMapLeaves(): could not test since key not always defined.";
596  delete split_tree;
597  delete trivial_map;
598  delete table_split_map;
599  DeleteBuildTreeStats(&stats);
600  return;
601  }
602  EventKeyType key = special_keys[Rand() % special_keys.size()];
603  std::vector<EventValueType> values;
604  bool always_defined = PossibleValues(key, stats, &values);
605  KALDI_ASSERT(always_defined);
606 
607  std::set<EventValueType> to_share;
608  for (size_t i = 0; i < 3; i++) to_share.insert(values[Rand() % values.size()]);
609 
610  std::vector<std::vector<EventValueType> > share_value;
611  for (std::set<EventValueType>::iterator iter = to_share.begin();
612  iter != to_share.end();
613  iter++) {
614  share_value.resize(share_value.size()+1);
615  share_value.back().push_back(*iter);
616  }
617  int num_leaves;
618  EventMap *shared = ShareEventMapLeaves(*split_tree,
619  key,
620  share_value,
621  &num_leaves);
622  KALDI_ASSERT(num_leaves <= nleaves);
623  for (size_t i = 0; i < share_value.size(); i++) {
624  EventType evec;
625  std::vector<EventAnswerType> answers;
626  evec.push_back(MakeEventPair(key, share_value[i][0]));
627  shared->MultiMap(evec, &answers);
628  SortAndUniq(&answers);
629  KALDI_ASSERT(answers.size() == 1); // should have been shared.
630  }
631  delete shared;
632 
633  delete split_tree;
634  delete trivial_map;
635  delete table_split_map;
636  DeleteBuildTreeStats(&stats);
637 }
EventMap * DoTableSplitMultiple(const EventMap &orig, const std::vector< EventKeyType > &keys, const BuildTreeStatsType &stats, int32 *num_leaves)
DoTableSplitMultiple does a complete split on all the keys, in order from keys[0], keys[1] and so on.
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
std::pair< EventKeyType, EventValueType > MakeEventPair(EventKeyType k, EventValueType v)
Definition: event-map.h:62
This class defines, for each EventKeyType, a set of initial questions that it tries and also a number...
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
EventMap * SplitDecisionTree(const EventMap &input_map, const BuildTreeStatsType &stats, Questions &q_opts, BaseFloat thresh, int32 max_leaves, int32 *num_leaves, BaseFloat *obj_impr_out, BaseFloat *smallest_split_change_out)
Does a decision-tree split at the leaves of an EventMap.
EventMap * ShareEventMapLeaves(const EventMap &e_in, EventKeyType key, std::vector< std::vector< EventValueType > > &values, int32 *num_leaves)
ShareEventMapLeaves performs a quite specific function that allows us to generate trees where...
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
void SortAndUniq(std::vector< T > *vec)
Sorts and uniq&#39;s (removes duplicates) from a vector.
Definition: stl-utils.h:39
bool PossibleValues(EventKeyType key, const BuildTreeStatsType &stats, std::vector< EventValueType > *ans)
Convenience function e.g.
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
void InitRand(const BuildTreeStatsType &stats, int32 num_quest, int32 num_iters_refine, AllKeysType all_keys_type)
InitRand attempts to generate "reasonable" random questions.
int32 EventKeyType
Things of type EventKeyType can take any value.
Definition: event-map.h:45
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
virtual void MultiMap(const EventType &event, std::vector< EventAnswerType > *ans) const =0
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestSortAndUniq()

static void kaldi::TestSortAndUniq ( )
static

Definition at line 79 of file stl-utils-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, rnnlm::n, Rand(), and SortAndUniq().

Referenced by main().

79  {
80  for (int i = 0;i < 100;i++) {
81  std::vector<int> vec;
82 
83  int len = Rand()%5;
84  for (int i = 0;i < len;i++) {
85  int n = Rand() % 100;
86  bool ok = true;
87  for (size_t j = 0;j < vec.size();j++) if (vec[j] == n) ok = false;
88  if (ok) vec.push_back(n);
89  }
90  // don't sort.
91  std::vector<int> vec2(vec); // make sure all things in "vec" represented
92  // in vec2.
93  int len2 = Rand()%10;
94  if (vec.size() > 0) // add more, randomly.
95  for (int i = 0;i < len2;i++)
96  vec2.push_back(vec[Rand()%vec.size()]);
97  SortAndUniq(&vec2);
98  std::sort(vec.begin(), vec.end());
99  KALDI_ASSERT(vec == vec2);
100  }
101 }
void SortAndUniq(std::vector< T > *vec)
Sorts and uniq&#39;s (removes duplicates) from a vector.
Definition: stl-utils.h:39
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestSplitDecisionTree()

void kaldi::TestSplitDecisionTree ( )

Definition at line 730 of file build-tree-utils-test.cc.

References EventMap::Check(), CopySetToVector(), DeleteBuildTreeStats(), Questions::GetQuestionsOf(), Questions::HasQuestionsForKey(), rnnlm::i, QuestionsForKey::initial_questions, Questions::InitRand(), rnnlm::j, KALDI_ASSERT, kAllKeysIntersection, ObjfGivenMap(), Rand(), RandGauss(), SplitDecisionTree(), SplitStatsByMap(), and TrivialTree().

Referenced by main().

730  {
731  // part of the code is the same as the code for testing Questions::InitRand() function.
732  for (int32 p = 0;p < 4;p++) {
733  std::vector<EventKeyType> keys_all, keys_some;
734  {
735  std::set<EventKeyType> keys_all_set, keys_some_set;
736  int32 num_all = Rand() % 3, num_some = Rand() % 3;
737  for (int32 i = 0;i < num_all;i++) keys_all_set.insert(Rand() % 10);
738  for (int32 i = 0;i < num_some;i++) {
739  int32 k = Rand() % 10;
740  if (keys_all_set.count(k) == 0) keys_some_set.insert(k);
741  }
742  CopySetToVector(keys_all_set, &keys_all);
743  CopySetToVector(keys_some_set, &keys_some);
744  }
745  std::set<EventKeyType> keys_all_saw_set;
746  // Now we have two distinct sets of keys keys_all and keys_some.
747  // We now create the Clusterable* stuff.
748  BuildTreeStatsType stats; // dummy because the Clusterable *pointers are actually NULL.
749  size_t n_stats = Rand() % 100;
750  // make sure we sometimes have empty or just one stats: may find extra bugs.
751  if (n_stats > 90) n_stats = 0;
752  if (n_stats > 80) n_stats = 1;
753 
754  for (size_t i = 0;i < n_stats;i++) { // Create stats...
755  EventType evec;
756  for (size_t j = 0;j < keys_all.size();j++) {
757  evec.push_back(std::make_pair( keys_all[j], (EventValueType)(Rand() % 10)));
758  keys_all_saw_set.insert(keys_all[j]);
759  }
760  for (size_t j = 0;j < keys_some.size();j++)
761  if (Rand() % 2 == 0) { // randomly w.p. 1/2
762  evec.push_back(std::make_pair( keys_some[j], (EventValueType)(Rand() % 10)));
763  keys_all_saw_set.insert(keys_some[j]);
764  }
765  std::sort(evec.begin(), evec.end()); // sorts on keys.
766  EventMap::Check(evec);
767  stats.push_back(std::make_pair(evec, (Clusterable*) new ScalarClusterable(RandGauss())));
768  }
769  Questions qo; // all default.
770  BaseFloat thresh = 0.00001; // these stats have a count of 1... need v. small thresh to get them to merge.
771  // 0.000001 tries to ensure everything is split.
772 
773  bool intersection = true; // keep borrowed code later on happy.
774 
775  int32 num_quest = Rand() % 10, num_iters = rand () % 5;
776  qo.InitRand(stats, num_quest, num_iters, kAllKeysIntersection);
777 
778  if (n_stats > 0) {
779  if (p < 2) {
780  for (size_t i = 0;i < keys_all.size();i++) {
781  KALDI_ASSERT(qo.HasQuestionsForKey(keys_all[i]));
782  const QuestionsForKey &opts = qo.GetQuestionsOf(keys_all[i]);
783  std::cout << "num-quest: "<< opts.initial_questions.size() << '\n';
784  for (size_t j = 0;j < opts.initial_questions.size();j++) {
785  for (size_t k = 0;k < opts.initial_questions[j].size();k++)
786  std::cout << opts.initial_questions[j][k] <<" ";
787  std::cout << '\n';
788  }
789  }
790  }
791  if (intersection) {
792  for (size_t i = 0;i < keys_all.size();i++) {
793  KALDI_ASSERT(qo.HasQuestionsForKey(keys_all[i]));
794  qo.GetQuestionsOf(keys_all[i]);
795  }
796  } else { // union: expect to see all keys that were in the data.
797  for (std::set<int32>::iterator iter = keys_all_saw_set.begin(); iter != keys_all_saw_set.end(); iter++) {
798  KALDI_ASSERT(qo.HasQuestionsForKey(*iter));
799  }
800  }
801  std::cout << "num_quest = " <<num_quest<<", num_iters = "<<num_iters<<'\n';
802  // OK, now want to do decision-tree split.
803 
804  int32 num_leaves = 0;
805  int32 max_leaves = 50;
806  EventMap *trivial_tree = TrivialTree(&num_leaves);
807 
808  BaseFloat impr, smallest_split;
809  EventMap *split_tree = SplitDecisionTree(*trivial_tree, stats, qo, thresh, max_leaves,
810  &num_leaves, &impr, &smallest_split);
811  KALDI_ASSERT(num_leaves <= max_leaves && smallest_split >= thresh);
812 
813  {
814  BaseFloat impr_check = ObjfGivenMap(stats, *split_tree) - ObjfGivenMap(stats, *trivial_tree);
815  std::cout << "Objf impr is " << impr << ", computed differently: " <<impr_check<<'\n';
816  KALDI_ASSERT(fabs(impr - impr_check) < 0.1);
817  }
818 
819 
820  std::cout << "After splitting, num_leaves = " << num_leaves << '\n';
821 
822  std::vector<BuildTreeStatsType> mapped_stats;
823  SplitStatsByMap(stats, *split_tree, &mapped_stats);
824  std::cout << "Assignments of stats to leaves is:\n";
825  for (size_t i = 0; i < mapped_stats.size(); i++) {
826  std::cout << " [ leaf "<<i<<"]: ";
827  for (size_t j = 0; j < mapped_stats[i].size(); j++) {
828  std::cout << ((ScalarClusterable*)(mapped_stats[i][j].second))->Info() << " ";
829  }
830  std::cout << '\n';
831  }
832  delete trivial_tree;
833  delete split_tree;
834  DeleteBuildTreeStats(&stats);
835  }
836  }
837 }
void CopySetToVector(const std::set< T > &s, std::vector< T > *v)
Copies the elements of a set to a vector.
Definition: stl-utils.h:86
This class defines, for each EventKeyType, a set of initial questions that it tries and also a number...
EventMap * SplitDecisionTree(const EventMap &input_map, const BuildTreeStatsType &stats, Questions &q_opts, BaseFloat thresh, int32 max_leaves, int32 *num_leaves, BaseFloat *obj_impr_out, BaseFloat *smallest_split_change_out)
Does a decision-tree split at the leaves of an EventMap.
void SplitStatsByMap(const BuildTreeStatsType &stats, const EventMap &e, std::vector< BuildTreeStatsType > *stats_out)
Splits stats according to the EventMap, indexing them at output by the leaf type. ...
const QuestionsForKey & GetQuestionsOf(EventKeyType key) const
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
void DeleteBuildTreeStats(BuildTreeStatsType *stats)
This frees the Clusterable* pointers in "stats", where non-NULL, and sets them to NULL...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
float BaseFloat
Definition: kaldi-types.h:29
void InitRand(const BuildTreeStatsType &stats, int32 num_quest, int32 num_iters_refine, AllKeysType all_keys_type)
InitRand attempts to generate "reasonable" random questions.
QuestionsForKey is a class used to define the questions for a key, and also options that allow us to ...
std::vector< std::vector< EventValueType > > initial_questions
BaseFloat ObjfGivenMap(const BuildTreeStatsType &stats_in, const EventMap &e)
Cluster the stats given the event map return the total objf given those clusters. ...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
bool HasQuestionsForKey(EventKeyType key) const
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventValueType
Given current code, things of type EventValueType should generally be nonnegative and in a reasonably...
Definition: event-map.h:51
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestSplitStatsByKey()

void kaldi::TestSplitStatsByKey ( )

Definition at line 123 of file build-tree-utils-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, EventMap::Lookup(), Rand(), and SplitStatsByKey().

Referenced by main().

123  {
124  {
125  BuildTreeStatsType stats;
126  for(int32 i = 0; i < 100; i++) {
127  EventType evec;
128  if (Rand() % 2)
129  evec.push_back(std::make_pair(12, Rand() % 10));
130  evec.push_back(std::make_pair(10, Rand() % 10));
131  if (Rand() % 2)
132  evec.push_back(std::make_pair(8, Rand() % 10));
133  std::sort(evec.begin(), evec.end());
134  stats.push_back(std::make_pair(evec, static_cast<Clusterable*>(NULL)));
135  }
136  std::vector<BuildTreeStatsType> stats_vec;
137  SplitStatsByKey(stats, 10, &stats_vec);
138  for(int32 i = 0; i < static_cast<int32>(stats_vec.size()); i++) {
139  for(int32 j = 0; j < static_cast<int32>(stats_vec[i].size()); j++) {
140  EventAnswerType ans;
141  bool ok = EventMap::Lookup(stats_vec[i][j].first, 10, &ans);
142  KALDI_ASSERT(ok && ans == i);
143  }
144  }
145  }
146 }
kaldi::int32 int32
void SplitStatsByKey(const BuildTreeStatsType &stats_in, EventKeyType key, std::vector< BuildTreeStatsType > *stats_out)
SplitStatsByKey splits stats up according to the value of a particular key, which must be always defi...
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
std::vector< std::pair< EventType, Clusterable * > > BuildTreeStatsType

◆ TestSplitStringOnFirstSpace()

void kaldi::TestSplitStringOnFirstSpace ( )

Definition at line 266 of file text-utils-test.cc.

References KALDI_ASSERT, and SplitStringOnFirstSpace().

Referenced by main().

266  {
267  std::string a, b;
268  SplitStringOnFirstSpace("a b", &a, &b);
269  KALDI_ASSERT(a == "a" && b == "b");
270  SplitStringOnFirstSpace("aa bb", &a, &b);
271  KALDI_ASSERT(a == "aa" && b == "bb");
272  SplitStringOnFirstSpace("aa", &a, &b);
273  KALDI_ASSERT(a == "aa" && b == "");
274  SplitStringOnFirstSpace(" aa \n\t ", &a, &b);
275  KALDI_ASSERT(a == "aa" && b == "");
276  SplitStringOnFirstSpace(" \n\t ", &a, &b);
277  KALDI_ASSERT(a == "" && b == "");
278  SplitStringOnFirstSpace(" aa bb \n\t ", &a, &b);
279  KALDI_ASSERT(a == "aa" && b == "bb");
280  SplitStringOnFirstSpace(" aa bb cc ", &a, &b);
281  KALDI_ASSERT(a == "aa" && b == "bb cc");
282  SplitStringOnFirstSpace(" aa bb cc ", &a, &b);
283  KALDI_ASSERT(a == "aa" && b == "bb cc");
284  SplitStringOnFirstSpace(" aa bb cc", &a, &b);
285  KALDI_ASSERT(a == "aa" && b == "bb cc");
286 }
void SplitStringOnFirstSpace(const std::string &str, std::string *first, std::string *rest)
Removes leading and trailing white space from the string, then splits on the first section of whitesp...
Definition: text-utils.cc:120
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestSplitStringToFloats()

void kaldi::TestSplitStringToFloats ( )

Definition at line 123 of file text-utils-test.cc.

References KALDI_ASSERT, and SplitStringToFloats().

Referenced by main().

123  {
124  {
125  std::vector<float> v;
126  KALDI_ASSERT(SplitStringToFloats("-1:2.5:4", ":", false, &v) == true
127  && v.size() == 3 && v[0] == -1 && v[1] == 2.5 && v[2] == 4);
128  KALDI_ASSERT(SplitStringToFloats("-1:2.5:4:", ":", false, &v) == false);
129  KALDI_ASSERT(SplitStringToFloats(":-1::2:4:", ":", true, &v) == true
130  && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
131  KALDI_ASSERT(SplitStringToFloats("-1\n2.5\t4", " \n\t\r", false, &v) == true
132  && v.size() == 3 && v[0] == -1 && v[1] == 2.5 && v[2] == 4);
133  KALDI_ASSERT(SplitStringToFloats(" ", " \n\t\r", true, &v) == true
134  && v.size() == 0);
135  KALDI_ASSERT(SplitStringToFloats("", " \n\t\r", false, &v) == true
136  && v.size() == 0);
137  }
138 
139  {
140  std::vector<double> v;
141  KALDI_ASSERT(SplitStringToFloats("-1:2:4", ":", false, &v) == true);
142  }
143 }
bool SplitStringToFloats(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< F > *out)
Definition: text-utils.cc:30
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestSplitStringToIntegers()

void kaldi::TestSplitStringToIntegers ( )

Definition at line 98 of file text-utils-test.cc.

References KALDI_ASSERT, and SplitStringToIntegers().

Referenced by main().

98  {
99  {
100  std::vector<int32> v;
101  KALDI_ASSERT(SplitStringToIntegers("-1:2:4", ":", false, &v) == true
102  && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
103  KALDI_ASSERT(SplitStringToIntegers("-1:2:4:", ":", false, &v) == false);
104  KALDI_ASSERT(SplitStringToIntegers(":-1::2:4:", ":", true, &v) == true
105  && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
106  KALDI_ASSERT(SplitStringToIntegers("-1\n2\t4", " \n\t\r", false, &v) == true
107  && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
108  KALDI_ASSERT(SplitStringToIntegers(" ", " \n\t\r", true, &v) == true
109  && v.size() == 0);
110  KALDI_ASSERT(SplitStringToIntegers("", " \n\t\r", false, &v) == true
111  && v.size() == 0);
112  }
113 
114  {
115  std::vector<uint32> v;
116  KALDI_ASSERT(SplitStringToIntegers("-1:2:4", ":", false, &v) == false);
117  // cannot put negative number in uint32.
118  }
119 }
bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< I > *out)
Split a string (e.g.
Definition: text-utils.h:68
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestSplitStringToVector()

void kaldi::TestSplitStringToVector ( )

Definition at line 41 of file text-utils-test.cc.

References full, GetRandChar(), GetRandDelim(), rnnlm::i, rnnlm::j, JoinVectorToString(), KALDI_ASSERT, Rand(), and SplitStringToVector().

Referenced by main().

41  {
42  // srand((unsigned int)time(NULL));
43  // didn't compile on cygwin.
44 
45  {
46  std::vector<std::string> str_vec;
47  SplitStringToVector("", " ", false, &str_vec);
48  KALDI_ASSERT(str_vec.size() == 1); // If this fails it may just mean
49  // that someone changed the
50  // semantics of SplitStringToVector in a reasonable way.
51  SplitStringToVector("", " ", true, &str_vec);
52  KALDI_ASSERT(str_vec.empty());
53  }
54  for (int j = 0; j < 100; j++) {
55  std::vector<std::string> str_vec;
56  int sz = Rand() % 73;
57  std::string full;
58  for (int i = 0; i < sz-1; i++) {
59  full.push_back((Rand() % 7 == 0)? GetRandDelim() : GetRandChar());
60  }
61  std::string delim;
62  delim.push_back(GetRandDelim());
63  bool omit_empty_strings = (Rand() %2 == 0)? true : false;
64  SplitStringToVector(full, delim.c_str(), omit_empty_strings, &str_vec);
65  std::string new_full;
66  for (size_t i = 0; i < str_vec.size(); i++) {
67  if (omit_empty_strings) KALDI_ASSERT(str_vec[i] != "");
68  new_full.append(str_vec[i]);
69  if (i < str_vec.size() -1) new_full.append(delim);
70  }
71  std::string new_full2;
72  JoinVectorToString(str_vec, delim.c_str(), omit_empty_strings, &new_full2);
73  if (omit_empty_strings) { // sequences of delimiters cannot be matched
74  size_t start = full.find_first_not_of(delim),
75  end = full.find_last_not_of(delim);
76  if (start == std::string::npos) { // only delimiters
77  KALDI_ASSERT(end == std::string::npos);
78  } else {
79  std::string full_test;
80  char last = '\0';
81  for (size_t i = start; i <= end; i++) {
82  if (full[i] != last || last != *delim.c_str())
83  full_test.push_back(full[i]);
84  last = full[i];
85  }
86  if (!full.empty()) {
87  KALDI_ASSERT(new_full.compare(full_test) == 0);
88  KALDI_ASSERT(new_full2.compare(full_test) == 0);
89  }
90  }
91  } else if (!full.empty()) {
92  KALDI_ASSERT(new_full.compare(full) == 0);
93  KALDI_ASSERT(new_full2.compare(full) == 0);
94  }
95  }
96 }
void JoinVectorToString(const std::vector< std::string > &vec_in, const char *delim, bool omit_empty_strings, std::string *str_out)
Joins the elements of a vector of strings into a single string using "delim" as the delimiter...
Definition: text-utils.cc:77
char GetRandDelim()
void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< std::string > *out)
Split a string using any of the single character delimiters.
Definition: text-utils.cc:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
char GetRandChar()
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestSplitToPhones()

void kaldi::TestSplitToPhones ( )

Definition at line 203 of file hmm-utils-test.cc.

References GenerateRandomAlignment(), GenRandTransitionModel(), TransitionModel::GetPhones(), rnnlm::i, rnnlm::j, KALDI_ASSERT, RandInt(), SplitToPhones(), and TransitionModel::TransitionIdToPhone().

Referenced by main().

203  {
204  ContextDependency *ctx_dep = NULL;
205  TransitionModel *trans_model = GenRandTransitionModel(&ctx_dep);
206  std::vector<int32> phone_seq;
207  int32 num_phones = RandInt(0, 10);
208  const std::vector<int32> &phone_list = trans_model->GetPhones();
209  for (int32 i = 0; i < num_phones; i++) {
210  int32 rand_phone = phone_list[RandInt(0, phone_list.size() - 1)];
211  phone_seq.push_back(rand_phone);
212  }
213  bool reorder = (RandInt(0, 1) == 0);
214  std::vector<int32> alignment;
215  GenerateRandomAlignment(*ctx_dep, *trans_model, reorder,
216  phone_seq, &alignment);
217  std::vector<std::vector<int32> > split_alignment;
218  SplitToPhones(*trans_model, alignment, &split_alignment);
219  KALDI_ASSERT(split_alignment.size() == phone_seq.size());
220  for (size_t i = 0; i < split_alignment.size(); i++) {
221  KALDI_ASSERT(!split_alignment[i].empty());
222  for (size_t j = 0; j < split_alignment[i].size(); j++) {
223  int32 transition_id = split_alignment[i][j];
224  KALDI_ASSERT(trans_model->TransitionIdToPhone(transition_id) ==
225  phone_seq[i]);
226  }
227  }
228  delete trans_model;
229  delete ctx_dep;
230 }
kaldi::int32 int32
bool SplitToPhones(const TransitionModel &trans_model, const std::vector< int32 > &alignment, std::vector< std::vector< int32 > > *split_alignment)
SplitToPhones splits up the TransitionIds in "alignment" into their individual phones (one vector per...
Definition: hmm-utils.cc:723
void GenerateRandomAlignment(const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, bool reorder, const std::vector< int32 > &phone_sequence, std::vector< int32 > *alignment)
For use in test code, this function generates an alignment (a sequence of transition-ids) correspondi...
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
TransitionModel * GenRandTransitionModel(ContextDependency **ctx_dep_out)
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ TestStringsApproxEqual()

void kaldi::TestStringsApproxEqual ( )

Definition at line 313 of file text-utils-test.cc.

References KALDI_ASSERT, and StringsApproxEqual().

Referenced by main().

313  {
314  // we must test the test.
315  KALDI_ASSERT(!StringsApproxEqual("a", "b"));
316  KALDI_ASSERT(!StringsApproxEqual("1", "2"));
317  KALDI_ASSERT(StringsApproxEqual("1.234", "1.235", 2));
318  KALDI_ASSERT(!StringsApproxEqual("1.234", "1.235", 3));
319  KALDI_ASSERT(StringsApproxEqual("x 1.234 y", "x 1.2345 y", 3));
320  KALDI_ASSERT(!StringsApproxEqual("x 1.234 y", "x 1.2345 y", 4));
321  KALDI_ASSERT(StringsApproxEqual("x 1.234 y 6.41", "x 1.235 y 6.49", 1));
322  KALDI_ASSERT(!StringsApproxEqual("x 1.234 y 6.41", "x 1.235 y 6.49", 2));
323  KALDI_ASSERT(StringsApproxEqual("x 1.234 y 6.41", "x 1.235 y 6.411", 2));
324  KALDI_ASSERT(StringsApproxEqual("x 1.0 y", "x 1.0001 y", 3));
325  KALDI_ASSERT(!StringsApproxEqual("x 1.0 y", "x 1.0001 y", 4));
326 }
bool StringsApproxEqual(const std::string &a, const std::string &b, int32 decimal_places_tolerance)
This function returns true when two text strings are approximately equal, and false when they are not...
Definition: text-utils.cc:335
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestSum()

static void kaldi::TestSum ( )
static

Definition at line 137 of file cluster-utils-test.cc.

References AssertEqual(), Clusterable::Objf(), and SumClusterable().

Referenced by main().

137  {
138  ScalarClusterable a(1.0), b(2.5);
139  std::vector<Clusterable*> vec;
140  vec.push_back(&a);
141  vec.push_back(&b);
142  Clusterable *sum = SumClusterable(vec);
143  AssertEqual(a.ObjfPlus(b), sum->Objf());
144  delete sum;
145 }
virtual BaseFloat Objf() const =0
Return the objective function associated with the stats [assuming ML estimation]. ...
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Clusterable * SumClusterable(const std::vector< Clusterable *> &vec)
Sums stats (ptrs may be NULL). Returns NULL if no non-NULL stats present.
ScalarClusterable clusters scalars with x^2 loss.

◆ TestSumObjfAndSumNormalizer()

static void kaldi::TestSumObjfAndSumNormalizer ( )
static

Definition at line 125 of file cluster-utils-test.cc.

References AssertEqual(), ScalarClusterable::Objf(), SumClusterableNormalizer(), and SumClusterableObjf().

Referenced by main().

125  {
126  ScalarClusterable a(1.0), b(2.5);
127  AssertEqual(a.Objf(), 0.0);
128  AssertEqual(b.Objf(), 0.0);
129  a.Add(b);
130  std::vector<Clusterable*> vec;
131  vec.push_back(&a);
132  vec.push_back(&a);
133  AssertEqual(SumClusterableObjf(vec), 2*vec[0]->Objf());
134  AssertEqual(SumClusterableNormalizer(vec), 2*vec[0]->Normalizer());
135 }
BaseFloat SumClusterableNormalizer(const std::vector< Clusterable *> &vec)
Returns the total normalizer (usually count) of the cluster (pointers may be NULL).
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
ScalarClusterable clusters scalars with x^2 loss.

◆ TestSymInvertPosDef()

void kaldi::TestSymInvertPosDef ( int32  dim)

Definition at line 286 of file cu-matrix-speed-test.cc.

References CuMatrixBase< Real >::CopyFromMat(), Timer::Elapsed(), KALDI_LOG, kNoTrans, CuMatrixBase< Real >::SymAddMat2(), and CuMatrixBase< Real >::SymInvertPosDef().

286  {
287  BaseFloat time_in_secs = 0.025;
288  CuMatrix<Real> M(dim, dim * 2), N(dim, dim);
289  M.SetRandn();
290  N.SymAddMat2(1.0, M, kNoTrans, 0.0);
291  CuMatrix<Real> Ncopy(N);
292 
293  int iter = 0;
294  Timer tim;
295  for (;tim.Elapsed() < time_in_secs; iter++) {
296  Ncopy.CopyFromMat(N);
297  Ncopy.SymInvertPosDef();
298  }
299 
300  BaseFloat fdim = dim;
301  BaseFloat gflops = (fdim * fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
302  KALDI_LOG << "For CuMatrix::TestCuInvertPosDef" << NameOf<Real>() << ", for dim = "
303  << dim << ", speed was " << gflops << " gigaflops.";
304 }
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ TestTaskSequencer()

void kaldi::TestTaskSequencer ( )

Definition at line 105 of file kaldi-thread-test.cc.

References rnnlm::i, KALDI_ASSERT, TaskSequencerConfig::num_threads, TaskSequencerConfig::num_threads_total, Rand(), and TaskSequencer< C >::Run().

Referenced by main().

105  {
106  TaskSequencerConfig config;
107  config.num_threads = 1 + Rand() % 20;
108  if (Rand() % 2 == 1 )
109  config.num_threads_total = config.num_threads + Rand() % config.num_threads;
110 
111  int32 num_tasks = Rand() % 100;
112 
113  std::vector<int32> task_output;
114  {
115  TaskSequencer<MyTaskClass> sequencer(config);
116  for (int32 i = 0; i < num_tasks; i++) {
117  sequencer.Run(new MyTaskClass(i, &task_output));
118  }
119  } // and let "sequencer" be destroyed, which waits for the last threads.
120  KALDI_ASSERT(task_output.size() == static_cast<size_t>(num_tasks));
121  for (int32 i = 0; i < num_tasks; i++)
122  KALDI_ASSERT(task_output[i] == i);
123 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestThreads()

void kaldi::TestThreads ( )

Definition at line 62 of file kaldi-thread-test.cc.

References g_num_threads, KALDI_ASSERT, and RunMultiThreaded().

Referenced by main().

62  {
63  g_num_threads = 8;
64  // run method with temporary threads on 8 threads
65  // Note: uncomment following line for the possibility of simple benchmarking
66  // for(int i=0; i<100000; i++)
67  {
68  int32 max_to_count = 10000, tot = 0;
69  MyThreadClass c(max_to_count, &tot);
71  KALDI_ASSERT(tot == (10000*(10000-1))/2);
72  }
73  g_num_threads = 1;
74  // let's try the same, but with only one thread
75  {
76  int32 max_to_count = 10000, tot = 0;
77  MyThreadClass c(max_to_count, &tot);
79  KALDI_ASSERT(tot == (10000*(10000-1))/2);
80  }
81 }
int32 g_num_threads
Definition: kaldi-thread.cc:25
kaldi::int32 int32
void RunMultiThreaded(const C &c_in)
Here, class C should inherit from MultiThreadable.
Definition: kaldi-thread.h:151
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestTransitionModel()

void kaldi::TestTransitionModel ( )

Definition at line 26 of file transition-model-test.cc.

References TransitionModel::Compatible(), GenRandTransitionModel(), KALDI_ASSERT, TransitionModel::Read(), and TransitionModel::Write().

Referenced by main().

26  {
27 
28  TransitionModel *trans_model = GenRandTransitionModel(NULL);
29 
30  bool binary = (rand() % 2 == 0);
31 
32  std::ostringstream os;
33  trans_model->Write(os, binary);
34 
35  TransitionModel trans_model2;
36  std::istringstream is2(os.str());
37  trans_model2.Read(is2, binary);
38 
39  {
40  std::ostringstream os1, os2;
41  trans_model->Write(os1, false);
42  trans_model2.Write(os2, false);
43  KALDI_ASSERT(os1.str() == os2.str());
44  KALDI_ASSERT(trans_model->Compatible(trans_model2));
45  }
46  delete trans_model;
47 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
TransitionModel * GenRandTransitionModel(ContextDependency **ctx_dep_out)

◆ TestTreeCluster()

static void kaldi::TestTreeCluster ( )
static

Definition at line 461 of file cluster-utils-test.cc.

References DeletePointers(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, rnnlm::n, Rand(), RandUniform(), SumClusterableObjf(), TreeClusterOptions::thresh, and TreeCluster().

Referenced by main().

461  {
462  size_t n_points_tot = 0, n_wrong_tot = 0;
463  for (size_t n = 0;n < 10;n++) {
464 
465  int32 n_clust = Rand() % 10;
466  std::vector<Clusterable*> points;
467  for (int32 j = 0;j < n_clust;j++) {
468  int32 n_points = 1 + Rand() % 5;
469  BaseFloat clust_center = (BaseFloat)j;
470  for (int32 k = 0;k < n_points;k++) points.push_back(new ScalarClusterable(clust_center + RandUniform()*0.01));
471  }
472  std::vector<Clusterable*> clusters_ext;
473  std::vector<int32> assignments;
474  std::vector<int32> clust_assignments;
475  TreeClusterOptions tcfg;
476  tcfg.thresh = 0.01; // should prevent us splitting things in same bucket.
477  int32 num_leaves = 0;
478  BaseFloat ans = TreeCluster(points, n_clust, &clusters_ext, &assignments, &clust_assignments, &num_leaves, tcfg);
479 
480  if (n < 3) TreeCluster(points, n_clust, NULL, NULL, NULL, NULL, tcfg); // make sure no crash
481 
482  KALDI_ASSERT(num_leaves == n_clust);
483  KALDI_ASSERT(clusters_ext.size() >= static_cast<size_t>(n_clust));
484  std::vector<Clusterable*> clusters(clusters_ext);
485  clusters.resize(n_clust); // ignore non-leaves.
486  BaseFloat clust_objf = SumClusterableObjf(clusters);
487 
488  KALDI_LOG << "TreeCluster: objf after clustering is: "<<clust_objf<<", impr is: "<<ans<<'\n';
489 
490  if (n < 2) // avoid generating too much output.
491  KALDI_LOG << "Num nodes is "<<clusters_ext.size() <<", leaves "<<num_leaves;
492  for (int32 i = 0;i<static_cast<int32>(clusters_ext.size());i++) {
493  if (n < 2) // avoid generating too much output.
494  KALDI_LOG << "Cluster "<<i<<": "<<((ScalarClusterable*)clusters_ext[i])->Info()<<", parent is: "<< clust_assignments[i]<<"";
495  KALDI_ASSERT(clust_assignments[i]>i || (i+1 == static_cast<int32>(clusters_ext.size()) && clust_assignments[i] == i));
496  if (i == static_cast<int32>(clusters_ext.size())-1)
497  KALDI_ASSERT(clust_assignments[i] == i); // top node.
498  }
499  DeletePointers(&clusters_ext);
500  DeletePointers(&points);
501  }
502  if (n_wrong_tot*4 > n_points_tot) {
503  KALDI_LOG << "Got too many wrong in k-means test [may not be fatal, but check it out.";
504  KALDI_ASSERT(0);
505  }
506 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
BaseFloat SumClusterableObjf(const std::vector< Clusterable *> &vec)
Returns the total objective function after adding up all the statistics in the vector (pointers may b...
BaseFloat TreeCluster(const std::vector< Clusterable *> &points, int32 max_clust, std::vector< Clusterable *> *clusters_out, std::vector< int32 > *assignments_out, std::vector< int32 > *clust_assignments_out, int32 *num_leaves_out, TreeClusterOptions cfg)
TreeCluster is a top-down clustering algorithm, using a binary tree (not necessarily balanced)...
#define KALDI_LOG
Definition: kaldi-error.h:153
ScalarClusterable clusters scalars with x^2 loss.

◆ TestTrim()

void kaldi::TestTrim ( )

Definition at line 256 of file text-utils-test.cc.

References KALDI_ASSERT, and TrimTmp().

Referenced by main().

256  {
257  KALDI_ASSERT(TrimTmp(" a ") == "a");
258  KALDI_ASSERT(TrimTmp(" a b c") == "a b c");
259  KALDI_ASSERT(TrimTmp("") == "");
260  KALDI_ASSERT(TrimTmp("X\n") == "X");
261  KALDI_ASSERT(TrimTmp("X\n\t") == "X");
262  KALDI_ASSERT(TrimTmp("\n\tX") == "X");
263 } // end namespace kaldi
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
std::string TrimTmp(std::string s)

◆ TestTrivialTree()

void kaldi::TestTrivialTree ( )

Definition at line 28 of file build-tree-utils-test.cc.

References KALDI_ASSERT, EventMap::Map(), and TrivialTree().

Referenced by main().

28  {
29  int32 nleaves = 0;
30  EventMap *tree = TrivialTree(&nleaves);
31  EventType empty; EventAnswerType ans;
32  bool b = tree->Map(empty, &ans);
33  KALDI_ASSERT(b);
34  KALDI_ASSERT(nleaves == 1);
35  delete tree;
36 }
kaldi::int32 int32
virtual bool Map(const EventType &event, EventAnswerType *ans) const =0
std::vector< std::pair< EventKeyType, EventValueType > > EventType
Definition: event-map.h:58
A class that is capable of representing a generic mapping from EventType (which is a vector of (key...
Definition: event-map.h:86
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 EventAnswerType
As far as the event-map code itself is concerned, things of type EventAnswerType may take any value e...
Definition: event-map.h:56
EventMap * TrivialTree(int32 *num_leaves)
Returns a tree with just one node.

◆ TestUniq()

static void kaldi::TestUniq ( )
static

Definition at line 58 of file stl-utils-test.cc.

References count, rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and Uniq().

Referenced by main().

58  {
59  for (int i = 0;i < 100;i++) {
60  std::vector<int> vec;
61 
62  int cur = 1; // sorted order.
63  int len = Rand()%5;
64  for (int i = 0;i < len;i++) {
65  cur += 1 + (Rand() % 100);
66  vec.push_back(cur);
67  }
68  std::vector<int> vec2;
69  for (int i = 0;i < len;i++) {
70  int count = 1 + Rand()%5;
71  for (int j = 0;j < count;j++) vec2.push_back(vec[i]);
72  }
73  Uniq(&vec2);
74  KALDI_ASSERT(vec2 == vec);
75  }
76 }
void Uniq(std::vector< T > *vec)
Removes duplicate elements from a sorted list.
Definition: stl-utils.h:78
const size_t count
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestVectorToPosteriorEntry()

void kaldi::TestVectorToPosteriorEntry ( )

Definition at line 26 of file posterior-test.cc.

References rnnlm::i, KALDI_ASSERT, VectorBase< Real >::Max(), rnnlm::n, RandUniform(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), and VectorToPosteriorEntry().

Referenced by main().

26  {
27  int32 n = 10 + rand () % 50, gselect = 1 + rand() % 5;
28  BaseFloat min_post = 0.1 + 0.8 * RandUniform();
29 
30  Vector<BaseFloat> loglikes(n);
31  loglikes.SetRandn();
32  loglikes.Scale(10.0);
33 
34  std::vector<std::pair<int32, BaseFloat> > post_entry;
35 
36  VectorToPosteriorEntry(loglikes, gselect, min_post, &post_entry);
37 
38  KALDI_ASSERT(post_entry.size() <= gselect);
39 
40  int32 max_elem;
41  loglikes.Max(&max_elem);
42  KALDI_ASSERT(post_entry[0].first == max_elem);
43 
44  KALDI_ASSERT(post_entry.back().second >= min_post);
45  KALDI_ASSERT(post_entry.back().second <= post_entry.front().second);
46 
47  BaseFloat sum = 0.0;
48  for (size_t i = 0; i < post_entry.size(); i++)
49  sum += post_entry[i].second;
50  KALDI_ASSERT(fabs(sum - 1.0) < 0.01);
51 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
BaseFloat VectorToPosteriorEntry(const VectorBase< BaseFloat > &log_likes, int32 num_gselect, BaseFloat min_post, std::vector< std::pair< int32, BaseFloat > > *post_entry)
Given a vector of log-likelihoods (typically of Gaussians in a GMM but could be of pdf-ids)...
Definition: posterior.cc:440
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TestWordAlignedLattice() [1/2]

void TestWordAlignedLattice ( const CompactLattice lat,
const TransitionModel tmodel,
const WordBoundaryInfo info,
const CompactLattice aligned_lat 
)

You should only test a lattice if WordAlignLattice returned true (i.e.

This function is designed to crash if something went wrong with the word-alignment of the lattice.

it succeeded and it wasn't a forced-out lattice); otherwise the test will most likely fail.

It verifies that arcs are of 4 types: properly-aligned word arcs, with a word label. partial-word arcs, with the partial-word label. silence arcs, with the silence label.

Definition at line 918 of file word-align-lattice.cc.

References WordAlignedLatticeTester::Test().

921  {
922  WordAlignedLatticeTester t(lat, tmodel, info, aligned_lat);
923  t.Test();
924 }

◆ TestWordAlignedLattice() [2/2]

static bool kaldi::TestWordAlignedLattice ( const WordAlignLatticeLexiconInfo lexicon_info,
const TransitionModel tmodel,
CompactLattice  clat,
CompactLattice  aligned_clat,
bool  allow_duplicate_paths 
)
static

Check equivalence.

Definition at line 927 of file word-align-lattice-lexicon.cc.

References fst::ConvertLattice(), GetVerboseLevel(), IsPlausibleWord(), KALDI_ASSERT, KALDI_WARN, LatticeForwardBackward(), MapSymbols(), and Rand().

Referenced by main(), and WordAlignLatticeLexicon().

931  {
932  int32 max_err = 5, num_err = 0;
933  { // We test whether the forward-backward likelihoods differ; this is intended
934  // to detect when we have duplicate paths in the aligned lattice, for some path
935  // in the input lattice (e.g. due to epsilon-sequencing problems).
936  Posterior post;
937  Lattice lat, aligned_lat;
938  ConvertLattice(clat, &lat);
939  ConvertLattice(aligned_clat, &aligned_lat);
940  TopSort(&lat);
941  TopSort(&aligned_lat);
942  BaseFloat like_before = LatticeForwardBackward(lat, &post),
943  like_after = LatticeForwardBackward(aligned_lat, &post);
944  if (fabs(like_before - like_after) >
945  1.0e-04 * (fabs(like_before) + fabs(like_after))) {
946  KALDI_WARN << "Forward-backward likelihoods differ in word-aligned lattice "
947  << "testing, " << like_before << " != " << like_after;
948  if (!allow_duplicate_paths)
949  num_err++;
950  }
951  }
952 
953  // Do a check on the arcs of the aligned lattice, that each arc corresponds
954  // to an entry in the lexicon.
955  for (CompactLattice::StateId s = 0; s < aligned_clat.NumStates(); s++) {
956  for (fst::ArcIterator<CompactLattice> aiter(aligned_clat, s);
957  !aiter.Done(); aiter.Next()) {
958  const CompactLatticeArc &arc (aiter.Value());
959  KALDI_ASSERT(arc.ilabel == arc.olabel);
960  int32 word_id = arc.ilabel;
961  const std::vector<int32> &tids = arc.weight.String();
962  if (word_id == 0 && tids.empty()) continue; // We allow epsilon arcs.
963 
964  if (num_err < max_err)
965  if (!IsPlausibleWord(lexicon_info, tmodel, word_id, tids))
966  num_err++;
967  // Note: IsPlausibleWord will warn if there is an error.
968  }
969  if (!aligned_clat.Final(s).String().empty()) {
970  KALDI_WARN << "Aligned lattice has nonempty string on its final-prob.";
971  return false;
972  }
973  }
974 
975  // Next we'll do an equivalence test.
976  // First map symbols into equivalence classes, so that we don't wrongly fail
977  // due to the capability of the framework to map words to other words.
978  // (e.g. mapping <eps> on silence arcs to SIL).
979 
980  MapSymbols(lexicon_info, &clat);
981  MapSymbols(lexicon_info, &aligned_clat);
982 
984  int32 num_paths = 5, seed = Rand(), max_path_length = -1;
985  BaseFloat delta = 0.2; // some lattices have large costs -> use large delta.
986 
987  FLAGS_v = GetVerboseLevel(); // set the OpenFst verbose level to the Kaldi
988  // verbose level.
989  if (!RandEquivalent(clat, aligned_clat, num_paths, delta, seed, max_path_length)) {
990  KALDI_WARN << "Equivalence test failed during lattice alignment.";
991  return false;
992  }
993  FLAGS_v = 0;
994 
995  return (num_err == 0);
996 }
fst::StdArc::StateId StateId
static void MapSymbols(const WordAlignLatticeLexiconInfo &lexicon_info, CompactLattice *lat)
Testing code; map word symbols in the lattice "lat" using the equivalence-classes obtained from the l...
int32 GetVerboseLevel()
Get verbosity level, usually set via command line &#39;–verbose=&#39; switch.
Definition: kaldi-error.h:60
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
BaseFloat LatticeForwardBackward(const Lattice &lat, Posterior *post, double *acoustic_like_sum)
This function does the forward-backward over lattices and computes the posterior probabilities of the...
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
#define KALDI_WARN
Definition: kaldi-error.h:150
static bool IsPlausibleWord(const WordAlignLatticeLexiconInfo &lexicon_info, const TransitionModel &tmodel, int32 word_id, const std::vector< int32 > &transition_ids)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
fst::ArcTpl< CompactLatticeWeight > CompactLatticeArc
Definition: kaldi-lattice.h:42

◆ TestWordAlignedLatticeLexicon()

void kaldi::TestWordAlignedLatticeLexicon ( const CompactLattice lat,
const TransitionModel tmodel,
const std::vector< std::vector< int32 > > &  lexicon,
const CompactLattice aligned_lat,
bool  allow_duplicate_paths 
)

This function is designed to crash if something went wrong with the word-alignment of the lattice.

If was_ok==true (was_ok is the return status of WordAlignLattice), it tests that, after removing any silence and partial-word labels that may have been inserted by WordAlignLattice, the word-aligned lattice is equivalent to the input. It also verifies that arcs are of 4 types: properly-aligned word arcs, with a word label. partial-word arcs, with the partial-word label. silence arcs, with the silence label.

Referenced by WordAlignLatticeLexiconOpts::Register().

◆ TestWordAlignLatticeLexicon()

void kaldi::TestWordAlignLatticeLexicon ( )

Definition at line 173 of file word-align-lattice-lexicon-test.cc.

References WordAlignLatticeLexiconOpts::allow_duplicate_paths, fst::ConvertLattice(), fst::ConvertNbestToVector(), GenerateCompactLatticeRandomly(), GenerateLexicon(), GenerateRandomAlignment(), GenerateWordAndPhoneSequence(), GenRandTransitionModel(), TransitionModel::GetPhones(), KALDI_ASSERT, KALDI_LOG, rnnlm::n, PrintLexicon(), PrintWordsAndPhones(), RandInt(), WordAlignLatticeLexiconOpts::reorder, WordAlignLatticeLexiconOpts::test, WordAlignLatticeLexicon(), and WriteCompactLattice().

Referenced by main().

173  {
174  ContextDependency *ctx_dep;
175  TransitionModel *trans_model = GenRandTransitionModel(&ctx_dep);
176  bool allow_zero_words = true;
177  bool allow_empty_word = true;
178  bool allow_multiple_prons = true;
179 
180  const std::vector<int32> &phones = trans_model->GetPhones();
181  std::vector<std::vector<int32> > lexicon;
182  GenerateLexicon(phones, allow_zero_words, allow_empty_word,
183  allow_multiple_prons, &lexicon);
184 
185  std::vector<int32> phone_seq;
186  std::vector<int32> word_seq;
187  while (phone_seq.empty())
188  GenerateWordAndPhoneSequence(lexicon, &phone_seq, &word_seq);
189 
190  PrintLexicon(lexicon);
191  PrintWordsAndPhones(word_seq, phone_seq);
192 
193  std::vector<int32> alignment;
194  bool reorder = (RandInt(0, 1) == 0);
195  GenerateRandomAlignment(*ctx_dep, *trans_model, reorder,
196  phone_seq, &alignment);
197 
198  CompactLattice clat;
199  GenerateCompactLatticeRandomly(alignment, word_seq, &clat);
200 
201  KALDI_LOG << "clat is ";
202  WriteCompactLattice(std::cerr, false, clat);
203 
204  WordAlignLatticeLexiconOpts opts;
205  WordAlignLatticeLexiconInfo lexicon_info(lexicon);
206  opts.test = true; // we rely on the self-test code that's activated when we
207  // do this.
208  opts.allow_duplicate_paths = true;
209  opts.reorder = reorder;
210  CompactLattice aligned_clat;
211  bool ans = WordAlignLatticeLexicon(clat, *trans_model, lexicon_info, opts,
212  &aligned_clat);
213  KALDI_LOG << "Aligned clat is ";
214  WriteCompactLattice(std::cerr, false, aligned_clat);
215  KALDI_ASSERT(ans);
216 
217  Lattice lat;
218  ConvertLattice(clat, &lat);
219  int32 n = 1000; // a maximum.
220  Lattice nbest_lat;
221  std::vector<Lattice> nbest_lats;
222  fst::ShortestPath(lat, &nbest_lat, n);
223  fst::ConvertNbestToVector(nbest_lat, &nbest_lats);
224  KALDI_LOG << "Word-aligned lattice has " << nbest_lats.size() << " paths.";
225 
226  delete ctx_dep;
227  delete trans_model;
228 }
void GenerateCompactLatticeRandomly(const std::vector< int32 > &alignment, const std::vector< int32 > &words, CompactLattice *clat)
kaldi::int32 int32
bool WordAlignLatticeLexicon(const CompactLattice &lat, const TransitionModel &tmodel, const WordAlignLatticeLexiconInfo &lexicon_info, const WordAlignLatticeLexiconOpts &opts, CompactLattice *lat_out)
Align lattice so that each arc has the transition-ids on it that correspond to the word that is on th...
void GenerateWordAndPhoneSequence(std::vector< std::vector< int32 > > &lexicon, std::vector< int32 > *phone_seq, std::vector< int32 > *word_seq)
void ConvertNbestToVector(const Fst< Arc > &fst, std::vector< VectorFst< Arc > > *fsts_out)
This function converts an FST with a special structure, which is output by the OpenFst functions Shor...
struct rnnlm::@11::@12 n
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
fst::VectorFst< LatticeArc > Lattice
Definition: kaldi-lattice.h:44
void GenerateRandomAlignment(const ContextDependencyInterface &ctx_dep, const TransitionModel &trans_model, bool reorder, const std::vector< int32 > &phone_sequence, std::vector< int32 > *alignment)
For use in test code, this function generates an alignment (a sequence of transition-ids) correspondi...
void GenerateLexicon(const std::vector< int32 > &phones, bool allow_zero_words, bool allow_empty_word, bool allow_multiple_prons, std::vector< std::vector< int32 > > *lexicon)
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool WriteCompactLattice(std::ostream &os, bool binary, const CompactLattice &t)
static void PrintLexicon(const std::vector< std::vector< int32 > > &lexicon)
TransitionModel * GenRandTransitionModel(ContextDependency **ctx_dep_out)
static void PrintWordsAndPhones(const std::vector< int32 > &words, const std::vector< int32 > &phones)
#define KALDI_LOG
Definition: kaldi-error.h:153
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ ThrowsExceptionTest()

bool kaldi::ThrowsExceptionTest ( bool  seps,
const std::string &  infile 
)

Definition at line 207 of file arpa-lm-compiler-test.cc.

References Compile().

Referenced by RunAllTests().

207  {
208  try {
209  // Make memory cleanup easy in both cases of try-catch block.
210  std::unique_ptr<ArpaLmCompiler> compiler(Compile(seps, infile));
211  return false;
212  } catch (const KaldiFatalError&) {
213  return true;
214  }
215 }
ArpaLmCompiler * Compile(bool seps, const std::string &infile)

◆ TimerTest()

void kaldi::TimerTest ( )

Definition at line 28 of file timer-test.cc.

References Timer::Elapsed(), KALDI_ERR, and Sleep().

Referenced by main().

28  {
29  float time_secs = 0.025 * (rand() % 10);
30  std::cout << "target is " << time_secs << "\n";
31  Timer timer;
32  Sleep(time_secs);
33  BaseFloat f = timer.Elapsed();
34  std::cout << "time is " << f << std::endl;
35  if (fabs(time_secs - f) > 0.05)
36  KALDI_ERR << "Timer fail: waited " << f << " seconds instead of "
37  << time_secs << " secs.";
38 }
void Sleep(float seconds)
Definition: kaldi-utils.cc:45
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ TimeToTimecode()

std::string TimeToTimecode ( float  time)

Definition at line 402 of file online-audio-client.cc.

Referenced by main().

402  {
403 
404  char buf[64];
405 
406  int32 h, m, s, ms;
407  s = (int32) time;
408  ms = (int32)((time - (float) s) * 1000.0f);
409  m = s / 60;
410  s %= 60;
411  h = m / 60;
412  m %= 60;
413 
414 #if !defined(_MSC_VER)
415  snprintf(buf, 64, "%02d:%02d:%02d.%03d", h, m, s, ms);
416 #endif
417 
418  return buf;
419 }
kaldi::int32 int32

◆ TopSortCompactLatticeIfNeeded()

void TopSortCompactLatticeIfNeeded ( CompactLattice clat)

Topologically sort the compact lattice if not already topologically sorted.

Will crash if the lattice cannot be topologically sorted.

Definition at line 608 of file lattice-functions.cc.

References KALDI_ERR.

Referenced by LatticeIncrementalDeterminizer::AcceptRawLatticeChunk(), CompactLatticeLimitDepth(), PrunedCompactLatticeComposer::Compose(), and main().

608  {
609  if (clat->Properties(fst::kTopSorted, true) == 0) {
610  if (fst::TopSort(clat) == false) {
611  KALDI_ERR << "Topological sorting failed";
612  }
613  }
614 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ TopSortLatticeIfNeeded()

void TopSortLatticeIfNeeded ( Lattice clat)

Topologically sort the lattice if not already topologically sorted.

Will crash if lattice cannot be topologically sorted.

Definition at line 616 of file lattice-functions.cc.

References KALDI_ERR.

Referenced by SingleUtteranceGmmDecoder::GetGaussianPosteriors(), LatticeBoost(), and ReplaceAcousticScoresFromMap().

616  {
617  if (lat->Properties(fst::kTopSorted, true) == 0) {
618  if (fst::TopSort(lat) == false) {
619  KALDI_ERR << "Topological sorting failed";
620  }
621  }
622 }
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ ToString()

std::string kaldi::ToString ( const T &  t)

Definition at line 42 of file cu-rand-speed-test.cc.

Referenced by MeanVariance().

42  {
43  std::ostringstream os;
44  os << t;
45  return os.str();
46 }

◆ TotalNumArcs()

static int32 kaldi::TotalNumArcs ( const CompactLattice clat)
static

Definition at line 878 of file compose-lattice-pruned.cc.

Referenced by PrunedCompactLatticeComposer::Compose().

878  {
879  int32 num_states = clat.NumStates(),
880  num_arcs = 0;
881  for (int32 s = 0; s < num_states; s++)
882  num_arcs += clat.NumArcs(s);
883  return num_arcs;
884 }
kaldi::int32 int32

◆ TraceMatMat() [1/6]

Real TraceMatMat ( const CuMatrixBase< Real > &  A,
const CuMatrixBase< Real > &  B,
MatrixTransposeType  trans 
)

Definition at line 2145 of file cu-matrix.cc.

References CU1DBLOCK, CuVectorBase< Real >::Data(), CuMatrixBase< Real >::Data(), CuMatrixBase< Real >::Dim(), KALDI_ASSERT, kNoTrans, kUndefined, CuMatrixBase< Real >::Mat(), CuMatrixBase< Real >::num_rows_, CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), CuMatrixBase< Real >::Stride(), VectorBase< Real >::Sum(), and TraceMatMat().

2147  {
2148  if (A.num_rows_ == 0) {
2149  KALDI_ASSERT(B.num_rows_ == 0);
2150  return 0.0;
2151  }
2152  Real result = 0;
2153 #if HAVE_CUDA == 1
2154  if (CuDevice::Instantiate().Enabled()) {
2155  if (trans == kNoTrans) {
2156  KALDI_ASSERT(A.NumRows() == B.NumCols() && A.NumCols() == B.NumRows());
2157  } else {
2158  KALDI_ASSERT(A.NumRows() == B.NumRows() && A.NumCols() == B.NumCols());
2159  }
2160  CuTimer tim;
2161  // 2D blocks: each (8x32) block sums up (32x32) elements.
2162  // 2D grid: try to cover all the matrix A unless it is too big.
2163  // Kernel will reduce to ~256 elements with good performance,
2164  // if the matrix is not in a very bad shape.
2165  // (wider or taller than 32x8192)
2166  // CPU will then reduce to 1 element.
2167  const int kWarpSize = 32;
2168  dim3 dimBlock(kWarpSize, CU1DBLOCK / kWarpSize);
2169  dim3 dimGrid(n_blocks(A.NumCols(), kWarpSize),
2170  n_blocks(A.NumRows(), kWarpSize));
2171  if (dimGrid.x * dimGrid.y > 256) {
2172  dimGrid.y = 256 / dimGrid.x;
2173  if (dimGrid.y == 0) {
2174  dimGrid.y = 1;
2175  }
2176  }
2177  CuVector<Real> result_vec(dimGrid.x * dimGrid.y, kUndefined);
2178  if (trans == kNoTrans) {
2179  cuda_trace_mat_mat(dimGrid, dimBlock, A.Data(), B.Data(), A.Dim(),
2180  B.Stride(), result_vec.Data());
2181  } else {
2182  cuda_trace_mat_mat_trans(dimGrid, dimBlock, A.Data(), B.Data(), A.Dim(),
2183  B.Stride(), result_vec.Data());
2184  }
2185  CU_SAFE_CALL(cudaGetLastError());
2186  Vector<Real> result_cpu(result_vec); // copying from CUDA faster than summing in CUDA.
2187  result = result_cpu.Sum();
2188  CuDevice::Instantiate().AccuProfile(__func__, tim);
2189  } else
2190 #endif
2191  {
2192  result = TraceMatMat(A.Mat(), B.Mat(), trans);
2193  }
2194  return result;
2195 }
#define CU1DBLOCK
Definition: cu-matrixdim.h:57
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
template double TraceMatMat(const CuMatrixBase< double > &A, const CuMatrixBase< double > &B, MatrixTransposeType trans)

◆ TraceMatMat() [2/6]

template float kaldi::TraceMatMat ( const CuMatrixBase< float > &  A,
const CuMatrixBase< float > &  B,
MatrixTransposeType  trans 
)

◆ TraceMatMat() [3/6]

template double kaldi::TraceMatMat ( const CuMatrixBase< double > &  A,
const CuMatrixBase< double > &  B,
MatrixTransposeType  trans 
)

◆ TraceMatMat() [4/6]

Real TraceMatMat ( const MatrixBase< Real > &  A,
const MatrixBase< Real > &  B,
MatrixTransposeType  trans = kNoTrans 
)

We need to declare this here as it will be a friend function.

tr(A B), or tr(A B^T).

Definition at line 2692 of file kaldi-matrix.cc.

References cblas_Xdot(), MatrixBase< Real >::data_, KALDI_ASSERT, kNoTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), MatrixBase< Real >::stride_, and TraceMatMat().

Referenced by CalBasisFmllrStepSize(), CalcFmllrStepSize(), DiscriminativeComputation::Compute(), kaldi::nnet3::ComputeObjectiveFunction(), BasisFmllrEstimate::ComputeTransform(), LstmNonlinearityComponent::ConsolidateMemory(), kaldi::nnet3::ConstrainOrthonormalInternal(), ConvolutionComponent::DotProduct(), TimeHeightConvolutionComponent::DotProduct(), LstmNonlinearityComponent::DotProduct(), TdnnComponent::DotProduct(), RepeatedAffineComponent::DotProduct(), AffineComponent::DotProduct(), LinearComponent::DotProduct(), BlockAffineComponent::DotProduct(), Convolutional1dComponent::DotProduct(), FmllrAuxfGradient(), FmllrAuxFuncDiagGmm(), FmllrSgmm2Accs::FmllrObjGradient(), MatrixBase< float >::FrobeniusNorm(), LogisticRegression::GetObjfAndGrad(), AffineComponent::Info(), AffineComponentPreconditioned::Info(), AffineComponentPreconditionedOnline::Info(), FixedLinearComponent::Info(), FixedAffineComponent::Info(), Convolutional1dComponent::Info(), main(), NnetComputer::MatrixStddev(), MllrAuxFunction(), MlObjective(), OnlineNaturalGradient::PreconditionDirections(), kaldi::nnet2::PreconditionDirectionsAlpha(), kaldi::nnet2::PreconditionDirectionsAlphaRescaled(), OnlinePreconditionerSimple::PreconditionDirectionsCpu(), OnlineNaturalGradientSimple::PreconditionDirectionsCpu(), OnlinePreconditioner::PreconditionDirectionsInternal(), kaldi::nnet3::PrintParameterStats(), NnetDiscriminativeComputeObjf::ProcessOutputs(), NnetChainTrainer::ProcessOutputs(), NnetChainComputeProb::ProcessOutputs(), NnetDiscriminativeTrainer::ProcessOutputs(), NnetUpdater::Propagate(), SolveQuadraticMatrixProblem(), kaldi::nnet3::attention::TestAttentionForwardBackward(), TestCuMatrixCompObjfAndDeriv(), TestCuMatrixTraceMatMat(), kaldi::nnet3::time_height_convolution::TestDataBackprop(), TestFmpe(), kaldi::nnet3::time_height_convolution::TestParamsBackprop(), kaldi::nnet3::TestSimpleComponentDataDerivative(), kaldi::nnet3::TestSimpleComponentModelDerivative(), TraceMatSpMatSp(), UnitTestCuMatrixObjfDeriv(), UnitTestCuMatrixTraceMatMat(), UnitTestCuSparseMatrixTraceMatSmat(), UnitTestDeterminant(), kaldi::nnet2::UnitTestGenericComponentInternal(), UnitTestLstmNonlinearity(), UnitTestMatrixAddMatSmat(), UnitTestMatrixAddSmatMat(), kaldi::nnet3::UnitTestNnetInputDerivatives(), kaldi::nnet3::UnitTestNnetModelDerivatives(), kaldi::nnet2::UnitTestPreconditionDirectionsOnline(), kaldi::nnet3::UnitTestPreconditionDirectionsOnline(), UnitTestSolve(), UnitTestSparseMatrixTraceMatSmat(), UnitTestTrace(), UnitTestTraceProduct(), FmllrSgmm2Accs::Update(), and MleAmSgmm2Updater::UpdateW().

2694  { // tr(A B), equivalent to sum of each element of A times same element in B'
2695  MatrixIndexT aStride = A.stride_, bStride = B.stride_;
2696  if (trans == kNoTrans) {
2697  KALDI_ASSERT(A.NumRows() == B.NumCols() && A.NumCols() == B.NumRows());
2698  Real ans = 0.0;
2699  Real *adata = A.data_, *bdata = B.data_;
2700  MatrixIndexT arows = A.NumRows(), acols = A.NumCols();
2701  for (MatrixIndexT row = 0;row < arows;row++, adata+=aStride, bdata++)
2702  ans += cblas_Xdot(acols, adata, 1, bdata, bStride);
2703  return ans;
2704  } else {
2705  KALDI_ASSERT(A.NumRows() == B.NumRows() && A.NumCols() == B.NumCols());
2706  Real ans = 0.0;
2707  Real *adata = A.data_, *bdata = B.data_;
2708  MatrixIndexT arows = A.NumRows(), acols = A.NumCols();
2709  for (MatrixIndexT row = 0;row < arows;row++, adata+=aStride, bdata+=bStride)
2710  ans += cblas_Xdot(acols, adata, 1, bdata, 1);
2711  return ans;
2712  }
2713 }
float cblas_Xdot(const int N, const float *const X, const int incX, const float *const Y, const int incY)
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ TraceMatMat() [5/6]

template float kaldi::TraceMatMat ( const MatrixBase< float > &  A,
const MatrixBase< float > &  B,
MatrixTransposeType  trans 
)

◆ TraceMatMat() [6/6]

template double kaldi::TraceMatMat ( const MatrixBase< double > &  A,
const MatrixBase< double > &  B,
MatrixTransposeType  trans 
)

Referenced by TraceMatMat(), and TraceMatMatMat().

◆ TraceMatMatMat() [1/2]

template float kaldi::TraceMatMatMat ( const MatrixBase< float > &  A,
MatrixTransposeType  transA,
const MatrixBase< float > &  B,
MatrixTransposeType  transB,
const MatrixBase< float > &  C,
MatrixTransposeType  transC 
)

◆ TraceMatMatMat() [2/2]

template double kaldi::TraceMatMatMat ( const MatrixBase< double > &  A,
MatrixTransposeType  transA,
const MatrixBase< double > &  B,
MatrixTransposeType  transB,
const MatrixBase< double > &  C,
MatrixTransposeType  transC 
)

◆ TraceMatMatMatMat() [1/2]

template float kaldi::TraceMatMatMatMat ( const MatrixBase< float > &  A,
MatrixTransposeType  transA,
const MatrixBase< float > &  B,
MatrixTransposeType  transB,
const MatrixBase< float > &  C,
MatrixTransposeType  transC,
const MatrixBase< float > &  D,
MatrixTransposeType  transD 
)

◆ TraceMatMatMatMat() [2/2]

template double kaldi::TraceMatMatMatMat ( const MatrixBase< double > &  A,
MatrixTransposeType  transA,
const MatrixBase< double > &  B,
MatrixTransposeType  transB,
const MatrixBase< double > &  C,
MatrixTransposeType  transC,
const MatrixBase< double > &  D,
MatrixTransposeType  transD 
)

Referenced by TraceMatMatMatMat().

◆ TraceMatSmat() [1/5]

Real TraceMatSmat ( const CuMatrixBase< Real > &  A,
const CuSparseMatrix< Real > &  B,
MatrixTransposeType  trans 
)

Definition at line 524 of file cu-sparse-matrix.cc.

References CuSparseMatrix< Real >::CsrColIdx(), CuSparseMatrix< Real >::CsrRowPtr(), CuSparseMatrix< Real >::CsrVal(), CU1DBLOCK, CuMatrixBase< Real >::Data(), CuMatrixBase< Real >::Dim(), KALDI_ASSERT, kNoTrans, kTrans, CuMatrixBase< Real >::Mat(), CuSparseMatrix< Real >::NumCols(), CuMatrixBase< Real >::NumCols(), CuSparseMatrix< Real >::NumElements(), CuSparseMatrix< Real >::NumRows(), CuMatrixBase< Real >::NumRows(), CuSparseMatrix< Real >::Smat(), and CuSparseMatrix< Real >::TraceMatSmat.

526  {
527  if (A.NumCols() == 0) {
528  KALDI_ASSERT(B.NumCols() == 0);
529  return 0.0;
530  }
531  if (B.NumElements() == 0) {
532  return 0.0;
533  }
534  Real result = 0;
535 #if HAVE_CUDA == 1
536  if (CuDevice::Instantiate().Enabled()) {
537  if (trans == kTrans) {
538  KALDI_ASSERT(A.NumRows() == B.NumRows() && A.NumCols() == B.NumCols());
539  } else {
540  KALDI_ASSERT(A.NumCols() == B.NumRows() && A.NumRows() == B.NumCols());
541  }
542 
543  // The Sum() method in CuVector handles a bunch of logic, we use that to
544  // comptue the trace.
545  CuVector<Real> sum_vec(B.NumElements());
546  CuTimer tim;
547 
548  // We use warpSize threads per row to access only the nnz elements.
549  // Every CU1DBLOCK/warpSize rows share one thread block.
550  // 1D grid to cover all rows of B.
551  const int warpSize = 32;
552  dim3 dimBlock(warpSize, CU1DBLOCK / warpSize);
553  dim3 dimGrid(n_blocks(B.NumRows(), dimBlock.y));
554 
555  if (trans == kNoTrans) {
556  cuda_trace_mat_smat(dimGrid, dimBlock, A.Data(), A.Dim(), B.CsrRowPtr(),
557  B.CsrColIdx(), B.CsrVal(), sum_vec.Data());
558  } else {
559  cuda_trace_mat_smat_trans(dimGrid, dimBlock, A.Data(), A.Dim(),
560  B.CsrRowPtr(), B.CsrColIdx(), B.CsrVal(),
561  sum_vec.Data());
562  }
563  result = sum_vec.Sum();
564  CuDevice::Instantiate().AccuProfile(__func__, tim);
565  } else
566 #endif
567  {
568  result = TraceMatSmat(A.Mat(), B.Smat(), trans);
569  }
570  return result;
571 }
#define CU1DBLOCK
Definition: cu-matrixdim.h:57
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
template double TraceMatSmat(const CuMatrixBase< double > &A, const CuSparseMatrix< double > &B, MatrixTransposeType trans)

◆ TraceMatSmat() [2/5]

template float kaldi::TraceMatSmat ( const CuMatrixBase< float > &  A,
const CuSparseMatrix< float > &  B,
MatrixTransposeType  trans 
)

◆ TraceMatSmat() [3/5]

template double kaldi::TraceMatSmat ( const CuMatrixBase< double > &  A,
const CuSparseMatrix< double > &  B,
MatrixTransposeType  trans 
)

◆ TraceMatSmat() [4/5]

template float kaldi::TraceMatSmat ( const MatrixBase< float > &  A,
const SparseMatrix< float > &  B,
MatrixTransposeType  trans 
)

◆ TraceMatSmat() [5/5]

template double kaldi::TraceMatSmat ( const MatrixBase< double > &  A,
const SparseMatrix< double > &  B,
MatrixTransposeType  trans 
)

Referenced by TraceMatSmat().

◆ TraceMatSpMat() [1/2]

template float kaldi::TraceMatSpMat ( const MatrixBase< float > &  A,
MatrixTransposeType  transA,
const SpMatrix< float > &  B,
const MatrixBase< float > &  C,
MatrixTransposeType  transC 
)

◆ TraceMatSpMat() [2/2]

template double kaldi::TraceMatSpMat ( const MatrixBase< double > &  A,
MatrixTransposeType  transA,
const SpMatrix< double > &  B,
const MatrixBase< double > &  C,
MatrixTransposeType  transC 
)

◆ TraceMatSpMatSp() [1/2]

template float kaldi::TraceMatSpMatSp ( const MatrixBase< float > &  A,
MatrixTransposeType  transA,
const SpMatrix< float > &  B,
const MatrixBase< float > &  C,
MatrixTransposeType  transC,
const SpMatrix< float > &  D 
)

◆ TraceMatSpMatSp() [2/2]

template double kaldi::TraceMatSpMatSp ( const MatrixBase< double > &  A,
MatrixTransposeType  transA,
const SpMatrix< double > &  B,
const MatrixBase< double > &  C,
MatrixTransposeType  transC,
const SpMatrix< double > &  D 
)

◆ TraceSpMat() [1/2]

template float kaldi::TraceSpMat ( const SpMatrix< float > &  A,
const MatrixBase< float > &  B 
)

◆ TraceSpMat() [2/2]

template double kaldi::TraceSpMat ( const SpMatrix< double > &  A,
const MatrixBase< double > &  B 
)

◆ TraceSpSp() [1/5]

Real TraceSpSp ( const CuSpMatrix< Real > &  A,
const CuSpMatrix< OtherReal > &  B 
)

C++ templatd wrapper of ANSI-C CUBLAS function GEMM (matrix multiply)

TraceSpSp returns tr(A B)

Definition at line 168 of file cu-sp-matrix.cc.

References CuVectorBase< Real >::CopyDiagFromPacked(), CuPackedMatrix< Real >::Data(), KALDI_ASSERT, kUndefined, CuSpMatrix< Real >::Mat(), CuPackedMatrix< Real >::NumRows(), TraceSpSp(), and VecVec().

168  {
169  KALDI_ASSERT(A.NumRows() == B.NumRows());
170 #if HAVE_CUDA == 1
171  if (CuDevice::Instantiate().Enabled()) {
172  if (A.NumRows() == 0) return 0.0;
173  MatrixIndexT nr = A.NumRows(), size = nr * (nr+1) / 2;
174  CuVector<Real> Adiag(nr, kUndefined);
175  CuVector<OtherReal> Bdiag(nr, kUndefined);
176  Adiag.CopyDiagFromPacked(A);
177  Bdiag.CopyDiagFromPacked(B);
178  CuSubVector<Real> Aall(A.Data(), size);
179  CuSubVector<OtherReal> Ball(B.Data(), size);
180  // Below, we subtrace VecVec(Adiag, Bdiag) to remove double-counting
181  // on the diagonal.
182  return 2.0 * VecVec(Aall, Ball) - VecVec(Adiag, Bdiag);
183  } else
184 #endif
185  {
186  return TraceSpSp(A.Mat(), B.Mat());
187  }
188 }
template double TraceSpSp(const CuSpMatrix< double > &A, const CuSpMatrix< double > &B)
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ TraceSpSp() [2/5]

template float kaldi::TraceSpSp ( const CuSpMatrix< float > &  A,
const CuSpMatrix< float > &  B 
)

◆ TraceSpSp() [3/5]

template float kaldi::TraceSpSp ( const CuSpMatrix< float > &  A,
const CuSpMatrix< double > &  B 
)

◆ TraceSpSp() [4/5]

template double kaldi::TraceSpSp ( const CuSpMatrix< double > &  A,
const CuSpMatrix< float > &  B 
)

◆ TraceSpSp() [5/5]

template double kaldi::TraceSpSp ( const CuSpMatrix< double > &  A,
const CuSpMatrix< double > &  B 
)

◆ TraceSpSp< double, float >()

template double kaldi::TraceSpSp< double, float > ( const SpMatrix< double > &  A,
const SpMatrix< float > &  B 
)

Referenced by TraceSpSp().

◆ TraceSpSp< float, double >()

template float kaldi::TraceSpSp< float, double > ( const SpMatrix< float > &  A,
const SpMatrix< double > &  B 
)

Referenced by TraceSpSp().

◆ TraceSpSpLower() [1/2]

template double kaldi::TraceSpSpLower ( const SpMatrix< double > &  A,
const SpMatrix< double > &  B 
)

◆ TraceSpSpLower() [2/2]

template float kaldi::TraceSpSpLower ( const SpMatrix< float > &  A,
const SpMatrix< float > &  B 
)

◆ TrainOneIter()

void kaldi::TrainOneIter ( const Matrix< BaseFloat > &  feats,
const MleDiagGmmOptions gmm_opts,
int32  iter,
int32  num_threads,
DiagGmm gmm 
)

Definition at line 61 of file gmm-global-init-from-feats.cc.

References AccumDiagGmm::AccumulateFromDiagMultiThreaded(), count, KALDI_LOG, kGmmAll, kUndefined, MleDiagGmmUpdate(), MatrixBase< Real >::NumRows(), and VectorBase< Real >::Set().

Referenced by main().

65  {
66  AccumDiagGmm gmm_acc(*gmm, kGmmAll);
67 
68  Vector<BaseFloat> frame_weights(feats.NumRows(), kUndefined);
69  frame_weights.Set(1.0);
70 
71  double tot_like;
72  tot_like = gmm_acc.AccumulateFromDiagMultiThreaded(*gmm, feats, frame_weights,
73  num_threads);
74 
75  KALDI_LOG << "Likelihood per frame on iteration " << iter
76  << " was " << (tot_like / feats.NumRows()) << " over "
77  << feats.NumRows() << " frames.";
78 
79  BaseFloat objf_change, count;
80  MleDiagGmmUpdate(gmm_opts, gmm_acc, kGmmAll, gmm, &objf_change, &count);
81 
82  KALDI_LOG << "Objective-function change on iteration " << iter << " was "
83  << (objf_change / count) << " over " << count << " frames.";
84 }
void MleDiagGmmUpdate(const MleDiagGmmOptions &config, const AccumDiagGmm &diag_gmm_acc, GmmFlagsType flags, DiagGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out, int32 *floored_elements_out, int32 *floored_gaussians_out, int32 *removed_gaussians_out)
for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model...
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Set(Real f)
Set all members of a vector to a specified value.
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TransformIvectors()

void kaldi::TransformIvectors ( const Matrix< BaseFloat > &  ivectors_in,
const PldaConfig plda_config,
const Plda plda,
Matrix< BaseFloat > *  ivectors_out 
)

Definition at line 87 of file ivector-plda-scoring-dense.cc.

References Plda::Dim(), rnnlm::i, MatrixBase< Real >::NumRows(), Matrix< Real >::Resize(), MatrixBase< Real >::Row(), and Plda::TransformIvector().

Referenced by main().

89  {
90  int32 dim = plda.Dim();
91  ivectors_out->Resize(ivectors_in.NumRows(), dim);
92  for (int32 i = 0; i < ivectors_in.NumRows(); i++) {
93  Vector<BaseFloat> transformed_ivector(dim);
94  plda.TransformIvector(plda_config, ivectors_in.Row(i), 1.0,
95  &transformed_ivector);
96  ivectors_out->Row(i).CopyFromVec(transformed_ivector);
97  }
98 }
double TransformIvector(const PldaConfig &config, const VectorBase< double > &ivector, int32 num_enroll_examples, VectorBase< double > *transformed_ivector) const
Transforms an iVector into a space where the within-class variance is unit and between-class variance...
Definition: plda.cc:120
kaldi::int32 int32
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
int32 Dim() const
Definition: plda.h:140

◆ Trim()

void Trim ( std::string *  str)

Removes the beginning and trailing whitespaces from a string.

Definition at line 92 of file text-utils.cc.

Referenced by ConvertStringToInteger(), ParseOptions::Read(), ParseOptions::ReadConfigFile(), TrimTmp(), and UnitTestRangesMatrix().

92  {
93  const char *white_chars = " \t\n\r\f\v";
94 
95  std::string::size_type pos = str->find_last_not_of(white_chars);
96  if (pos != std::string::npos) {
97  str->erase(pos + 1);
98  pos = str->find_first_not_of(white_chars);
99  if (pos != std::string::npos) str->erase(0, pos);
100  } else {
101  str->erase(str->begin(), str->end());
102  }
103 }

◆ TrimTmp()

std::string kaldi::TrimTmp ( std::string  s)

Definition at line 251 of file text-utils-test.cc.

References Trim().

Referenced by TestTrim().

251  {
252  Trim(&s);
253  return s;
254 }
void Trim(std::string *str)
Removes the beginning and trailing whitespaces from a string.
Definition: text-utils.cc:92

◆ TrimTrailingWhitespace()

void kaldi::TrimTrailingWhitespace ( std::string *  str)

Definition at line 41 of file arpa-file-parser.cc.

Referenced by ArpaFileParser::Read().

41  {
42  str->erase(str->find_last_not_of(" \n\r\t") + 1);
43 }

◆ TypeOneUsage() [1/2]

int32 kaldi::TypeOneUsage ( const ParseOptions po,
BaseFloat  scale1,
BaseFloat  scale2 
)

Definition at line 30 of file matrix-sum.cc.

References MatrixBase< Real >::AddMat(), DeletePointers(), SequentialTableReader< Holder >::Done(), SequentialTableReader< Holder >::FreeCurrent(), ParseOptions::GetArg(), rnnlm::i, KALDI_LOG, KALDI_WARN, SequentialTableReader< Holder >::Key(), kNoTrans, SequentialTableReader< Holder >::Next(), ParseOptions::NumArgs(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), SameDim(), MatrixBase< Real >::Scale(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

32  {
33  int32 num_args = po.NumArgs();
34  std::string matrix_in_fn1 = po.GetArg(1),
35  matrix_out_fn = po.GetArg(num_args);
36 
37  // Output matrix
38  BaseFloatMatrixWriter matrix_writer(matrix_out_fn);
39 
40  // Input matrices
41  SequentialBaseFloatMatrixReader matrix_reader1(matrix_in_fn1);
42  std::vector<RandomAccessBaseFloatMatrixReader*>
43  matrix_readers(num_args-2,
44  static_cast<RandomAccessBaseFloatMatrixReader*>(NULL));
45  std::vector<std::string> matrix_in_fns(num_args-2);
46  for (int32 i = 2; i < num_args; ++i) {
47  matrix_readers[i-2] = new RandomAccessBaseFloatMatrixReader(po.GetArg(i));
48  matrix_in_fns[i-2] = po.GetArg(i);
49  }
50 
51  int32 n_utts = 0, n_total_matrices = 0,
52  n_success = 0, n_missing = 0, n_other_errors = 0;
53 
54  for (; !matrix_reader1.Done(); matrix_reader1.Next()) {
55  std::string key = matrix_reader1.Key();
56  Matrix<BaseFloat> matrix1 = matrix_reader1.Value();
57  matrix_reader1.FreeCurrent();
58  n_utts++;
59  n_total_matrices++;
60 
61  matrix1.Scale(scale1);
62 
63  Matrix<BaseFloat> matrix_out(matrix1);
64 
65  for (int32 i = 0; i < num_args-2; ++i) {
66  if (matrix_readers[i]->HasKey(key)) {
67  Matrix<BaseFloat> matrix2 = matrix_readers[i]->Value(key);
68  n_total_matrices++;
69  if (SameDim(matrix2, matrix_out)) {
70  BaseFloat scale = (i == 0 ? scale2 : 1.0);
71  // note: i == 0 corresponds to the 2nd input archive.
72  matrix_out.AddMat(scale, matrix2, kNoTrans);
73  } else {
74  KALDI_WARN << "Dimension mismatch for utterance " << key
75  << " : " << matrix2.NumRows() << " by "
76  << matrix2.NumCols() << " for "
77  << "system " << (i + 2) << ", rspecifier: "
78  << matrix_in_fns[i] << " vs " << matrix_out.NumRows()
79  << " by " << matrix_out.NumCols()
80  << " primary matrix, rspecifier:" << matrix_in_fn1;
81  n_other_errors++;
82  }
83  } else {
84  KALDI_WARN << "No matrix found for utterance " << key << " for "
85  << "system " << (i + 2) << ", rspecifier: "
86  << matrix_in_fns[i];
87  n_missing++;
88  }
89  }
90 
91  matrix_writer.Write(key, matrix_out);
92  n_success++;
93  }
94 
95  KALDI_LOG << "Processed " << n_utts << " utterances: with a total of "
96  << n_total_matrices << " matrices across " << (num_args-1)
97  << " different systems";
98  KALDI_LOG << "Produced output for " << n_success << " utterances; "
99  << n_missing << " total missing matrices";
100 
101  DeletePointers(&matrix_readers);
102 
103  return (n_success != 0 && n_missing < (n_success - n_missing)) ? 0 : 1;
104 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
RandomAccessTableReader< KaldiObjectHolder< Matrix< BaseFloat > > > RandomAccessBaseFloatMatrixReader
Definition: table-types.h:41
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
bool SameDim(const MatrixBase< Real > &M, const MatrixBase< Real > &N)
float BaseFloat
Definition: kaldi-types.h:29
void Scale(Real alpha)
Multiply each element with a scalar value.
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
int NumArgs() const
Number of positional parameters (c.f. argc-1).
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TypeOneUsage() [2/2]

int32 kaldi::TypeOneUsage ( const ParseOptions po)

Definition at line 36 of file vector-sum.cc.

References VectorBase< Real >::AddVec(), DeletePointers(), VectorBase< Real >::Dim(), SequentialTableReader< Holder >::Done(), SequentialTableReader< Holder >::FreeCurrent(), ParseOptions::GetArg(), rnnlm::i, KALDI_LOG, KALDI_WARN, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), ParseOptions::NumArgs(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

36  {
37  int32 num_args = po.NumArgs();
38  std::string vector_in_fn1 = po.GetArg(1),
39  vector_out_fn = po.GetArg(num_args);
40 
41  // Output vector
42  BaseFloatVectorWriter vector_writer(vector_out_fn);
43 
44  // Input vectors
45  SequentialBaseFloatVectorReader vector_reader1(vector_in_fn1);
46  std::vector<RandomAccessBaseFloatVectorReader*> vector_readers(num_args-2,
47  static_cast<RandomAccessBaseFloatVectorReader*>(NULL));
48  std::vector<std::string> vector_in_fns(num_args-2);
49  for (int32 i = 2; i < num_args; ++i) {
50  vector_readers[i-2] = new RandomAccessBaseFloatVectorReader(po.GetArg(i));
51  vector_in_fns[i-2] = po.GetArg(i);
52  }
53 
54  int32 n_utts = 0, n_total_vectors = 0,
55  n_success = 0, n_missing = 0, n_other_errors = 0;
56 
57  for (; !vector_reader1.Done(); vector_reader1.Next()) {
58  std::string key = vector_reader1.Key();
59  Vector<BaseFloat> vector1 = vector_reader1.Value();
60  vector_reader1.FreeCurrent();
61  n_utts++;
62  n_total_vectors++;
63 
64  Vector<BaseFloat> vector_out(vector1);
65 
66  for (int32 i = 0; i < num_args-2; ++i) {
67  if (vector_readers[i]->HasKey(key)) {
68  Vector<BaseFloat> vector2 = vector_readers[i]->Value(key);
69  n_total_vectors++;
70  if (vector2.Dim() == vector_out.Dim()) {
71  vector_out.AddVec(1.0, vector2);
72  } else {
73  KALDI_WARN << "Dimension mismatch for utterance " << key
74  << " : " << vector2.Dim() << " for "
75  << "system " << (i + 2) << ", rspecifier: "
76  << vector_in_fns[i] << " vs " << vector_out.Dim()
77  << " primary vector, rspecifier:" << vector_in_fn1;
78  n_other_errors++;
79  }
80  } else {
81  KALDI_WARN << "No vector found for utterance " << key << " for "
82  << "system " << (i + 2) << ", rspecifier: "
83  << vector_in_fns[i];
84  n_missing++;
85  }
86  }
87 
88  vector_writer.Write(key, vector_out);
89  n_success++;
90  }
91 
92  KALDI_LOG << "Processed " << n_utts << " utterances: with a total of "
93  << n_total_vectors << " vectors across " << (num_args-1)
94  << " different systems";
95  KALDI_LOG << "Produced output for " << n_success << " utterances; "
96  << n_missing << " total missing vectors";
97 
98  DeletePointers(&vector_readers);
99 
100  return (n_success != 0 && n_missing < (n_success - n_missing)) ? 0 : 1;
101 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
int NumArgs() const
Number of positional parameters (c.f. argc-1).
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...
RandomAccessTableReader< KaldiObjectHolder< Vector< BaseFloat > > > RandomAccessBaseFloatVectorReader
Definition: table-types.h:62

◆ TypeOneUsageAverage()

int32 kaldi::TypeOneUsageAverage ( const ParseOptions po)

Definition at line 106 of file matrix-sum.cc.

References MatrixBase< Real >::AddMat(), DeletePointers(), SequentialTableReader< Holder >::Done(), SequentialTableReader< Holder >::FreeCurrent(), ParseOptions::GetArg(), rnnlm::i, KALDI_LOG, KALDI_WARN, SequentialTableReader< Holder >::Key(), kNoTrans, SequentialTableReader< Holder >::Next(), ParseOptions::NumArgs(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), SameDim(), MatrixBase< Real >::Scale(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

106  {
107  int32 num_args = po.NumArgs();
108  std::string matrix_in_fn1 = po.GetArg(1),
109  matrix_out_fn = po.GetArg(num_args);
110  BaseFloat scale = 1.0 / (num_args - 1);
111 
112  // Output matrix
113  BaseFloatMatrixWriter matrix_writer(matrix_out_fn);
114 
115  // Input matrices
116  SequentialBaseFloatMatrixReader matrix_reader1(matrix_in_fn1);
117  std::vector<RandomAccessBaseFloatMatrixReader*>
118  matrix_readers(num_args-2,
119  static_cast<RandomAccessBaseFloatMatrixReader*>(NULL));
120  std::vector<std::string> matrix_in_fns(num_args-2);
121  for (int32 i = 2; i < num_args; ++i) {
122  matrix_readers[i-2] = new RandomAccessBaseFloatMatrixReader(po.GetArg(i));
123  matrix_in_fns[i-2] = po.GetArg(i);
124  }
125 
126  int32 n_utts = 0, n_total_matrices = 0,
127  n_success = 0, n_missing = 0, n_other_errors = 0;
128 
129  for (; !matrix_reader1.Done(); matrix_reader1.Next()) {
130  std::string key = matrix_reader1.Key();
131  Matrix<BaseFloat> matrix1 = matrix_reader1.Value();
132  matrix_reader1.FreeCurrent();
133  n_utts++;
134  n_total_matrices++;
135 
136  matrix1.Scale(scale);
137 
138  Matrix<BaseFloat> matrix_out(matrix1);
139 
140  for (int32 i = 0; i < num_args-2; ++i) {
141  if (matrix_readers[i]->HasKey(key)) {
142  Matrix<BaseFloat> matrix2 = matrix_readers[i]->Value(key);
143  n_total_matrices++;
144  if (SameDim(matrix2, matrix_out)) {
145  matrix_out.AddMat(scale, matrix2, kNoTrans);
146  } else {
147  KALDI_WARN << "Dimension mismatch for utterance " << key
148  << " : " << matrix2.NumRows() << " by "
149  << matrix2.NumCols() << " for "
150  << "system " << (i + 2) << ", rspecifier: "
151  << matrix_in_fns[i] << " vs " << matrix_out.NumRows()
152  << " by " << matrix_out.NumCols()
153  << " primary matrix, rspecifier:" << matrix_in_fn1;
154  n_other_errors++;
155  }
156  } else {
157  KALDI_WARN << "No matrix found for utterance " << key << " for "
158  << "system " << (i + 2) << ", rspecifier: "
159  << matrix_in_fns[i];
160  n_missing++;
161  }
162  }
163 
164  matrix_writer.Write(key, matrix_out);
165  n_success++;
166  }
167 
168  KALDI_LOG << "Processed " << n_utts << " utterances: with a total of "
169  << n_total_matrices << " matrices across " << (num_args-1)
170  << " different systems";
171  KALDI_LOG << "Produced output for " << n_success << " utterances; "
172  << n_missing << " total missing matrices";
173 
174  DeletePointers(&matrix_readers);
175 
176  return (n_success != 0 && n_missing < (n_success - n_missing)) ? 0 : 1;
177 }
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
RandomAccessTableReader< KaldiObjectHolder< Matrix< BaseFloat > > > RandomAccessBaseFloatMatrixReader
Definition: table-types.h:41
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
void AddMat(const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transA=kNoTrans)
*this += alpha * M [or M^T]
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
bool SameDim(const MatrixBase< Real > &M, const MatrixBase< Real > &N)
float BaseFloat
Definition: kaldi-types.h:29
void Scale(Real alpha)
Multiply each element with a scalar value.
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
int NumArgs() const
Number of positional parameters (c.f. argc-1).
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TypeThreeUsage() [1/2]

int32 kaldi::TypeThreeUsage ( const ParseOptions po,
bool  binary 
)

Definition at line 151 of file vector-sum.cc.

References VectorBase< Real >::AddVec(), ClassifyRspecifier(), ClassifyWspecifier(), VectorBase< Real >::Dim(), ParseOptions::GetArg(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_LOG, kCopyData, kNoRspecifier, kNoWspecifier, ParseOptions::NumArgs(), PrintableWxfilename(), ReadKaldiObject(), Vector< Real >::Resize(), and WriteKaldiObject().

152  {
153  KALDI_ASSERT(po.NumArgs() >= 2);
154  for (int32 i = 1; i < po.NumArgs(); i++) {
155  if (ClassifyRspecifier(po.GetArg(i), NULL, NULL) != kNoRspecifier) {
156  KALDI_ERR << "Wrong usage (type 3): if first and last arguments are not "
157  << "tables, the intermediate arguments must not be tables.";
158  }
159  }
160  if (ClassifyWspecifier(po.GetArg(po.NumArgs()), NULL, NULL, NULL) !=
161  kNoWspecifier) {
162  KALDI_ERR << "Wrong usage (type 3): if first and last arguments are not "
163  << "tables, the intermediate arguments must not be tables.";
164  }
165 
166  Vector<BaseFloat> sum;
167  for (int32 i = 1; i < po.NumArgs(); i++) {
168  Vector<BaseFloat> this_vec;
169  ReadKaldiObject(po.GetArg(i), &this_vec);
170  if (sum.Dim() < this_vec.Dim())
171  sum.Resize(this_vec.Dim(), kCopyData);;
172  sum.AddVec(1.0, this_vec);
173  }
174  WriteKaldiObject(sum, po.GetArg(po.NumArgs()), binary);
175  KALDI_LOG << "Summed " << (po.NumArgs() - 1) << " vectors; "
176  << "wrote sum to " << PrintableWxfilename(po.GetArg(po.NumArgs()));
177  return 0;
178 }
kaldi::int32 int32
void Resize(MatrixIndexT length, MatrixResizeType resize_type=kSetZero)
Set vector to a specified size (can be zero).
RspecifierType ClassifyRspecifier(const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
Definition: kaldi-table.cc:225
void ReadKaldiObject(const std::string &filename, Matrix< float > *m)
Definition: kaldi-io.cc:832
#define KALDI_ERR
Definition: kaldi-error.h:147
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
WspecifierType ClassifyWspecifier(const std::string &wspecifier, std::string *archive_wxfilename, std::string *script_wxfilename, WspecifierOptions *opts)
Definition: kaldi-table.cc:135
int NumArgs() const
Number of positional parameters (c.f. argc-1).
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257
std::string PrintableWxfilename(const std::string &wxfilename)
PrintableWxfilename turns the wxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:73
#define KALDI_LOG
Definition: kaldi-error.h:153
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...

◆ TypeThreeUsage() [2/2]

int32 kaldi::TypeThreeUsage ( const ParseOptions po,
bool  binary,
bool  average 
)

Definition at line 226 of file matrix-sum.cc.

References MatrixBase< Real >::AddMat(), ClassifyRspecifier(), ClassifyWspecifier(), ParseOptions::GetArg(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_LOG, kCopyData, kNoRspecifier, kNoWspecifier, ParseOptions::NumArgs(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), PrintableWxfilename(), ReadKaldiObject(), Matrix< Real >::Resize(), MatrixBase< Real >::Scale(), and WriteKaldiObject().

Referenced by main().

227  {
228  KALDI_ASSERT(po.NumArgs() >= 2);
229  for (int32 i = 1; i < po.NumArgs(); i++) {
230  if (ClassifyRspecifier(po.GetArg(i), NULL, NULL) != kNoRspecifier) {
231  KALDI_ERR << "Wrong usage (type 3): if first and last arguments are not "
232  << "tables, the intermediate arguments must not be tables.";
233  }
234  }
235  if (ClassifyWspecifier(po.GetArg(po.NumArgs()), NULL, NULL, NULL) !=
236  kNoWspecifier) {
237  KALDI_ERR << "Wrong usage (type 3): if first and last arguments are not "
238  << "tables, the intermediate arguments must not be tables.";
239  }
240 
241  Matrix<BaseFloat> sum;
242  for (int32 i = 1; i < po.NumArgs(); i++) {
243  Matrix<BaseFloat> this_mat;
244  ReadKaldiObject(po.GetArg(i), &this_mat);
245  if (sum.NumRows() < this_mat.NumRows() ||
246  sum.NumCols() < this_mat.NumCols())
247  sum.Resize(std::max(sum.NumRows(), this_mat.NumRows()),
248  std::max(sum.NumCols(), this_mat.NumCols()),
249  kCopyData);
250  sum.AddMat(1.0, this_mat);
251  }
252  if (average)
253  sum.Scale(1.0 / (po.NumArgs() - 1));
254  WriteKaldiObject(sum, po.GetArg(po.NumArgs()), binary);
255  KALDI_LOG << "Summed " << (po.NumArgs() - 1) << " matrices; "
256  << "wrote sum to " << PrintableWxfilename(po.GetArg(po.NumArgs()));
257  return 0;
258 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
void AddMat(const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transA=kNoTrans)
*this += alpha * M [or M^T]
kaldi::int32 int32
RspecifierType ClassifyRspecifier(const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
Definition: kaldi-table.cc:225
void ReadKaldiObject(const std::string &filename, Matrix< float > *m)
Definition: kaldi-io.cc:832
void Scale(Real alpha)
Multiply each element with a scalar value.
#define KALDI_ERR
Definition: kaldi-error.h:147
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
WspecifierType ClassifyWspecifier(const std::string &wspecifier, std::string *archive_wxfilename, std::string *script_wxfilename, WspecifierOptions *opts)
Definition: kaldi-table.cc:135
int NumArgs() const
Number of positional parameters (c.f. argc-1).
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257
std::string PrintableWxfilename(const std::string &wxfilename)
PrintableWxfilename turns the wxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:73
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TypeTwoUsage() [1/2]

int32 kaldi::TypeTwoUsage ( const ParseOptions po,
bool  binary,
bool  average = false 
)

Definition at line 103 of file vector-sum.cc.

References ClassifyRspecifier(), ClassifyWspecifier(), VectorBase< Real >::Dim(), ParseOptions::GetArg(), KALDI_ASSERT, KALDI_LOG, KALDI_WARN, kNoRspecifier, kNoWspecifier, ParseOptions::NumArgs(), PrintableWxfilename(), and WriteKaldiObject().

105  {
106  KALDI_ASSERT(po.NumArgs() == 2);
107  KALDI_ASSERT(ClassifyRspecifier(po.GetArg(1), NULL, NULL) != kNoRspecifier &&
108  "vector-sum: first argument must be an rspecifier");
109  // if next assert fails it would be bug in the code as otherwise we shouldn't
110  // be called.
111  KALDI_ASSERT(ClassifyWspecifier(po.GetArg(2), NULL, NULL, NULL) ==
112  kNoWspecifier);
113 
114  SequentialBaseFloatVectorReader vec_reader(po.GetArg(1));
115 
116  Vector<double> sum;
117 
118  int32 num_done = 0, num_err = 0;
119 
120  for (; !vec_reader.Done(); vec_reader.Next()) {
121  const Vector<BaseFloat> &vec = vec_reader.Value();
122  if (vec.Dim() == 0) {
123  KALDI_WARN << "Zero vector input for key " << vec_reader.Key();
124  num_err++;
125  } else {
126  if (sum.Dim() == 0) sum.Resize(vec.Dim());
127  if (sum.Dim() != vec.Dim()) {
128  KALDI_WARN << "Dimension mismatch for key " << vec_reader.Key()
129  << ": " << vec.Dim() << " vs. " << sum.Dim();
130  num_err++;
131  } else {
132  sum.AddVec(1.0, vec);
133  num_done++;
134  }
135  }
136  }
137 
138  if (num_done > 0 && average) sum.Scale(1.0 / num_done);
139 
140  Vector<BaseFloat> sum_float(sum);
141  WriteKaldiObject(sum_float, po.GetArg(2), binary);
142 
143  KALDI_LOG << "Summed " << num_done << " vectors, "
144  << num_err << " with errors; wrote sum to "
145  << PrintableWxfilename(po.GetArg(2));
146  return (num_done > 0 && num_err < num_done) ? 0 : 1;
147 }
kaldi::int32 int32
RspecifierType ClassifyRspecifier(const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
Definition: kaldi-table.cc:225
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
MatrixIndexT Dim() const
Returns the dimension of the vector.
Definition: kaldi-vector.h:64
WspecifierType ClassifyWspecifier(const std::string &wspecifier, std::string *archive_wxfilename, std::string *script_wxfilename, WspecifierOptions *opts)
Definition: kaldi-table.cc:135
int NumArgs() const
Number of positional parameters (c.f. argc-1).
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257
std::string PrintableWxfilename(const std::string &wxfilename)
PrintableWxfilename turns the wxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:73
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ TypeTwoUsage() [2/2]

int32 kaldi::TypeTwoUsage ( const ParseOptions po,
bool  binary 
)

Definition at line 179 of file matrix-sum.cc.

References ClassifyRspecifier(), ClassifyWspecifier(), ParseOptions::GetArg(), KALDI_ASSERT, KALDI_LOG, KALDI_WARN, kNoRspecifier, kNoTrans, kNoWspecifier, ParseOptions::NumArgs(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), PrintableWxfilename(), and WriteKaldiObject().

Referenced by main().

180  {
181  KALDI_ASSERT(po.NumArgs() == 2);
182  KALDI_ASSERT(ClassifyRspecifier(po.GetArg(1), NULL, NULL) != kNoRspecifier &&
183  "matrix-sum: first argument must be an rspecifier");
184  // if next assert fails it would be bug in the code as otherwise we shouldn't
185  // be called.
186  KALDI_ASSERT(ClassifyWspecifier(po.GetArg(2), NULL, NULL, NULL) ==
187  kNoWspecifier);
188 
189  SequentialBaseFloatMatrixReader mat_reader(po.GetArg(1));
190 
191  Matrix<double> sum;
192 
193  int32 num_done = 0, num_err = 0;
194 
195  for (; !mat_reader.Done(); mat_reader.Next()) {
196  const Matrix<BaseFloat> &mat = mat_reader.Value();
197  if (mat.NumRows() == 0) {
198  KALDI_WARN << "Zero matrix input for key " << mat_reader.Key();
199  num_err++;
200  } else {
201  if (sum.NumRows() == 0) sum.Resize(mat.NumRows(), mat.NumCols());
202  if (sum.NumRows() != mat.NumRows() || sum.NumCols() != mat.NumCols()) {
203  KALDI_WARN << "Dimension mismatch for key " << mat_reader.Key()
204  << ": " << mat.NumRows() << " by " << mat.NumCols() << " vs. "
205  << sum.NumRows() << " by " << sum.NumCols();
206  num_err++;
207  } else {
208  Matrix<double> dmat(mat);
209  sum.AddMat(1.0, dmat, kNoTrans);
210  num_done++;
211  }
212  }
213  }
214 
215  Matrix<BaseFloat> sum_float(sum);
216  WriteKaldiObject(sum_float, po.GetArg(2), binary);
217 
218  KALDI_LOG << "Summed " << num_done << " matrices, "
219  << num_err << " with errors; wrote sum to "
220  << PrintableWxfilename(po.GetArg(2));
221  return (num_done > 0 && num_err < num_done) ? 0 : 1;
222 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
RspecifierType ClassifyRspecifier(const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
Definition: kaldi-table.cc:225
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
WspecifierType ClassifyWspecifier(const std::string &wspecifier, std::string *archive_wxfilename, std::string *script_wxfilename, WspecifierOptions *opts)
Definition: kaldi-table.cc:135
int NumArgs() const
Number of positional parameters (c.f. argc-1).
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257
std::string PrintableWxfilename(const std::string &wxfilename)
PrintableWxfilename turns the wxfilename into a more human-readable form for error reporting...
Definition: kaldi-io.cc:73
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ Uniq()

void kaldi::Uniq ( std::vector< T > *  vec)
inline

Removes duplicate elements from a sorted list.

Definition at line 78 of file stl-utils.h.

References IsSorted(), KALDI_ASSERT, and KALDI_PARANOID_ASSERT.

Referenced by TestUniq(), UnitTestTableRandomBothDouble(), and UnitTestTableRandomBothDoubleMatrix().

78  { // must be already sorted.
80  KALDI_ASSERT(vec);
81  vec->erase(std::unique(vec->begin(), vec->end()), vec->end());
82 }
#define KALDI_PARANOID_ASSERT(cond)
Definition: kaldi-error.h:206
bool IsSorted(const std::vector< T > &vec)
Returns true if the vector is sorted.
Definition: stl-utils.h:47
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitInvert()

static void kaldi::UnitInvert ( )
static

Definition at line 151 of file cu-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddVecVec(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), rnnlm::i, KALDI_LOG, kNoTrans, and CuMatrixBase< Real >::SymInvertPosDef().

151  {
152  //MatrixIndexT dim = 15 + Rand() % 40;;
153  MatrixIndexT dim = 8;
154  CuMatrix<Real> A(dim,dim);
155  Matrix<Real> B(dim,dim);
156  Vector<Real> C(dim);
157  for (MatrixIndexT i = 0; i < dim; i++) {
158  B(i,i) = 1;
159  C(i) = i + 1;
160  }
161  B.AddVecVec(1.0,C,C);
162  CuMatrix<Real> tmp(dim,dim);
163  A.CopyFromMat(B);
164  //A.Cholesky();
165  A.CopyToMat(&B);
166  KALDI_LOG << "B is : ";
167  KALDI_LOG << B;
168  A.SymInvertPosDef();
169  Matrix<Real> D(dim,dim);
170  A.CopyToMat(&D);
171  KALDI_LOG << "D is : ";
172  KALDI_LOG << D;
173  Matrix<Real> X(dim,dim);
174  X.AddMatMat(1,B,kNoTrans,D,kNoTrans,0);
175  KALDI_LOG << X;
176  //for (MatrixIndexT i = 0; i < dim; i++) {
177  // for (MatrixIndexT j = i+1; j < dim; j++)
178  // D(i,j) = 0;
179  //}
180  //Matrix<Real> E(dim,dim);
181  //E.AddMatMat(1,D,kNoTrans,D,kTrans,0);
182  //AssertEqual(B,E);
183 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestAddColSumMatSpeed()

static void kaldi::UnitTestAddColSumMatSpeed ( )
static

Definition at line 166 of file matrix-lib-speed-test.cc.

References VectorBase< Real >::AddColSumMat(), Timer::Elapsed(), rnnlm::i, and MatrixBase< Real >::SetRandn().

166  {
167  Timer t;
168  std::vector<MatrixIndexT> sizes;
169  int32 size = 4, num = 5;
170  for(int32 i = 0; i < num; i++) {
171  sizes.push_back(size);
172  size *= 4;
173  }
174 
175  for(size_t i = 0; i < sizes.size(); i++) {
176  MatrixIndexT size = sizes[i];
177  Matrix<Real> M(size, size);
178  M.SetRandn();
179  Vector<Real> Vc(size);
180 
181  int32 iter = 0;
182  BaseFloat time_in_secs = 0.02;
183  Timer t1;
184  for (;t1.Elapsed() < time_in_secs; iter++) {
185  Vc.AddColSumMat(0.4, M, 0.5);
186  }
187 
188  BaseFloat fdim = size;
189  BaseFloat gflops = (fdim * fdim * iter) / (t1.Elapsed() * 1.0e+09);
190  CsvResult<Real>("AddColSumMat", size, gflops, "gigaflops");
191  }
192  CsvResult<Real>(__func__, sizes.size(), t.Elapsed(), "seconds");
193 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestAddDiagMat2()

static void kaldi::UnitTestAddDiagMat2 ( )
static

Definition at line 1986 of file matrix-lib-test.cc.

References VectorBase< Real >::AddDiagMat2(), MatrixBase< Real >::AddMatMat(), VectorBase< Real >::AddVec(), AssertEqual(), VectorBase< Real >::CopyDiagFromMat(), diag, kNoTrans, kTrans, Rand(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

1986  {
1987  for (MatrixIndexT iter = 0; iter < 4; iter++) {
1988  MatrixIndexT dimM = 10 + Rand() % 3,
1989  dimN = 1 + Rand() % 4;
1990  Vector<Real> v(dimM);
1991  v.SetRandn();
1992  Vector<Real> w(v);
1993  if (iter % 2 == 1) {
1994  Matrix<Real> M(dimM, dimN);
1995  M.SetRandn();
1996  v.AddDiagMat2(0.5, M, kNoTrans, 0.3);
1997  Matrix<Real> M2(dimM, dimM);
1998  M2.AddMatMat(1.0, M, kNoTrans, M, kTrans, 0.0);
1999  Vector<Real> diag(dimM);
2000  diag.CopyDiagFromMat(M2);
2001  w.Scale(0.3);
2002  w.AddVec(0.5, diag);
2003  AssertEqual(w, v);
2004  } else {
2005  Matrix<Real> M(dimN, dimM);
2006  M.SetRandn();
2007  v.AddDiagMat2(0.5, M, kTrans, 0.3);
2008  Matrix<Real> M2(dimM, dimM);
2009  M2.AddMatMat(1.0, M, kTrans, M, kNoTrans, 0.0);
2010  Vector<Real> diag(dimM);
2011  diag.CopyDiagFromMat(M2);
2012  w.Scale(0.3);
2013  w.AddVec(0.5, diag);
2014  AssertEqual(w, v);
2015  }
2016  }
2017 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddDiagMatMat()

static void kaldi::UnitTestAddDiagMatMat ( )
static

Definition at line 2020 of file matrix-lib-test.cc.

References VectorBase< Real >::AddDiagMatMat(), MatrixBase< Real >::AddMatMat(), VectorBase< Real >::AddVec(), AssertEqual(), VectorBase< Real >::CopyDiagFromMat(), rnnlm::d, kNoTrans, kTrans, Rand(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

2020  {
2021  for (MatrixIndexT iter = 0; iter < 4; iter++) {
2022  BaseFloat alpha = 0.432 + Rand() % 5, beta = 0.043 + Rand() % 2;
2023  MatrixIndexT dimM = 10 + Rand() % 3,
2024  dimN = 5 + Rand() % 4;
2025  Vector<Real> v(dimM);
2026  Matrix<Real> M_orig(dimM, dimN), N_orig(dimN, dimM);
2027  M_orig.SetRandn();
2028  N_orig.SetRandn();
2029  MatrixTransposeType transM = (iter % 2 == 0 ? kNoTrans : kTrans);
2030  MatrixTransposeType transN = ((iter/2) % 2 == 0 ? kNoTrans : kTrans);
2031  Matrix<Real> M(M_orig, transM), N(N_orig, transN);
2032 
2033  v.SetRandn();
2034  Vector<Real> w(v);
2035 
2036  w.AddDiagMatMat(alpha, M, transM, N, transN, beta);
2037 
2038  {
2039  Vector<Real> w2(v);
2040  Matrix<Real> MN(dimM, dimM);
2041  MN.AddMatMat(1.0, M, transM, N, transN, 0.0);
2042  Vector<Real> d(dimM);
2043  d.CopyDiagFromMat(MN);
2044  w2.Scale(beta);
2045  w2.AddVec(alpha, d);
2046  AssertEqual(w, w2);
2047  }
2048  }
2049 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddDiagVecMat()

static void kaldi::UnitTestAddDiagVecMat ( )
static

Definition at line 190 of file matrix-lib-test.cc.

References VectorBase< Real >::AddVec(), AssertEqual(), VectorBase< Real >::CopyColFromMat(), VectorBase< Real >::CopyFromVec(), KALDI_ASSERT, kNoTrans, kTrans, Rand(), MatrixBase< Real >::Row(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and Matrix< Real >::Transpose().

190  {
191  for (int p = 0; p < 2; p++) {
192  MatrixIndexT dimM = 100 + Rand() % 255, dimN = 100 + Rand() % 255;
193  Real alpha = 0.43243, beta = 1.423;
194  Matrix<Real> M(dimM, dimN), N(dimM, dimN);
195  M.SetRandn();
196  N.SetRandn();
197  MatrixTransposeType trans = (p % 2 == 0 ? kNoTrans : kTrans);
198  if (trans == kTrans)
199  N.Transpose();
200 
201  Vector<Real> V(dimM);
202  V.SetRandn();
203 
204  Matrix<Real> Mcheck(M);
205  for (int32 r = 0; r < dimM; r++) {
206  SubVector<Real> Mcheckrow(Mcheck, r);
207  Vector<Real> Nrow(dimN);
208  if (trans == kTrans) Nrow.CopyColFromMat(N, r);
209  else Nrow.CopyFromVec(N.Row(r));
210  Mcheckrow.Scale(beta);
211  Mcheckrow.AddVec(alpha * V(r), Nrow);
212  }
213 
214  M.AddDiagVecMat(alpha, V, N, trans, beta);
215  AssertEqual(M, Mcheck);
216  KALDI_ASSERT(M.Sum() != 0.0);
217  }
218 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestAddMat2()

static void kaldi::UnitTestAddMat2 ( )
static

Definition at line 2944 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), AssertEqual(), MatrixBase< Real >::CopyFromSp(), rnnlm::i, kNoTrans, kTakeLower, kTrans, Rand(), Matrix< Real >::Resize(), PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::SymAddMat2().

2944  {
2945  MatrixIndexT extra = 1;
2946  // Test AddMat2 function of SpMatrix.
2947  for (MatrixIndexT i = 0; i < 5; i++) {
2948  MatrixIndexT dimM = (Rand()%10) + extra,
2949  dimN = (Rand() % 10) + extra;
2950  Real alpha = 0.2 * (Rand() % 6),
2951  beta = 0.2 * (Rand() % 6);
2952  SpMatrix<Real> S(dimM);
2953  S.SetRandn();
2954  MatrixTransposeType trans = (i % 2 == 1 ? kTrans: kNoTrans),
2955  other_trans = (trans == kTrans ? kNoTrans : kTrans);
2956  Matrix<Real> M;
2957  if (trans == kNoTrans) M.Resize(dimM, dimN);
2958  else M.Resize(dimN, dimM);
2959  M.SetRandn();
2960 
2961  Matrix<Real> Sfull(S), Sfull2(S);
2962 
2963  S.AddMat2(alpha, M, trans, beta);
2964 
2965  Sfull.AddMatMat(alpha, M, trans, M, other_trans, beta);
2966 
2967  Sfull2.SymAddMat2(alpha, M, trans, beta);
2968 
2969  // now symmetrize.
2970  SpMatrix<Real> Sfull2_copy(Sfull2, kTakeLower);
2971  Sfull2.CopyFromSp(Sfull2_copy);
2972 
2973  Matrix<Real> Sfull3(S);
2974  AssertEqual(Sfull, Sfull3);
2975  AssertEqual(Sfull2, Sfull3);
2976  }
2977 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
void SetRandn()
Sets to random values of a normal distribution.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

◆ UnitTestAddMat2Sp()

static void kaldi::UnitTestAddMat2Sp ( )
static

Definition at line 2903 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddMatSp(), SpMatrix< Real >::AddSmat2Sp(), AssertEqual(), rnnlm::i, kNoTrans, kTrans, Rand(), PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and Matrix< Real >::Transpose().

2903  {
2904  for (MatrixIndexT i = 0; i < 5; i++) {
2905  MatrixIndexT dimM = (Rand()%10) + 1,
2906  dimN = (Rand()%10 + 1);
2907  BaseFloat alpha = 0.8, beta = 0.9;
2908  SpMatrix<Real> S(dimM), T(dimN);
2909  S.SetRandn();
2910  T.SetRandn();
2911  Matrix<Real> M(dimM, dimN);
2912  M.SetRandn();
2913  MatrixTransposeType trans = (i % 2 == 1 ? kTrans: kNoTrans);
2914  if (trans == kTrans) M.Transpose();
2915  SpMatrix<Real> S2(S), S3(S);
2916  S.AddMat2Sp(alpha, M, trans, T, beta);
2917  S3.AddSmat2Sp(alpha, M, trans, T, beta);
2918 
2919  // M[trans?] * T.
2920  Matrix<Real> A(dimM, dimN);
2921  A.AddMatSp(1.0, M, trans, T, 0.0);
2922  Matrix<Real> B(dimM, dimM); // M[trans] * T * M[trans]'
2923  B.AddMatMat(1.0, A, kNoTrans, M, trans == kTrans ? kNoTrans : kTrans, 0.0);
2924  SpMatrix<Real> tmp(B);
2925  S2.Scale(beta);
2926  S2.AddSp(alpha, tmp);
2927  AssertEqual(S, S2);
2928  AssertEqual(S, S3);
2929  }
2930 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddMatDiagVec()

static void kaldi::UnitTestAddMatDiagVec ( )
static

Definition at line 220 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMat(), AssertEqual(), MatrixBase< Real >::CopyFromMat(), KALDI_ASSERT, kNoTrans, kTrans, MatrixBase< Real >::MulColsVec(), Rand(), MatrixBase< Real >::Scale(), and VectorBase< Real >::SetRandn().

220  {
221  // M <- alpha * N[^T] * diag(v) + beta * M
222  for (int p = 0; p < 2; p++) {
223  MatrixIndexT dimM = 100 + Rand() % 255, dimN = 100 + Rand() % 255;
224  Real alpha = 0.43243, beta = 1.423;
225 
226  Matrix<Real> M(dimM, dimN), N(dimM, dimN), buf(dimM, dimN);
227  M.SetRandn();
228  N.SetRandn();
229  buf.CopyFromMat(N);
230  MatrixTransposeType trans = (p % 2 == 0 ? kNoTrans : kTrans);
231  if (trans == kTrans)
232  N.Transpose();
233 
234  Vector<Real> V(dimN);
235  V.SetRandn();
236 
237  Matrix<Real> Mcheck(M);
238  Mcheck.Scale(beta);
239  buf.MulColsVec(V);
240  Mcheck.AddMat(alpha, buf, kNoTrans);
241 
242  M.AddMatDiagVec(alpha, N, trans, V, beta);
243  AssertEqual(M, Mcheck);
244  KALDI_ASSERT(M.Sum() != 0.0);
245  }
246 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddMatMatElements()

static void kaldi::UnitTestAddMatMatElements ( )
static

Definition at line 248 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMat(), AssertEqual(), MatrixBase< Real >::CopyFromMat(), KALDI_ASSERT, kNoTrans, MatrixBase< Real >::MulElements(), Rand(), and MatrixBase< Real >::Scale().

248  {
249  // M <- alpha *(A .* B) + beta * M
250  MatrixIndexT dimM = 100 + Rand() % 255, dimN = 100 + Rand() % 255;
251  Real alpha = 0.43243, beta = 1.423;
252  Matrix<Real> M(dimM, dimN), A(dimM, dimN), B(dimM, dimN), buf(dimM, dimN);
253  M.SetRandn();
254  A.SetRandn();
255  B.SetRandn();
256 
257  Matrix<Real> Mcheck(M);
258  buf.CopyFromMat(A); buf.MulElements(B);
259  Mcheck.Scale(beta); Mcheck.AddMat(alpha, buf, kNoTrans);
260 
261  M.AddMatMatElements(alpha, A, B, beta);
262  AssertEqual(M, Mcheck);
263  KALDI_ASSERT(M.Sum() != 0.0);
264 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddMatMatNans()

static void kaldi::UnitTestAddMatMatNans ( )
static

Definition at line 4503 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), rnnlm::i, KALDI_ASSERT, kNoTrans, PlaceNansInGaps(), RandInt(), and MatrixBase< Real >::Sum().

4503  {
4504  for (int32 i = 0; i < 200; i++) {
4505  int32 num_rows = RandInt(1, 256), mid = RandInt(1, 256), num_cols = RandInt(1, 256);
4506  Matrix<Real> mat1(num_rows, mid), mat2(mid, num_cols), prod(num_rows, num_cols);
4507  PlaceNansInGaps(&mat1);
4508  PlaceNansInGaps(&mat2);
4509  prod.AddMatMat(1.0, mat1, kNoTrans, mat2, kNoTrans, 0.0);
4510  // make sure the nan's don't propagate.
4511  KALDI_ASSERT(prod.Sum() == 0.0 &&
4512  "The BLAS library that you are linking against has an issue that might "
4513  "cause problems later on.");
4514  }
4515 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
void PlaceNansInGaps(Matrix< Real > *mat)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestAddMatMatSpeed()

static void kaldi::UnitTestAddMatMatSpeed ( )
static

Definition at line 112 of file matrix-lib-speed-test.cc.

References MatrixBase< Real >::AddMatMat(), Timer::Elapsed(), rnnlm::i, rnnlm::j, kNoTrans, and kTrans.

112  {
113  Timer t;
114  std::vector<MatrixIndexT> sizes;
115  sizes.push_back(512);
116  sizes.push_back(1024);
117  for (size_t i = 0; i < sizes.size(); i++) {
118  MatrixIndexT size = sizes[i];
119  {
120  Timer t1;
121  for (int32 j=0; j<2; j++) {
122  Matrix<Real> A(size,size), B(size,size), C(size,size);
123  A.SetRandn(); B.SetRandn();
124  C.AddMatMat(1.0, A, kNoTrans, B, kNoTrans, 0.0);
125  C.AddMatMat(1.0, A, kNoTrans, B, kTrans, 0.0);
126  C.AddMatMat(1.0, A, kTrans, B, kNoTrans, 0.0);
127  C.AddMatMat(1.0, A, kTrans, B, kTrans, 0.0);
128  }
129  CsvResult<Real>("AddMatMat", size, t1.Elapsed(), "seconds");
130  }
131  }
132  CsvResult<Real>(__func__, sizes.size(), t.Elapsed(), "seconds");
133 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestAddMatSelf()

static void kaldi::UnitTestAddMatSelf ( )
static

Definition at line 2932 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMat(), AssertEqual(), kTrans, and Rand().

2932  {
2933  MatrixIndexT dimM = (Rand() % 10) + 1;
2934  Matrix<Real> M(dimM, dimM), N(dimM, dimM);
2935  M.SetRandn();
2936  N.AddMat(1.5, M);
2937  M.AddMat(0.5, M);
2938  AssertEqual(M, N);
2939  N.AddMat(0.5, M, kTrans);
2940  M.AddMat(0.5, M, kTrans);
2941  AssertEqual(M, N);
2942 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddMatSmat()

static void kaldi::UnitTestAddMatSmat ( )
static

Definition at line 2880 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddSmatMat(), AssertEqual(), rnnlm::i, kNoTrans, kTrans, Rand(), MatrixBase< Real >::SetRandn(), and Matrix< Real >::Transpose().

2880  {
2881  for (MatrixIndexT i = 0; i < 6; i++) {
2882  MatrixIndexT dimM = (Rand()%10) + 1,
2883  dimN = (Rand()%10 + 1),
2884  dimO = (Rand()%10 + 1);
2885  MatrixTransposeType transB = (i % 2 == 0 ? kTrans : kNoTrans),
2886  transC = (i % 3 == 0 ? kTrans : kNoTrans);
2887  Matrix<Real> A(dimM, dimN),
2888  B(dimM, dimO), C(dimO, dimN);
2889  A.SetRandn(); B.SetRandn(); C.SetRandn();
2890  if (transB == kTrans) B.Transpose();
2891  if (transC == kTrans) C.Transpose();
2892  Matrix<Real> A2(A), A3(A);
2893  BaseFloat beta = 0.333, alpha = 0.5;
2894  A.AddMatMat(alpha, B, transB, C, transC, beta);
2895  A2.AddMatSmat(alpha, B, transB, C, transC, beta);
2896  A3.AddSmatMat(alpha, B, transB, C, transC, beta);
2897  AssertEqual(A, A2);
2898  AssertEqual(A, A3);
2899  }
2900 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddOuterProductPlusMinus()

static void kaldi::UnitTestAddOuterProductPlusMinus ( )
static

Definition at line 1136 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMat(), AddOuterProductPlusMinus(), AssertEqual(), rnnlm::i, KALDI_ASSERT, fst::Plus(), Rand(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetZero().

1136  {
1137  for (MatrixIndexT iter = 0; iter < 10; iter++) {
1138  MatrixIndexT dimM = 10 + Rand() % 10;
1139  MatrixIndexT dimN = 10 + Rand() % 10;
1140  Matrix<Real> M(dimM, dimN), Plus(dimM, dimN), Minus(dimM, dimN),
1141  M2(dimM, dimN);
1142  Vector<Real> v1(dimM), v2(dimN);
1143 
1144  for (MatrixIndexT i = 0; i < 5; i++) {
1145  v1.SetRandn();
1146  v2.SetRandn();
1147  Real alpha = 0.333 * ((Rand() % 10) - 5);
1148  M.AddVecVec(alpha, v1, v2);
1149 
1150  AddOuterProductPlusMinus(alpha, v1, v2, &Plus, &Minus);
1151  M2.SetZero();
1152  M2.AddMat(-1.0, Minus);
1153  M2.AddMat(1.0, Plus);
1154  AssertEqual(M, M2);
1155  KALDI_ASSERT(Minus.Min() >= 0);
1156  KALDI_ASSERT(Plus.Min() >= 0);
1157  }
1158  }
1159 }
LatticeWeightTpl< FloatType > Plus(const LatticeWeightTpl< FloatType > &w1, const LatticeWeightTpl< FloatType > &w2)
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
void AddOuterProductPlusMinus(Real alpha, const VectorBase< Real > &a, const VectorBase< Real > &b, MatrixBase< Real > *plus, MatrixBase< Real > *minus)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddRows()

static void kaldi::UnitTestAddRows ( )
static

Definition at line 779 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, rnnlm::j, Rand(), MatrixBase< Real >::RowData(), and MatrixBase< Real >::SetRandn().

779  {
780  for (MatrixIndexT p = 0; p < 10; p++) {
781  MatrixIndexT num_rows1 = 10 + Rand() % 10,
782  num_rows2 = 10 + Rand() % 10,
783  num_cols = 10 + Rand() % 10;
784  Matrix<Real> M(num_rows1, num_cols);
785  M.SetRandn();
786 
787  Matrix<Real> N1(num_rows2, num_cols),
788  N2(num_rows2, num_cols), O(num_rows2, num_cols);
789  std::vector<int32> reorder(num_rows2);
790  std::vector<const Real*> reorder_src(num_rows2,
791  static_cast<const Real*>(NULL));
792  for (int32 i = 0; i < num_rows2; i++) {
793  reorder[i] = -1 + (Rand() % (num_rows1 + 1));
794  if (reorder[i] != -1)
795  reorder_src[i] = M.RowData(reorder[i]);
796  }
797 
798  Real alpha =
799  static_cast<Real>((Rand() % num_rows2)) / static_cast<Real>(num_rows1);
800 
801  N1.AddRows(alpha, M, &(reorder[0]));
802  N2.AddRows(alpha, &(reorder_src[0]));
803 
804  for (int32 i = 0; i < num_rows2; i++) {
805  if (reorder[i] != -1) {
806  for (int32 j = 0; j < num_cols; j++) {
807  O(i, j) += alpha * M(reorder[i], j);
808  }
809  }
810  }
811 
812  AssertEqual(N1, O);
813  AssertEqual(N2, O);
814  }
815 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddRowSumMatSpeed()

static void kaldi::UnitTestAddRowSumMatSpeed ( )
static

Definition at line 136 of file matrix-lib-speed-test.cc.

References VectorBase< Real >::AddRowSumMat(), Timer::Elapsed(), rnnlm::i, and MatrixBase< Real >::SetRandn().

136  {
137  Timer t;
138  std::vector<MatrixIndexT> sizes;
139  int32 size = 4, num = 5;
140  for(int32 i = 0; i < num; i++) {
141  sizes.push_back(size);
142  size *= 4;
143  }
144 
145  for(size_t i = 0; i < sizes.size(); i++) {
146  MatrixIndexT size = sizes[i];
147  Matrix<Real> M(size, size);
148  M.SetRandn();
149  Vector<Real> Vr(size);
150 
151  int32 iter = 0;
152  BaseFloat time_in_secs = 0.02;
153  Timer t1;
154  for (;t1.Elapsed() < time_in_secs; iter++) {
155  Vr.AddRowSumMat(0.4, M, 0.5);
156  }
157 
158  BaseFloat fdim = size;
159  BaseFloat gflops = (fdim * fdim * iter) / (t1.Elapsed() * 1.0e+09);
160  CsvResult<Real>("AddRowSumMat", size, gflops, "gigaflops");
161  }
162  CsvResult<Real>(__func__, sizes.size(), t.Elapsed(), "seconds");
163 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestAddSp()

static void kaldi::UnitTestAddSp ( )
static

Definition at line 266 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddSp(), AssertEqual(), rnnlm::i, Rand(), and PackedMatrix< Real >::SetRandn().

266  {
267  for (MatrixIndexT i = 0;i< 10;i++) {
268  MatrixIndexT dimM = 10+Rand()%10;
269  SpMatrix<Real> S(dimM);
270  S.SetRandn();
271  Matrix<Real> M(S), N(S);
272  N.AddSp(2.0, S);
273  M.Scale(3.0);
274  AssertEqual(M, N);
275  }
276 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddToDiag()

static void kaldi::UnitTestAddToDiag ( )
static

Definition at line 2831 of file matrix-lib-test.cc.

References PackedMatrix< Real >::AddToDiag(), AssertEqual(), rnnlm::i, Rand(), and PackedMatrix< Real >::SetRandn().

2831  {
2832  MatrixIndexT N = 1 + Rand() % 10;
2833  SpMatrix<Real> S(N);
2834  S.SetRandn();
2835  SpMatrix<Real> S2(S);
2836  Real x = 0.5;
2837  S.AddToDiag(x);
2838  for (MatrixIndexT i = 0; i < N; i++) S2(i, i) += x;
2839  AssertEqual(S, S2);
2840 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddToDiagMatrix()

static void kaldi::UnitTestAddToDiagMatrix ( )
static

Definition at line 177 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, and Rand().

177  {
178  for (int p = 0; p < 2; p++) {
179  MatrixIndexT dimM = 10 + Rand() % 2, dimN = 1 + Rand() % 5;
180  Matrix<Real> M(dimM, dimN), Mcopy(M);
181  BaseFloat alpha = 0.35;
182  M.AddToDiag(alpha);
183  for (MatrixIndexT i = 0; i < dimM && i < dimN; i++)
184  Mcopy(i, i) += alpha;
185  AssertEqual(M, Mcopy);
186  }
187 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddToRows()

static void kaldi::UnitTestAddToRows ( )
static

Definition at line 818 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddToRows(), AssertEqual(), rnnlm::i, rnnlm::j, Rand(), and MatrixBase< Real >::SetRandn().

818  {
819  for (MatrixIndexT p = 0; p < 10; p++) {
820  MatrixIndexT num_rows1 = 10 + Rand() % 10,
821  num_rows2 = 10 + Rand() % 10,
822  num_cols = 10 + Rand() % 10;
823  Matrix<Real> M(num_rows1, num_cols);
824  M.SetRandn();
825 
826  Real alpha =
827  static_cast<Real>((Rand() % num_rows2)) / static_cast<Real>(num_rows1);
828 
829  Matrix<Real> N(num_rows2, num_cols), O(num_rows2, num_cols);
830  std::vector<Real*> reorder_dst(num_rows1, static_cast<Real*>(NULL));
831  unordered_map<MatrixIndexT, bool> used_index;
832  for (int32 i = 0; i < num_rows1; i++) {
833  MatrixIndexT index = -1 + (Rand() % (num_rows2 + 1));
834  if (used_index.find(index) == used_index.end()) {
835  used_index[index] = true;
836  } else {
837  index = -1;
838  }
839  if (index != -1) {
840  reorder_dst[i] = N.RowData(index);
841  for (int32 j = 0; j < num_cols; j++)
842  O(index, j) += alpha * M(i, j);
843  }
844  }
845 
846  M.AddToRows(alpha, &(reorder_dst[0]));
847 
848  AssertEqual(N, O);
849  }
850 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddVec2Sp()

static void kaldi::UnitTestAddVec2Sp ( )
static

Definition at line 3519 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2Sp(), SpMatrix< Real >::AddVec2Sp(), AssertEqual(), MatrixBase< Real >::CopyDiagFromVec(), rnnlm::i, kNoTrans, Rand(), VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

3519  {
3520  for (int32 i = 0; i < 10; i++) {
3521  int32 dim = Rand() % 5;
3522  SpMatrix<Real> S(dim);
3523  S.SetRandn();
3524  Vector<Real> v(dim);
3525  v.SetRandn();
3526  Matrix<Real> M(dim, dim);
3527  M.CopyDiagFromVec(v);
3528 
3529  SpMatrix<Real> T1(dim);
3530  T1.SetRandn();
3531  SpMatrix<Real> T2(T1);
3532  Real alpha = 0.33, beta = 4.5;
3533  T1.AddVec2Sp(alpha, v, S, beta);
3534  T2.AddMat2Sp(alpha, M, kNoTrans, S, beta);
3535  AssertEqual(T1, T2);
3536  }
3537 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddVecCross()

void kaldi::UnitTestAddVecCross ( )

Definition at line 3814 of file matrix-lib-test.cc.

References VectorBase< Real >::AddVec(), VectorBase< Real >::AddVec2(), AssertEqual(), rnnlm::i, and VectorBase< Real >::SetRandn().

Referenced by MatrixUnitTest().

3814  {
3815 
3816  Vector<float> v(5);
3817  v.SetRandn();
3818  Vector<double> w(5);
3819  w.SetRandn();
3820 
3821  Vector<float> wf(w);
3822 
3823  for (MatrixIndexT i = 0; i < 2; i++) {
3824  float f = 1.0;
3825  if (i == 0) f = 2.0;
3826 
3827  {
3828  Vector<float> sum1(5);
3829  Vector<double> sum2(5);
3830  Vector<float> sum3(5);
3831  sum1.AddVec(f, v); sum1.AddVec(f, w);
3832  sum2.AddVec(f, v); sum2.AddVec(f, w);
3833  sum3.AddVec(f, v); sum3.AddVec(f, wf);
3834  Vector<float> sum2b(sum2);
3835  AssertEqual(sum1, sum2b);
3836  AssertEqual(sum1, sum3);
3837  }
3838 
3839  {
3840  Vector<float> sum1(5);
3841  Vector<double> sum2(5);
3842  Vector<float> sum3(5);
3843  sum1.AddVec2(f, v); sum1.AddVec2(f, w);
3844  sum2.AddVec2(f, v); sum2.AddVec2(f, w);
3845  sum3.AddVec2(f, v); sum3.AddVec2(f, wf);
3846  Vector<float> sum2b(sum2);
3847  AssertEqual(sum1, sum2b);
3848  AssertEqual(sum1, sum3);
3849  }
3850  }
3851 }
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddVecToCols()

static void kaldi::UnitTestAddVecToCols ( )
static

Definition at line 3540 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddVecToCols(), MatrixBase< Real >::AddVecVec(), AssertEqual(), rnnlm::i, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), VectorBase< Real >::Set(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

3540  {
3541  std::vector<Real> sizes;
3542  sizes.push_back(16);
3543  sizes.push_back(128);
3544  for (int i = 0; i < 2; i++) {
3545  MatrixIndexT dimM = sizes[i] + Rand() % 10, dimN = sizes[i] + Rand() % 10;
3546  Matrix<Real> M(dimM, dimN);
3547  M.SetRandn();
3548  Vector<float> v(M.NumRows());
3549  v.SetRandn();
3550  Matrix<Real> N(M);
3551  Vector<float> ones(M.NumCols());
3552  ones.Set(1.0);
3553  M.AddVecToCols(0.5, v);
3554  N.AddVecVec(0.5, v, ones);
3555  AssertEqual(M, N);
3556  }
3557 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void SetRandn()
Set vector to random normally-distributed noise.
void Set(Real f)
Set all members of a vector to a specified value.
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddVecToColsSpeed()

static void kaldi::UnitTestAddVecToColsSpeed ( )
static

Definition at line 227 of file matrix-lib-speed-test.cc.

References MatrixBase< Real >::AddVecToCols(), Timer::Elapsed(), rnnlm::i, VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

227  {
228  Timer t;
229  std::vector<MatrixIndexT> sizes;
230  int32 size = 4, num = 5;
231  for(int32 i = 0; i < num; i++) {
232  sizes.push_back(size);
233  size *= 4;
234  }
235 
236  for(size_t i = 0; i < sizes.size(); i++) {
237  MatrixIndexT size = sizes[i];
238  Matrix<Real> M(size, size);
239  M.SetRandn();
240  Vector<Real> Vr(size);
241  Vr.SetRandn();
242 
243  int32 iter = 0;
244  BaseFloat time_in_secs = 0.02;
245  Timer t1;
246  for (;t1.Elapsed() < time_in_secs; iter++) {
247  M.AddVecToCols(0.5, Vr);
248  }
249 
250  BaseFloat fdim = size;
251  BaseFloat gflops = (fdim * fdim * iter) / (t1.Elapsed() * 1.0e+09);
252  CsvResult<Real>("AddVecToCols", size, gflops, "gigaflops");
253  }
254  CsvResult<Real>(__func__, sizes.size(), t.Elapsed(), "seconds");
255 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestAddVecToRows()

static void kaldi::UnitTestAddVecToRows ( )
static

Definition at line 3500 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddVecToRows(), MatrixBase< Real >::AddVecVec(), AssertEqual(), rnnlm::i, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), VectorBase< Real >::Set(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

3500  {
3501  std::vector<Real> sizes;
3502  sizes.push_back(16);
3503  sizes.push_back(128);
3504  for (int i = 0; i < 2; i++) {
3505  MatrixIndexT dimM = sizes[i] + Rand() % 10, dimN = sizes[i] + Rand() % 10;
3506  Matrix<Real> M(dimM, dimN);
3507  M.SetRandn();
3508  Vector<float> v(M.NumCols());
3509  v.SetRandn();
3510  Matrix<Real> N(M);
3511  Vector<float> ones(M.NumRows());
3512  ones.Set(1.0);
3513  M.AddVecToRows(0.5, v);
3514  N.AddVecVec(0.5, ones, v);
3515  AssertEqual(M, N);
3516  }
3517 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void SetRandn()
Set vector to random normally-distributed noise.
void Set(Real f)
Set all members of a vector to a specified value.
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAddVecToRowsSpeed()

static void kaldi::UnitTestAddVecToRowsSpeed ( )
static

Definition at line 196 of file matrix-lib-speed-test.cc.

References MatrixBase< Real >::AddVecToRows(), Timer::Elapsed(), rnnlm::i, VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

196  {
197  Timer t;
198  std::vector<MatrixIndexT> sizes;
199  int32 size = 4, num = 5;
200  for(int32 i = 0; i < num; i++) {
201  sizes.push_back(size);
202  size *= 4;
203  }
204 
205  for(size_t i = 0; i < sizes.size(); i++) {
206  MatrixIndexT size = sizes[i];
207  Matrix<Real> M(size, size);
208  M.SetRandn();
209  Vector<Real> Vc(size);
210  Vc.SetRandn();
211 
212  int32 iter = 0;
213  BaseFloat time_in_secs = 0.02;
214  Timer t1;
215  for (;t1.Elapsed() < time_in_secs; iter++) {
216  M.AddVecToRows(0.5, Vc);
217  }
218 
219  BaseFloat fdim = size;
220  BaseFloat gflops = (fdim * fdim * iter) / (t1.Elapsed() * 1.0e+09);
221  CsvResult<Real>("AddVecToRows", size, gflops, "gigaflops");
222  }
223  CsvResult<Real>(__func__, sizes.size(), t.Elapsed(), "seconds");
224 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestAddVecVec()

static void kaldi::UnitTestAddVecVec ( )
static

Definition at line 1749 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddVecVec(), AssertEqual(), rnnlm::i, rnnlm::j, Rand(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

1749  {
1750  for (int32 i = 0; i < 20; i++) {
1751  int32 dimM = 5 + Rand() % 10, dimN = 5 + Rand() % 10;
1752 
1753  Matrix<Real> M(dimM, dimN);
1754  M.SetRandn();
1755  Matrix<Real> N(M);
1756  Vector<float> v(dimM), w(dimN);
1757  v.SetRandn();
1758  w.SetRandn();
1759  float alpha = 0.2 * (Rand() % 10);
1760  M.AddVecVec(alpha, v, w);
1761  for (int32 j = 0; j < 20; j++) {
1762  int32 dimX = Rand() % dimM, dimY = Rand() % dimN;
1763  AssertEqual(M(dimX, dimY),
1764  N(dimX, dimY) + alpha * v(dimX) * w(dimY));
1765  }
1766  }
1767 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestApplyExpSpecial()

static void kaldi::UnitTestApplyExpSpecial ( )
static

Definition at line 2800 of file matrix-lib-test.cc.

References MatrixBase< Real >::Add(), MatrixBase< Real >::ApplyExpSpecial(), MatrixBase< Real >::ApplyFloor(), AssertEqual(), KALDI_LOG, RandInt(), and MatrixBase< Real >::SetRandn().

2800  {
2801  int32 rows = RandInt(1, 10), cols = RandInt(1, 10);
2802  Matrix<Real> mat(rows, cols);
2803  mat.SetRandn();
2804  Matrix<Real> A(mat), B(mat);
2805  A.ApplyExp();
2806  B.Add(1.0);
2807  B.ApplyFloor(1.0);
2808  A.Min(B); // min of exp(x) and max(1.0, x + 1).
2809  mat.ApplyExpSpecial();
2810  KALDI_LOG << "A is: " << A;
2811  AssertEqual(mat, A);
2812 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestApproxEqual()

void kaldi::UnitTestApproxEqual ( )

Definition at line 255 of file kaldi-math-test.cc.

References ApproxEqual(), and KALDI_ASSERT.

Referenced by main().

255  {
256  KALDI_ASSERT(ApproxEqual(1.0, 1.00001));
257  KALDI_ASSERT(ApproxEqual(1.0, 1.00001, 0.001));
258  KALDI_ASSERT(!ApproxEqual(1.0, 1.1));
259  KALDI_ASSERT(!ApproxEqual(1.0, 1.01, 0.001));
260  KALDI_ASSERT(!ApproxEqual(1.0, 0.0));
261  KALDI_ASSERT(ApproxEqual(0.0, 0.0));
262  KALDI_ASSERT(!ApproxEqual(0.0, 0.00001));
263  KALDI_ASSERT(!ApproxEqual(std::numeric_limits<float>::infinity(),
264  -std::numeric_limits<float>::infinity()));
265  KALDI_ASSERT(ApproxEqual(std::numeric_limits<float>::infinity(),
266  std::numeric_limits<float>::infinity()));
267  KALDI_ASSERT(ApproxEqual(-std::numeric_limits<float>::infinity(),
268  -std::numeric_limits<float>::infinity()));
269  KALDI_ASSERT(!ApproxEqual(-std::numeric_limits<float>::infinity(),
270  0));
271  KALDI_ASSERT(!ApproxEqual(-std::numeric_limits<float>::infinity(),
272  1));
273 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestAssertFunc()

void kaldi::UnitTestAssertFunc ( )

Definition at line 220 of file kaldi-math-test.cc.

References AssertEqual(), rnnlm::i, and Rand().

Referenced by main().

220  { // Testing Assert** *functions
221  for (int i = 1; i < 100; i++) {
222  float f1 = Rand() % 10000 + 1, f2 = Rand() % 20 + 1;
223  float tmp1 = f1 * f2;
224  float tmp2 = (1/f1 + 1/f2);
225  float add = f1 + f2;
226  float addeql = tmp1 * tmp2;
227  float thresh = 0.00001;
228  AssertEqual(add, addeql, thresh); // test AssertEqual()
229  }
230 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestAxpy()

static void kaldi::UnitTestAxpy ( )
static

Definition at line 1020 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMat(), AssertEqual(), rnnlm::i, InitRandNonsingular(), rnnlm::j, KALDI_ASSERT, kTrans, and Rand().

1020  {
1021 
1022  for (MatrixIndexT i = 0;i< 10;i++) {
1023  MatrixIndexT dimM = 10+Rand()%10, dimN = 10+Rand()%10;
1024  Matrix<Real> M(dimM, dimN), N(dimM, dimN), O(dimN, dimM);
1025 
1027  Matrix<Real> Morig(M);
1028  M.AddMat(0.5, N);
1029  for (MatrixIndexT i = 0;i < dimM;i++)
1030  for (MatrixIndexT j = 0;j < dimN;j++)
1031  KALDI_ASSERT(std::abs(M(i, j) - (Morig(i, j)+0.5*N(i, j))) < 0.1);
1032  M.CopyFromMat(Morig);
1033  M.AddMat(0.5, O, kTrans);
1034  for (MatrixIndexT i = 0;i < dimM;i++)
1035  for (MatrixIndexT j = 0;j < dimN;j++)
1036  KALDI_ASSERT(std::abs(M(i, j) - (Morig(i, j)+0.5*O(j, i))) < 0.1);
1037  {
1038  float f = 0.5 * (float) (Rand() % 3);
1039  Matrix<Real> N(dimM, dimM);
1040  InitRandNonsingular(&N);
1041 
1042  Matrix<Real> N2(N);
1043  Matrix<Real> N3(N);
1044  N2.AddMat(f, N2, kTrans);
1045  N3.AddMat(f, N, kTrans);
1046  AssertEqual(N2, N3); // check works same with self as arg.
1047  }
1048  }
1049 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
static void InitRandNonsingular(SpMatrix< Real > *M)

◆ UnitTestBackpropLstmNonlinearity()

static void kaldi::UnitTestBackpropLstmNonlinearity ( )
static

Definition at line 321 of file cu-math-test.cc.

References AssertEqual(), kaldi::cu::BackpropLstmNonlinearity(), kaldi::cu::CpuBackpropLstmNonlinearity(), Timer::Elapsed(), rnnlm::i, KALDI_LOG, Rand(), RandInt(), VectorBase< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), CuVectorBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

321  {
322  for (int i = 0; i < 3; i++) {
323  int32 num_rows = 1 + Rand() % 200;
324  int32 cell_dim = 1 + Rand() % 2000,
325  dropout_dim = (RandInt(0, 1) == 0 ? 0 : 3);
326 // KALDI_LOG << num_rows << ", " << cell_dim;
327 
328  Matrix<Real> hinput(num_rows, 5 * cell_dim + dropout_dim);
329  Matrix<Real> hparams(3, cell_dim);
330  Matrix<Real> houtput_deriv(num_rows, 2 * cell_dim);
331  Matrix<double> hderiv_sum_in(5, cell_dim);
332  Vector<Real> hself_repair_config(10);
333  double count_in;
334  Matrix<Real> hinput_deriv(num_rows, 5 * cell_dim + dropout_dim);
335  Matrix<Real> hparams_deriv(3, cell_dim);
336  Matrix<double> hvalue_sum_out(5, cell_dim);
337  Matrix<double> hderiv_sum_out(5, cell_dim);
338  Matrix<Real> hself_repair_sum_out(5, cell_dim);
339 
340  hinput.SetRandn();
341  hparams.SetRandn();
342  houtput_deriv.SetRandn();
343  hderiv_sum_in.SetRandn();
344  hself_repair_config.SetRandn();
345  count_in = Rand() % num_rows;
346 
347  hinput_deriv.SetRandn();
348  hparams_deriv.SetRandn();
349  hvalue_sum_out.SetRandn();
350  hderiv_sum_out.SetRandn();
351  hself_repair_sum_out.SetRandn();
352 
353  CuMatrix<Real> dinput(hinput);
354  CuMatrix<Real> dparams(hparams);
355  CuMatrix<Real> doutput_deriv(houtput_deriv);
356  CuMatrix<double> dderiv_sum_in(hderiv_sum_in);
357  CuVector<Real> dself_repair_config(hself_repair_config);
358 
359  CuMatrix<Real> dinput_deriv(hinput_deriv);
360  CuMatrix<Real> dparams_deriv(hparams_deriv);
361  CuMatrix<double> dvalue_sum_out(hvalue_sum_out);
362  CuMatrix<double> dderiv_sum_out(hderiv_sum_out);
363  CuMatrix<Real> dself_repair_sum_out(hself_repair_sum_out);
364 
365  cu::CpuBackpropLstmNonlinearity(hinput, hparams, houtput_deriv,
366  hderiv_sum_in, hself_repair_config,
367  count_in, (MatrixBase<Real>*) NULL,
368  (MatrixBase<Real>*) NULL,
369  (MatrixBase<double>*) NULL,
370  (MatrixBase<double>*) NULL,
371  (MatrixBase<Real>*) NULL);
372  cu::BackpropLstmNonlinearity(dinput, dparams, doutput_deriv, dderiv_sum_in,
373  dself_repair_config, count_in,
374  (CuMatrixBase<Real>*) NULL,
375  (CuMatrixBase<Real>*) NULL,
376  (CuMatrixBase<double>*) NULL,
377  (CuMatrixBase<double>*) NULL,
378  (CuMatrixBase<Real>*) NULL);
379 
380  cu::CpuBackpropLstmNonlinearity(hinput, hparams, houtput_deriv,
381  hderiv_sum_in, hself_repair_config,
382  count_in, (MatrixBase<Real>*) NULL,
383  &hparams_deriv, &hvalue_sum_out,
384  &hderiv_sum_out, &hself_repair_sum_out);
385  cu::BackpropLstmNonlinearity(dinput, dparams, doutput_deriv, dderiv_sum_in,
386  dself_repair_config, count_in,
387  (CuMatrixBase<Real>*) NULL, &dparams_deriv,
388  &dvalue_sum_out, &dderiv_sum_out,
389  &dself_repair_sum_out);
390 
391  cu::CpuBackpropLstmNonlinearity(hinput, hparams, houtput_deriv,
392  hderiv_sum_in, hself_repair_config,
393  count_in, &hinput_deriv,
394  (MatrixBase<Real>*) NULL,
395  (MatrixBase<double>*) NULL,
396  (MatrixBase<double>*) NULL,
397  (MatrixBase<Real>*) NULL);
398  cu::BackpropLstmNonlinearity(dinput, dparams, doutput_deriv, dderiv_sum_in,
399  dself_repair_config, count_in, &dinput_deriv,
400  (CuMatrixBase<Real>*) NULL,
401  (CuMatrixBase<double>*) NULL,
402  (CuMatrixBase<double>*) NULL,
403  (CuMatrixBase<Real>*) NULL);
404 
405  cu::CpuBackpropLstmNonlinearity(hinput, hparams, houtput_deriv,
406  hderiv_sum_in, hself_repair_config,
407  count_in, &hinput_deriv, &hparams_deriv,
408  &hvalue_sum_out, &hderiv_sum_out,
409  &hself_repair_sum_out);
410  cu::BackpropLstmNonlinearity(dinput, dparams, doutput_deriv, dderiv_sum_in,
411  dself_repair_config, count_in, &dinput_deriv,
412  &dparams_deriv, &dvalue_sum_out,
413  &dderiv_sum_out, &dself_repair_sum_out);
414 
415  Matrix<Real> hdinput_deriv(dinput_deriv);
416  Matrix<Real> hdparams_deriv(dparams_deriv);
417  Matrix<double> hdvalue_sum_out(dvalue_sum_out);
418  Matrix<double> hdderiv_sum_out(dderiv_sum_out);
419  Matrix<Real> hdself_repair_sum_out(dself_repair_sum_out);
420 
421 // KALDI_LOG<< "input_deriv" << hinput_deriv << "d" << hdinput_deriv;
422 // KALDI_LOG<< "hparams_deriv" << hparams_deriv << "d" << hdparams_deriv;
423 // KALDI_LOG<< "hvalue_sum_out" << hvalue_sum_out << "d" << hdvalue_sum_out;
424 // KALDI_LOG<< "hderiv_sum_out" << hderiv_sum_out << "d" << hdderiv_sum_out;
425 // KALDI_LOG<< "hself_repair_sum_out" << hself_repair_sum_out << "d" << hdself_repair_sum_out;
426 
427  AssertEqual(hinput_deriv, hdinput_deriv);
428  AssertEqual(hparams_deriv, hdparams_deriv);
429  AssertEqual(hvalue_sum_out, hdvalue_sum_out);
430  AssertEqual(hderiv_sum_out, hdderiv_sum_out);
431  AssertEqual(hself_repair_sum_out, hdself_repair_sum_out);
432  }
433 
434  for (int i = 16; i <= 2048; i *= 2) {
435  BaseFloat time_in_secs = 0.025;
436  int32 num_rows = i;
437  int32 cell_dim = i;
438  int32 dropout_dim = (RandInt(0, 1) == 0 ? 0 : 3);
439 
440  CuMatrix<Real> input(num_rows, 5 * cell_dim + dropout_dim);
441  CuMatrix<Real> params(3, cell_dim);
442  CuMatrix<Real> output_deriv(num_rows, 2 * cell_dim);
443  CuMatrix<double> deriv_sum_in(5, cell_dim);
444  CuVector<Real> self_repair_config(10);
445  double count_in;
446 
447  CuMatrix<Real> input_deriv(num_rows, 5 * cell_dim + dropout_dim);
448  CuMatrix<Real> params_deriv(3, cell_dim);
449  CuMatrix<double> value_sum_out(5, cell_dim);
450  CuMatrix<double> deriv_sum_out(5, cell_dim);
451  CuMatrix<Real> self_repair_sum_out(5, cell_dim);
452 
453  input.SetRandn();
454  params.SetRandn();
455  output_deriv.SetRandn();
456  deriv_sum_in.SetRandn();
457  self_repair_config.SetRandn();
458  count_in = Rand() % num_rows;
459 
460  Timer tim;
461  int32 iter = 0;
462  for (; tim.Elapsed() < time_in_secs; iter++)
463  cu::BackpropLstmNonlinearity(input, params, output_deriv, deriv_sum_in,
464  self_repair_config, count_in, &input_deriv,
465  &params_deriv, &value_sum_out,
466  &deriv_sum_out, &self_repair_sum_out);
467 
468 
469  BaseFloat gflops = ((BaseFloat) i * i * iter) / (tim.Elapsed() * 1.0e+09);
470  KALDI_LOG << "For BackpropLstmNonlinearity"
471  << (sizeof(Real) == 8 ? "<double>" : "<float>") << ", for dim = "
472  << i << ", speed was " << gflops << " gigaflops";
473  if (tim.Elapsed() > 0.05)
474  break;
475  }
476 }
Base class which provides matrix operations not involving resizing or allocation. ...
Definition: kaldi-matrix.h:49
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
void BackpropLstmNonlinearity(const CuMatrixBase< Real > &input, const CuMatrixBase< Real > &params, const CuMatrixBase< Real > &output_deriv, const CuMatrixBase< double > &deriv_sum_in, const CuVectorBase< Real > &self_repair_config, double count_in, CuMatrixBase< Real > *input_deriv, CuMatrixBase< Real > *params_deriv, CuMatrixBase< double > *value_sum_out, CuMatrixBase< double > *deriv_sum_out, CuMatrixBase< Real > *self_repair_sum_out)
This function does the &#39;backward&#39; pass corresponding to the function ComputeLstmNonlinearity.
Definition: cu-math.cc:768
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Matrix for CUDA computing.
Definition: matrix-common.h:69
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95
void CpuBackpropLstmNonlinearity(const MatrixBase< Real > &input, const MatrixBase< Real > &params, const MatrixBase< Real > &output_deriv, const MatrixBase< double > &deriv_sum_in, const VectorBase< Real > &self_repair_config, double count_in, MatrixBase< Real > *input_deriv, MatrixBase< Real > *params_deriv, MatrixBase< double > *value_sum_out, MatrixBase< double > *deriv_sum_out, MatrixBase< Real > *self_repair_sum_out)
Definition: cu-math.cc:543

◆ UnitTestCheck()

void kaldi::UnitTestCheck ( )

Definition at line 2519 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::CopyFromMat(), KALDI_LOG, CuMatrixBase< Real >::NumRows(), and MatrixBase< Real >::SetRandn().

2519  {
2520  Matrix<Real> Hi(100,111);
2521  Hi.SetRandn();
2522 
2523  CuMatrix<Real> Di(100,111);
2524  Di.CopyFromMat(Hi);
2525 
2526  CuMatrix<Real> Dj(Di);
2527  KALDI_LOG << Dj.NumRows();
2528 
2529 
2530 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestCholesky()

static void kaldi::UnitTestCholesky ( )
static

Definition at line 87 of file cu-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddVecVec(), AssertEqual(), CuMatrixBase< Real >::Cholesky(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), rnnlm::i, kNoTrans, kTrans, and Rand().

87  {
88  for (MatrixIndexT iter = 0; iter < 3; iter++) {
89  MatrixIndexT dim = 300 + Rand() % 200;
90  // set dimension
91  // computing the matrix for cholesky input
92  // CuMatrix is cuda matrix class while Matrix is cpu matrix class
93  CuMatrix<Real> A(dim, dim);
94  Matrix<Real> B(dim, dim);
95  Vector<Real> C(dim);
96  for (MatrixIndexT i = 0; i < dim; i++) {
97  B(i, i) = 1;
98  C(i) = 1 + Rand() % 4;
99  }
100  B.AddVecVec(1.0, C, C);
101  // copy the matrix to cudamatrix object
102  A.CopyFromMat(B);
103  A.CopyToMat(&B);
104  //KALDI_LOG << B;
105  // doing cholesky
106  A.Cholesky();
107 
108  Matrix<Real> D(dim,dim);
109  A.CopyToMat(&D);
110 
111  //KALDI_LOG << "D is: " << D;
112  Matrix<Real> E(dim,dim);
113  E.AddMatMat(1.0, D, kNoTrans, D, kTrans, 0.0);
114  // check if the D'D is equal to B or not!
115  AssertEqual(B, E);
116  }
117 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestClassifyRspecifier()

void kaldi::UnitTestClassifyRspecifier ( )

Definition at line 177 of file kaldi-table-test.cc.

References ClassifyRspecifier(), KALDI_ASSERT, kArchiveRspecifier, kNoRspecifier, kScriptRspecifier, RspecifierOptions::once, and RspecifierOptions::sorted.

Referenced by main().

177  {
178  {
179  std::string a = "ark:foo|";
180  std::string fname = "x";
181  RspecifierOptions opts;
182  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
183  KALDI_ASSERT(ans == kArchiveRspecifier && fname == "foo|");
184  }
185 
186 
187  {
188  std::string a = "b,ark:foo|"; // b, is ignored.
189  std::string fname = "x";
190  RspecifierOptions opts;
191  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
192  KALDI_ASSERT(ans == kArchiveRspecifier && fname == "foo|");
193  }
194 
195  {
196  std::string a = "ark,b:foo|"; // , b is ignored.
197  std::string fname = "x";
198  RspecifierOptions opts;
199  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
200  KALDI_ASSERT(ans == kArchiveRspecifier && fname == "foo|");
201  }
202 
203 
204  {
205  std::string a = "scp,b:foo|";
206  std::string fname = "x";
207  RspecifierOptions opts;
208  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
209  KALDI_ASSERT(ans == kScriptRspecifier && fname == "foo|");
210  }
211 
212  {
213  std::string a = "scp,scp,b:foo|"; // invalid as repeated.
214  std::string fname = "x";
215  RspecifierOptions opts;
216  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
217  KALDI_ASSERT(ans == kNoRspecifier && fname == "");
218  }
219 
220  {
221  std::string a = "ark,scp,b:foo|"; // invalid as combined.
222  std::string fname = "x";
223  RspecifierOptions opts;
224  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
225  KALDI_ASSERT(ans == kNoRspecifier && fname == "");
226  }
227 
228  {
229  std::string a = "scp,o:foo|";
230  std::string fname = "x";
231  RspecifierOptions opts;
232  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
233  KALDI_ASSERT(ans == kScriptRspecifier && fname == "foo|");
234  KALDI_ASSERT(opts.once);
235  }
236 
237  {
238  std::string a = "scp,no:foo|";
239  std::string fname = "x";
240  RspecifierOptions opts;
241  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
242  KALDI_ASSERT(ans == kScriptRspecifier && fname == "foo|");
243  KALDI_ASSERT(!opts.once);
244  }
245 
246  {
247  std::string a = "s,scp,no:foo|";
248  std::string fname = "x";
249  RspecifierOptions opts;
250  RspecifierType ans = ClassifyRspecifier(a, &fname, &opts);
251  KALDI_ASSERT(ans == kScriptRspecifier && fname == "foo|");
252  KALDI_ASSERT(!opts.once && opts.sorted);
253  }
254 
255 
256  {
257  std::string a = "scp:foo|";
258  std::string fname = "x";
259  RspecifierType ans = ClassifyRspecifier(a, &fname, NULL);
260  KALDI_ASSERT(ans == kScriptRspecifier && fname == "foo|");
261  }
262 
263  {
264  std::string a = "scp:"; // empty fname valid.
265  std::string fname = "x";
266  RspecifierType ans = ClassifyRspecifier(a, &fname, NULL);
267  KALDI_ASSERT(ans == kScriptRspecifier && fname == "");
268  }
269 
270  {
271  std::string a = "scp:"; // empty fname valid.
272  RspecifierType ans = ClassifyRspecifier(a, NULL, NULL);
274  }
275 
276  {
277  std::string a = "";
278  RspecifierType ans = ClassifyRspecifier(a, NULL, NULL);
279  KALDI_ASSERT(ans == kNoRspecifier);
280  }
281 
282  {
283  std::string a = "scp";
284  RspecifierType ans = ClassifyRspecifier(a, NULL, NULL);
285  KALDI_ASSERT(ans == kNoRspecifier);
286  }
287 
288  {
289  std::string a = "ark";
290  RspecifierType ans = ClassifyRspecifier(a, NULL, NULL);
291  KALDI_ASSERT(ans == kNoRspecifier);
292  }
293 
294  {
295  std::string a = "ark:foo "; // trailing space not allowed.
296  RspecifierType ans = ClassifyRspecifier(a, NULL, NULL);
297  KALDI_ASSERT(ans == kNoRspecifier);
298  }
299 
300  // Testing it accepts the meaningless t, and b, prefixes.
301  {
302  std::string a = "b,scp:a", b;
303  RspecifierType ans = ClassifyRspecifier(a, &b, NULL);
304  KALDI_ASSERT(ans == kScriptRspecifier && b == "a");
305  }
306  {
307  std::string a = "t,scp:a", b;
308  RspecifierType ans = ClassifyRspecifier(a, &b, NULL);
309  KALDI_ASSERT(ans == kScriptRspecifier && b == "a");
310  }
311  {
312  std::string a = "b,ark:a", b;
313  RspecifierType ans = ClassifyRspecifier(a, &b, NULL);
314  KALDI_ASSERT(ans == kArchiveRspecifier && b == "a");
315  }
316  {
317  std::string a = "t,ark:a", b;
318  RspecifierType ans = ClassifyRspecifier(a, &b, NULL);
319  KALDI_ASSERT(ans == kArchiveRspecifier && b == "a");
320  }
321 }
RspecifierType ClassifyRspecifier(const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
Definition: kaldi-table.cc:225
RspecifierType
Definition: kaldi-table.h:219
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestClassifyRxfilename()

void kaldi::UnitTestClassifyRxfilename ( )

Definition at line 31 of file kaldi-io-test.cc.

References ClassifyRxfilename(), KALDI_ASSERT, kFileInput, kNoInput, kOffsetFileInput, kPipeInput, and kStandardInput.

Referenced by main().

31  {
46  KALDI_ASSERT(ClassifyRxfilename("ark,s,cs:a b c") == kNoInput);
47  KALDI_ASSERT(ClassifyRxfilename("scp:a b c") == kNoInput);
48 
49 }
InputType ClassifyRxfilename(const std::string &filename)
ClassifyRxfilenames interprets filenames for reading as follows:
Definition: kaldi-io.cc:138
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestClassifyWspecifier()

void kaldi::UnitTestClassifyWspecifier ( )

Definition at line 91 of file kaldi-table-test.cc.

References WspecifierOptions::binary, ClassifyWspecifier(), WspecifierOptions::flush, KALDI_ASSERT, kArchiveWspecifier, kBothWspecifier, kNoWspecifier, and kScriptWspecifier.

Referenced by main().

91  {
92  {
93  std::string a = "b,ark:|foo";
94  std::string ark = "x", scp = "y";
95  WspecifierOptions opts;
96  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
97  KALDI_ASSERT(ans == kArchiveWspecifier && ark == "|foo" && scp == "" &&
98  opts.binary == true);
99  }
100 
101  {
102  std::string a = "t,ark:|foo";
103  std::string ark = "x", scp = "y";
104  WspecifierOptions opts;
105  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
106  KALDI_ASSERT(ans == kArchiveWspecifier && ark == "|foo" && scp == "" &&
107  opts.binary == false);
108  }
109 
110  {
111  std::string a = "t,scp:a b c d";
112  std::string ark = "x", scp = "y";
113  WspecifierOptions opts;
114  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
115  KALDI_ASSERT(ans == kScriptWspecifier && ark == "" && scp == "a b c d" &&
116  opts.binary == false);
117  }
118 
119  {
120  std::string a = "t,ark,scp:a b,c,d";
121  std::string ark = "x", scp = "y";
122  WspecifierOptions opts;
123  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
124  KALDI_ASSERT(ans == kBothWspecifier && ark == "a b" && scp == "c,d" &&
125  opts.binary == false);
126  }
127 
128  {
129  std::string a = "";
130  std::string ark = "x", scp = "y";
131  WspecifierOptions opts;
132  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
133  KALDI_ASSERT(ans == kNoWspecifier);
134  }
135 
136  {
137  std::string a = " t,ark:boo"; // leading space not allowed.
138  WspecifierType ans = ClassifyWspecifier(a, NULL, NULL, NULL);
139  KALDI_ASSERT(ans == kNoWspecifier);
140  }
141 
142  {
143  std::string a = "t,ark:boo "; // trailing space not allowed.
144  WspecifierType ans = ClassifyWspecifier(a, NULL, NULL, NULL);
145  KALDI_ASSERT(ans == kNoWspecifier);
146  }
147 
148  {
149  std::string a = "b,ark,scp:,"; // empty ark, scp fnames valid.
150  std::string ark = "x", scp = "y";
151  WspecifierOptions opts;
152  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
153  KALDI_ASSERT(ans == kBothWspecifier && ark == "" && scp == "" &&
154  opts.binary == true);
155  }
156 
157  {
158  std::string a = "f,b,ark,scp:,"; // empty ark, scp fnames valid.
159  std::string ark = "x", scp = "y";
160  WspecifierOptions opts;
161  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
162  KALDI_ASSERT(ans == kBothWspecifier && ark == "" && scp == "" &&
163  opts.binary == true && opts.flush == true);
164  }
165 
166  {
167  std::string a = "nf,b,ark,scp:,"; // empty ark, scp fnames valid.
168  std::string ark = "x", scp = "y";
169  WspecifierOptions opts;
170  WspecifierType ans = ClassifyWspecifier(a, &ark, &scp, &opts);
171  KALDI_ASSERT(ans == kBothWspecifier && ark == "" && scp == "" &&
172  opts.binary == true && opts.flush == false);
173  }
174 }
WspecifierType
Definition: kaldi-table.h:106
WspecifierType ClassifyWspecifier(const std::string &wspecifier, std::string *archive_wxfilename, std::string *script_wxfilename, WspecifierOptions *opts)
Definition: kaldi-table.cc:135
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestClassifyWxfilename()

void kaldi::UnitTestClassifyWxfilename ( )

Definition at line 52 of file kaldi-io-test.cc.

References ClassifyWxfilename(), KALDI_ASSERT, kFileOutput, kNoOutput, kPipeOutput, and kStandardOutput.

Referenced by main().

52  {
63  KALDI_ASSERT(ClassifyWxfilename("a b c:123") == kNoOutput);
64  KALDI_ASSERT(ClassifyWxfilename("ark,s,cs:a b c") == kNoOutput);
65  KALDI_ASSERT(ClassifyWxfilename("scp:a b c") == kNoOutput);
69 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
OutputType ClassifyWxfilename(const std::string &filename)
ClassifyWxfilename interprets filenames as follows:
Definition: kaldi-io.cc:85

◆ UnitTestComplexFft()

static void kaldi::UnitTestComplexFft ( )
static

Definition at line 3422 of file matrix-lib-test.cc.

References AssertEqual(), ComplexFft(), ComplexFt(), VectorBase< Real >::CopyFromVec(), Rand(), and VectorBase< Real >::Scale().

3422  {
3423 
3424  // Make sure it inverts properly.
3425  for (MatrixIndexT N_ = 0; N_ < 100; N_+=3) {
3426  MatrixIndexT N = N_;
3427  if (N>=95) {
3428  N = ( Rand() % 150);
3429  N = N*N; // big number.
3430  }
3431 
3432  MatrixIndexT twoN = 2*N;
3433  Vector<Real> v(twoN), w_base(twoN), w_alg(twoN), x_base(twoN), x_alg(twoN);
3434 
3435  v.SetRandn();
3436 
3437  if (N< 100) ComplexFt(v, &w_base, true);
3438  w_alg.CopyFromVec(v);
3439  ComplexFft(&w_alg, true);
3440  if (N< 100) AssertEqual(w_base, w_alg, 0.01*N);
3441 
3442  if (N< 100) ComplexFt(w_base, &x_base, false);
3443  x_alg.CopyFromVec(w_alg);
3444  ComplexFft(&x_alg, false);
3445 
3446  if (N< 100) AssertEqual(x_base, x_alg, 0.01*N);
3447  x_alg.Scale(1.0/N);
3448  AssertEqual(v, x_alg, 0.001*N);
3449  }
3450 }
void ComplexFt(const VectorBase< Real > &in, VectorBase< Real > *out, bool forward)
ComplexFt is the same as ComplexFft but it implements the Fourier transform in an inefficient way...
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void ComplexFft(VectorBase< Real > *v, bool forward, Vector< Real > *tmp_in)
The function ComplexFft does an Fft on the vector argument v.
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestComplexFft2()

static void kaldi::UnitTestComplexFft2 ( )
static

Definition at line 3559 of file matrix-lib-test.cc.

References ApproxEqual(), ComplexFft(), ComplexFt(), and KALDI_ASSERT.

3559  {
3560 
3561  // Make sure it inverts properly.
3562  for (MatrixIndexT pos = 0; pos < 10; pos++) {
3563  for (MatrixIndexT N_ = 2; N_ < 15; N_+=2) {
3564  if ( pos < N_) {
3565  MatrixIndexT N = N_;
3566  Vector<Real> v(N), vorig(N), v2(N);
3567  v(pos) = 1.0;
3568  vorig.CopyFromVec(v);
3569  // KALDI_LOG << "Original v:\n" << v;
3570  ComplexFft(&v, true);
3571  // KALDI_LOG << "one fft:\n" << v;
3572  ComplexFt(vorig, &v2, true);
3573  // KALDI_LOG << "one fft[baseline]:\n" << v2;
3574  if (!ApproxEqual(v, v2) ) {
3575  ComplexFft(&vorig, true);
3576  KALDI_ASSERT(0);
3577  }
3578  ComplexFft(&v, false);
3579  // KALDI_LOG << "one more:\n" << v;
3580  v.Scale(1.0/(N/2));
3581  if (!ApproxEqual(v, vorig)) {
3582  ComplexFft(&vorig, true);
3583  KALDI_ASSERT(0);
3584  }// AssertEqual(v, vorig);
3585  }
3586  }
3587  }
3588 }
void ComplexFt(const VectorBase< Real > &in, VectorBase< Real > *out, bool forward)
ComplexFt is the same as ComplexFft but it implements the Fourier transform in an inefficient way...
int32 MatrixIndexT
Definition: matrix-common.h:98
void ComplexFft(VectorBase< Real > *v, bool forward, Vector< Real > *tmp_in)
The function ComplexFft does an Fft on the vector argument v.
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestComplexFt()

static void kaldi::UnitTestComplexFt ( )
static

Definition at line 3395 of file matrix-lib-test.cc.

References AssertEqual(), ComplexFt(), rnnlm::d, Rand(), and VectorBase< Real >::Scale().

3395  {
3396 
3397  // Make sure it inverts properly.
3398  for (MatrixIndexT d = 0; d < 10; d++) {
3399  MatrixIndexT N = Rand() % 100, twoN = 2*N;
3400  Vector<Real> v(twoN), w(twoN), x(twoN);
3401  v.SetRandn();
3402  ComplexFt(v, &w, true);
3403  ComplexFt(w, &x, false);
3404  if (N>0) x.Scale(1.0/static_cast<Real>(N));
3405  AssertEqual(v, x);
3406  }
3407 }
void ComplexFt(const VectorBase< Real > &in, VectorBase< Real > *out, bool forward)
ComplexFt is the same as ComplexFft but it implements the Fourier transform in an inefficient way...
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestComplexPower()

void kaldi::UnitTestComplexPower ( )

Definition at line 3701 of file matrix-lib-test.cc.

References AssertEqual(), AttemptComplexPower(), rnnlm::i, KALDI_ASSERT, and RandGauss().

3701  {
3702  // This tests a not-really-public function that's used in Matrix::Power().
3703 
3704  for (MatrixIndexT i = 0; i < 10; i++) {
3705  Real power = RandGauss();
3706  Real x = 2.0, y = 0.0;
3707  bool ans = AttemptComplexPower(&x, &y, power);
3708  KALDI_ASSERT(ans);
3709  AssertEqual(std::pow(static_cast<Real>(2.0), power), x);
3710  AssertEqual(y, 0.0);
3711  }
3712  {
3713  Real x, y;
3714  x = 0.5; y = -0.3;
3715  bool ans = AttemptComplexPower(&x, &y, static_cast<Real>(2.21));
3716  KALDI_ASSERT(ans);
3717  ans = AttemptComplexPower(&x, &y, static_cast<Real>(1.0/2.21));
3718  KALDI_ASSERT(ans);
3719  AssertEqual(x, 0.5);
3720  AssertEqual(y, -0.3);
3721  }
3722  {
3723  Real x, y;
3724  x = 0.5; y = -0.3;
3725  bool ans = AttemptComplexPower(&x, &y, static_cast<Real>(2.0));
3726  KALDI_ASSERT(ans);
3727  AssertEqual(x, 0.5*0.5 - 0.3*0.3);
3728  AssertEqual(y, -0.3*0.5*2.0);
3729  }
3730 
3731  {
3732  Real x, y;
3733  x = 1.0/std::sqrt(2.0); y = -1.0/std::sqrt(2.0);
3734  bool ans = AttemptComplexPower(&x, &y, static_cast<Real>(-1.0));
3735  KALDI_ASSERT(ans);
3736  AssertEqual(x, 1.0/std::sqrt(2.0));
3737  AssertEqual(y, 1.0/std::sqrt(2.0));
3738  }
3739 
3740  {
3741  Real x, y;
3742  x = 0.0; y = 0.0;
3743  bool ans = AttemptComplexPower(&x, &y, static_cast<Real>(-2.0));
3744  KALDI_ASSERT(!ans); // zero; negative pow.
3745  }
3746  {
3747  Real x, y;
3748  x = -2.0; y = 0.0;
3749  bool ans = AttemptComplexPower(&x, &y, static_cast<Real>(1.5));
3750  KALDI_ASSERT(!ans); // negative real case
3751  }
3752 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
bool AttemptComplexPower(Real *x_re, Real *x_im, Real power)
The following function is used in Matrix::Power, and separately tested, so we declare it here mainly ...

◆ UnitTestCompressedMatrix()

static void kaldi::UnitTestCompressedMatrix ( )
static

Definition at line 4057 of file matrix-lib-test.cc.

References MatrixBase< Real >::Add(), MatrixBase< Real >::AddMat(), AssertEqual(), CompressedMatrix::CopyColToVec(), CompressedMatrix::CopyRowToVec(), CompressedMatrix::CopyToMat(), MatrixBase< Real >::FrobeniusNorm(), rnnlm::i, InitKaldiInputStream(), InitKaldiOutputStream(), KALDI_ASSERT, KALDI_ERR, KALDI_LOG, KALDI_WARN, kAutomaticMethod, kOneByteAuto, kSpeechFeature, kTwoByteAuto, rnnlm::n, CompressedMatrix::NumCols(), CompressedMatrix::NumRows(), Rand(), RandGauss(), RandInt(), CompressedMatrix::Read(), Matrix< Real >::Read(), MatrixBase< Real >::Row(), CompressedMatrix::Scale(), MatrixBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), CompressedMatrix::Write(), and MatrixBase< Real >::Write().

4057  {
4058  // This is the basic test.
4059 
4060  CompressedMatrix empty_cmat; // some tests on empty matrix
4061  KALDI_ASSERT(empty_cmat.NumRows() == 0);
4062  KALDI_ASSERT(empty_cmat.NumCols() == 0);
4063 
4064  // could set num_tot to 10000 for more thorough testing.
4065  MatrixIndexT num_failure = 0, num_tot = 1000, max_failure = 1;
4066  for (MatrixIndexT n = 0; n < num_tot; n++) {
4067  MatrixIndexT num_rows = Rand() % 20, num_cols = Rand() % 15;
4068  if (num_rows * num_cols == 0) {
4069  num_rows = 0;
4070  num_cols = 0;
4071  }
4072  if (rand() % 2 == 0 && num_cols != 0) {
4073  // smaller matrices are more likely to have problems.
4074  num_cols = 1 + Rand() % 3;
4075  }
4076  Matrix<Real> M(num_rows, num_cols);
4077  if (Rand() % 3 != 0) M.SetRandn();
4078  else {
4079  M.Add(RandGauss());
4080  }
4081  if (Rand() % 2 == 0 && num_rows != 0) { // set one row to all the same value,
4082  // which is one possible pathology.
4083  // Give it large dynamic range to increase chance that it
4084  // is the largest or smallest value in the matrix.
4085  M.Row(Rand() % num_rows).Set(RandGauss() * 4.0);
4086  }
4087  double rand_val = RandGauss() * 4.0;
4088  // set a bunch of elements to all one value: increases
4089  // chance of pathologies.
4090  MatrixIndexT modulus = 1 + Rand() % 5;
4091  for (MatrixIndexT r = 0; r < num_rows; r++)
4092  for (MatrixIndexT c = 0; c < num_cols; c++)
4093  if (Rand() % modulus != 0) M(r, c) = rand_val;
4094 
4095 
4096  CompressionMethod method;
4097  switch(RandInt(0, 3)) {
4098  case 0: method = kAutomaticMethod; break;
4099  case 1: method = kSpeechFeature; break;
4100  case 2: method = kTwoByteAuto; break;
4101  default: method = kOneByteAuto; break;
4102  }
4103 
4104  CompressedMatrix cmat(M, method);
4105  KALDI_ASSERT(cmat.NumRows() == num_rows);
4106  KALDI_ASSERT(cmat.NumCols() == num_cols);
4107 
4108  Matrix<Real> M2(cmat.NumRows(), cmat.NumCols());
4109  cmat.CopyToMat(&M2);
4110 
4111  Matrix<Real> diff(M2);
4112  diff.AddMat(-1.0, M);
4113 
4114  { // Check that when compressing a matrix that has already been compressed,
4115  // and uncompressing, we get the same answer if using the same compression
4116  // method.
4117  // ok, actually, we can't guarantee this, so just limit the number of
4118  // failures.
4119  CompressedMatrix cmat2(M2, method);
4120  Matrix<Real> M3(cmat.NumRows(), cmat.NumCols());
4121  cmat2.CopyToMat(&M3);
4122  if (!M2.ApproxEqual(M3, 1.0e-04)) {
4123  KALDI_LOG << "cmat is: ";
4124  cmat.Write(std::cout, false);
4125  KALDI_LOG << "cmat2 is: ";
4126  cmat2.Write(std::cout, false);
4127  KALDI_WARN << "Matrices differ " << M2 << " vs. " << M3 << ", M2 range is "
4128  << M2.Min() << " to " << M2.Max() << ", M3 range is "
4129  << M3.Min() << " to " << M3.Max();
4130  num_failure++;
4131  }
4132  }
4133 
4134  if (num_rows > 0) { // Check that the constructor accepting row and column offsets
4135  // etc., works.
4136  if (RandInt(0, 1) == 0) {
4137  // test the ability of the self-constructor to do row-padding. (used in
4138  // getting nnet3 examples without un-compressing and re-compressing the
4139  // data_.
4140  bool allow_row_padding = true;
4141  int32 row_offset = RandInt(-4, num_rows - 1),
4142  col_offset = RandInt(0, num_cols - 1),
4143  num_rows_sub = RandInt(1, 4 + num_rows - row_offset),
4144  num_cols_sub = RandInt(1, num_cols - col_offset);
4145  CompressedMatrix cmat_sub(cmat, row_offset, num_rows_sub,
4146  col_offset, num_cols_sub, allow_row_padding);
4147  Matrix<Real> M2_sub(num_rows_sub, num_cols_sub);
4148  for (int32 row = 0; row < num_rows_sub; row++) {
4149  int32 old_row = row + row_offset;
4150  if (old_row < 0) old_row = 0;
4151  else if (old_row >= num_rows) { old_row = num_rows - 1; }
4152  SubVector<Real> M2_sub_row(M2_sub, row),
4153  M2_row(M2, old_row),
4154  M2_row_part(M2_row, col_offset, num_cols_sub);
4155  M2_sub_row.CopyFromVec(M2_row_part);
4156  }
4157  Matrix<Real> M3_sub(cmat_sub);
4158  M3_sub.AddMat(-1.0, M2_sub);
4159  KALDI_ASSERT(M3_sub.FrobeniusNorm() / (num_rows_sub * num_cols_sub) <
4160  1.0e-03);
4161  } else {
4162  int32 row_offset = RandInt(0, num_rows - 1),
4163  col_offset = RandInt(0, num_cols - 1),
4164  num_rows_sub = RandInt(1, num_rows - row_offset),
4165  num_cols_sub = RandInt(1, num_cols - col_offset);
4166  CompressedMatrix cmat_sub(cmat, row_offset, num_rows_sub,
4167  col_offset, num_cols_sub);
4168  SubMatrix<Real> M2_sub(M2, row_offset, num_rows_sub,
4169  col_offset, num_cols_sub);
4170  Matrix<Real> M3_sub(cmat_sub);
4171  M3_sub.AddMat(-1.0, M2_sub);
4172  KALDI_ASSERT(M3_sub.FrobeniusNorm() / (num_rows_sub * num_cols_sub) <
4173  1.0e-03);
4174  }
4175  } else {
4176  CompressedMatrix cmat_sub(cmat, 0, 0, 0, 0);
4177  }
4178 
4179  // test CopyRowToVec
4180  for (MatrixIndexT i = 0; i < num_rows; i++) {
4181  Vector<Real> V(num_cols);
4182  cmat.CopyRowToVec(i, &V); // get row.
4183  for (MatrixIndexT k = 0; k < num_cols; k++) {
4184  AssertEqual(M2(i, k), V(k));
4185  }
4186  }
4187 
4188  // test CopyColToVec
4189  for (MatrixIndexT i = 0; i < num_cols; i++) {
4190  Vector<Real> V(num_rows);
4191  cmat.CopyColToVec(i, &V); // get col.
4192  for (MatrixIndexT k = 0;k < num_rows;k++) {
4193  AssertEqual(M2(k, i), V(k));
4194  }
4195  }
4196 
4197  //test of getting a submatrix
4198  if(num_rows != 0 && num_cols != 0){
4199  MatrixIndexT sub_row_offset = Rand() % num_rows,
4200  sub_col_offset = Rand() % num_cols;
4201  // to make sure we don't mod by zero
4202  MatrixIndexT num_subrows = Rand() % (num_rows-sub_row_offset),
4203  num_subcols = Rand() % (num_cols-sub_col_offset);
4204  if(num_subrows == 0 || num_subcols == 0){ // in case we randomized to
4205  // empty matrix, at least make it correct
4206  num_subrows = 0;
4207  num_subcols = 0;
4208  }
4209  Matrix<Real> Msub(num_subrows, num_subcols);
4210  cmat.CopyToMat(sub_row_offset, sub_col_offset, &Msub);
4211  for (MatrixIndexT i = 0; i < num_subrows; i++) {
4212  for (MatrixIndexT k = 0;k < num_subcols;k++) {
4213  AssertEqual(M2(i+sub_row_offset, k+sub_col_offset), Msub(i, k));
4214  }
4215  }
4216  }
4217 
4218  { // Check Scale() method for compressedMatrix.
4219  for (int32 t = 0; t < 10; t++) {
4220  float alpha = 0.1;
4221  MatrixIndexT num_rows = 4 + Rand() % 20,
4222  num_cols = 10 + Rand() % 50;
4223  Matrix<Real> M(num_rows, num_cols);
4224  M.SetRandn();
4225  CompressedMatrix cmat(M);
4226  Matrix<Real> scaled_comp_mat(num_rows, num_cols),
4227  scaled_mat(M);
4228  scaled_mat.Scale(alpha);
4229  cmat.Scale(alpha);
4230  cmat.CopyToMat(&scaled_comp_mat);
4231  AssertEqual(scaled_comp_mat, scaled_mat);
4232  }
4233  }
4234  if (n < 5) { // test I/O.
4235  bool binary = (n % 2 == 1);
4236  {
4237  std::ofstream outs("tmpf", std::ios_base::out |std::ios_base::binary);
4238  InitKaldiOutputStream(outs, binary);
4239  cmat.Write(outs, binary);
4240  }
4241  CompressedMatrix cmat2;
4242  {
4243  bool binary_in;
4244  std::ifstream ins("tmpf", std::ios_base::in | std::ios_base::binary);
4245  InitKaldiInputStream(ins, &binary_in);
4246  cmat2.Read(ins, binary_in);
4247  }
4248 #if 1
4249  { // check that compressed-matrix can be read as matrix.
4250  bool binary_in;
4251  std::ifstream ins("tmpf", std::ios_base::in | std::ios_base::binary);
4252  InitKaldiInputStream(ins, &binary_in);
4253  Matrix<Real> mat1;
4254  mat1.Read(ins, binary_in);
4255  Matrix<Real> mat2(cmat2);
4256  AssertEqual(mat1, mat2);
4257  }
4258 #endif
4259 
4260 
4261  { // check that matrix can be read as compressed-matrix.
4262  Matrix<Real> mat1(cmat);
4263  {
4264  std::ofstream outs("tmpf", std::ios_base::out |std::ios_base::binary);
4265  InitKaldiOutputStream(outs, binary);
4266  mat1.Write(outs, binary);
4267  }
4268  bool binary_in;
4269  std::ifstream ins("tmpf", std::ios_base::in | std::ios_base::binary);
4270  InitKaldiInputStream(ins, &binary_in);
4271  CompressedMatrix cmat2;
4272  cmat2.Read(ins, binary_in);
4273  Matrix<Real> mat2(cmat2);
4274  AssertEqual(mat1, mat2);
4275  }
4276 
4277 
4278  Matrix<Real> M3(cmat2.NumRows(), cmat2.NumCols());
4279  cmat2.CopyToMat(&M3);
4280  AssertEqual(M2, M3); // tests I/O of CompressedMatrix.
4281 
4282  CompressedMatrix cmat3(cmat2); // testing self-constructor, which
4283  // tests assignment operator.
4284  Matrix<Real> M4(cmat3.NumRows(), cmat3.NumCols());
4285  cmat3.CopyToMat(&M4);
4286  AssertEqual(M2, M4);
4287  }
4288  KALDI_LOG << "M = " << M;
4289  KALDI_LOG << "M2 = " << M2;
4290  double tot = M.FrobeniusNorm(), err = diff.FrobeniusNorm();
4291  KALDI_LOG << "Compressed matrix, tot = " << tot << ", diff = "
4292  << err;
4293  if (err > 0.015 * tot) {
4294  KALDI_WARN << "Failure in compressed-matrix test.";
4295  num_failure++;
4296  }
4297  }
4298  if (num_failure > max_failure)
4299  KALDI_ERR << "Too many failures in compressed matrix test " << num_failure
4300  << " > " << max_failure;
4301 
4302  unlink("tmpf");
4303 }
void Write(std::ostream &out, bool binary) const
write to stream.
bool InitKaldiInputStream(std::istream &is, bool *binary)
Initialize an opened stream for reading by detecting the binary header and.
Definition: io-funcs-inl.h:306
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
void Read(std::istream &is, bool binary)
void Read(std::istream &in, bool binary, bool add=false)
read from stream.
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for emtpy matrix).
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void InitKaldiOutputStream(std::ostream &os, bool binary)
InitKaldiOutputStream initializes an opened stream for writing by writing an optional binary header a...
Definition: io-funcs-inl.h:291
MatrixIndexT NumCols() const
Returns number of columns (or zero for emtpy matrix).
#define KALDI_LOG
Definition: kaldi-error.h:153
void CopyToMat(MatrixBase< Real > *mat, MatrixTransposeType trans=kNoTrans) const
Copies contents to matrix.
Sub-matrix representation.
Definition: kaldi-matrix.h:988
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestCompressedMatrix2()

static void kaldi::UnitTestCompressedMatrix2 ( )
static

Definition at line 4013 of file matrix-lib-test.cc.

References ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, kOneByteZeroOne, kTwoByteSignedInteger, and RandInt().

4013  {
4014  // These are some new tests added after we add the capability to
4015  // specify the compression type.
4016 
4017  for (int32 i = 0; i < 10; i++) {
4018  // test that the kTwoByteSignedInteger method works.
4019  int32 num_rows = RandInt(1, 5), num_cols = RandInt(1, 10);
4020  Matrix<Real> mat(num_rows, num_cols);
4021  for (int32 j = 0; j < num_rows; j++) {
4022  for (int32 k = 0; k < num_cols; k++) {
4023  mat(j, k) = RandInt(-32768, 32767);
4024  }
4025  }
4027 
4028  Matrix<Real> mat2(cmat);
4029 
4030  // Check that they are exactly equal. These integers should all be
4031  // exactly representable, and exactly reconstructed after compression.
4032  KALDI_ASSERT(ApproxEqual(mat, mat2, Real(0.0)));
4033  }
4034 
4035 
4036  for (int32 i = 0; i < 10; i++) {
4037  // test that the kOneByteZeroOne compression method works.
4038  int32 num_rows = RandInt(1, 5), num_cols = RandInt(1, 10);
4039  Matrix<Real> mat(num_rows, num_cols);
4040  for (int32 j = 0; j < num_rows; j++) {
4041  for (int32 k = 0; k < num_cols; k++) {
4042  mat(j, k) = RandInt(0, 255) / 255.0;
4043  }
4044  }
4045  CompressedMatrix cmat(mat, kOneByteZeroOne);
4046 
4047  Matrix<Real> mat2(cmat);
4048 
4049  // Check that they are almost exactly equal. (It's not 100% exact because
4050  // 1.0 / 255.0 is not exactly representable.
4051  KALDI_ASSERT(ApproxEqual(mat, mat2, Real(1.00001)));
4052  }
4053 
4054 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestComputeGPE()

static void kaldi::UnitTestComputeGPE ( )
static

Definition at line 327 of file pitch-functions-test.cc.

References ConvertIntToString(), rnnlm::i, rnnlm::j, KALDI_LOG, MatrixBase< Real >::NumRows(), and Matrix< Real >::Read().

Referenced by UnitTestFeatWithKeele().

327  {
328  KALDI_LOG << "=== UnitTestComputeGPE ===\n";
329  int32 wrong_pitch = 0, tot_voiced = 0, tot_unvoiced = 0, num_frames = 0;
330  BaseFloat tol = 0.1, avg_d_kpitch = 0, real_pitch = 0;
331  for (int32 i = 1; i < 11; i++) {
332  std::string wavefile;
333  std::string num;
334  if (i < 6) {
335  num = "f" + ConvertIntToString(i) + "nw0000";
336  } else {
337  num = "m" + ConvertIntToString(i-5) + "nw0000";
338  }
339  Matrix<BaseFloat> gross_pitch;
340  std::string pitchfile = "keele/keele-true-lags/"+num+".txt";
341  std::ifstream pitch(pitchfile.c_str());
342  gross_pitch.Read(pitch, false);
343  Matrix<BaseFloat> kaldi_pitch;
344  std::string kfile = "keele/tmp/+"+num+"-kaldi.txt";
345  std::ifstream kpitch(kfile.c_str());
346  kaldi_pitch.Read(kpitch, false);
347  num_frames = std::min(kaldi_pitch.NumRows(),gross_pitch.NumRows());
348  for (int32 j = 1; j < num_frames; j++) {
349  if (gross_pitch(j,0) > 0.0) {
350  tot_voiced++;
351  real_pitch = 20000.0/gross_pitch(j,0);
352  if (fabs((real_pitch - kaldi_pitch(j,1))/real_pitch) > tol)
353  wrong_pitch++;
354  } else if (gross_pitch(j,0) == 0.0 && gross_pitch(j-1,0) == 0.0) {
355  tot_unvoiced++;
356  avg_d_kpitch += fabs(kaldi_pitch(j,1) - kaldi_pitch(j-1,1));
357  }
358  }
359  }
360  BaseFloat GPE = 1.0 * wrong_pitch / tot_voiced;
361  KALDI_LOG << " Gross Pitch Error with Rel.Error " << tol << " is " << GPE;
362  KALDI_LOG << "Average Kaldi delta_pitch for unvoiced regions " << avg_d_kpitch/tot_unvoiced;
363 }
std::string ConvertIntToString(const int &number)
kaldi::int32 int32
void Read(std::istream &in, bool binary, bool add=false)
read from stream.
float BaseFloat
Definition: kaldi-types.h:29
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestConfigLineParse()

void kaldi::UnitTestConfigLineParse ( )

Definition at line 328 of file text-utils-test.cc.

References ConfigLine::FirstToken(), ConfigLine::GetValue(), ConfigLine::HasUnusedValues(), KALDI_ASSERT, ConfigLine::ParseLine(), and ConfigLine::UnusedValues().

Referenced by main().

328  {
329  std::string str;
330  {
331  ConfigLine cfl;
332  str = "a-b xx=yyy foo=bar baz=123 ba=1:2";
333  bool status = cfl.ParseLine(str);
334  KALDI_ASSERT(status && cfl.FirstToken() == "a-b");
335 
337  std::string str_value;
338  KALDI_ASSERT(cfl.GetValue("xx", &str_value));
339  KALDI_ASSERT(str_value == "yyy");
341  KALDI_ASSERT(cfl.GetValue("foo", &str_value));
342  KALDI_ASSERT(str_value == "bar");
344  KALDI_ASSERT(!cfl.GetValue("xy", &str_value));
345  KALDI_ASSERT(cfl.GetValue("baz", &str_value));
346  KALDI_ASSERT(str_value == "123");
347 
348  std::vector<int32> int_values;
349  KALDI_ASSERT(!cfl.GetValue("xx", &int_values));
350  KALDI_ASSERT(cfl.GetValue("baz", &int_values));
352  KALDI_ASSERT(int_values.size() == 1 && int_values[0] == 123);
353  KALDI_ASSERT(cfl.GetValue("ba", &int_values));
354  KALDI_ASSERT(int_values.size() == 2 && int_values[0] == 1 && int_values[1] == 2);
356  }
357 
358  {
359  ConfigLine cfl;
360  str = "a-b baz=x y z pp = qq ab =cd ac= bd";
361  KALDI_ASSERT(!cfl.ParseLine(str));
362  }
363  {
364  ConfigLine cfl;
365  str = "a-b baz=x y z pp = qq ab=cd ac=bd";
366  KALDI_ASSERT(!cfl.ParseLine(str));
367  }
368  {
369  ConfigLine cfl;
370  str = "foo-bar";
371  KALDI_ASSERT(cfl.ParseLine(str));
372  }
373  {
374  ConfigLine cfl;
375  str = "foo-bar a=b c d f=g";
376  std::string value;
377  KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "foo-bar" &&
378  cfl.GetValue("a", &value) && value == "b c d" &&
379  cfl.GetValue("f", &value) && value == "g" &&
380  !cfl.HasUnusedValues());
381  }
382  {
383  ConfigLine cfl;
384  str = "zzz a=b baz";
385  KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "zzz" &&
386  cfl.UnusedValues() == "a=b baz");
387  }
388  {
389  ConfigLine cfl;
390  str = "xxx a=b baz ";
391  KALDI_ASSERT(cfl.ParseLine(str) && cfl.UnusedValues() == "a=b baz");
392  }
393  {
394  ConfigLine cfl;
395  str = "xxx a=b =c";
396  KALDI_ASSERT(!cfl.ParseLine(str));
397  }
398  {
399  ConfigLine cfl;
400  str = "xxx baz='x y z' pp=qq ab=cd ac=bd";
401  KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "xxx");
402  std::string str_value;
403  KALDI_ASSERT(cfl.GetValue("baz", &str_value));
404  KALDI_ASSERT(str_value == "x y z");
405  KALDI_ASSERT(cfl.GetValue("pp", &str_value));
406  KALDI_ASSERT(str_value == "qq");
407  KALDI_ASSERT(cfl.UnusedValues() == "ab=cd ac=bd");
408  KALDI_ASSERT(cfl.GetValue("ab", &str_value));
409  KALDI_ASSERT(str_value == "cd");
410  KALDI_ASSERT(cfl.UnusedValues() == "ac=bd");
412  KALDI_ASSERT(cfl.GetValue("ac", &str_value));
413  KALDI_ASSERT(str_value == "bd");
415  }
416 
417  {
418  ConfigLine cfl;
419  str = "x baz= pp = qq flag=t ";
420  KALDI_ASSERT(!cfl.ParseLine(str));
421  }
422  {
423  ConfigLine cfl;
424  str = " x baz= pp=qq flag=t ";
425  KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "x");
426 
427  std::string str_value;
428  KALDI_ASSERT(cfl.GetValue("baz", &str_value));
429  KALDI_ASSERT(str_value == "");
430  KALDI_ASSERT(cfl.GetValue("pp", &str_value));
431  KALDI_ASSERT(str_value == "qq");
433  KALDI_ASSERT(cfl.GetValue("flag", &str_value));
434  KALDI_ASSERT(str_value == "t");
436 
437  bool bool_value = false;
438  KALDI_ASSERT(cfl.GetValue("flag", &bool_value));
439  KALDI_ASSERT(bool_value);
440  }
441 
442  {
443  ConfigLine cfl;
444  str = "xx _baz=a -pp=qq";
445  KALDI_ASSERT(!cfl.ParseLine(str));
446  }
447  {
448  ConfigLine cfl;
449  str = "xx 0baz=a pp=qq";
450  KALDI_ASSERT(!cfl.ParseLine(str));
451  }
452  {
453  ConfigLine cfl;
454  str = "xx -baz=a pp=qq";
455  KALDI_ASSERT(!cfl.ParseLine(str));
456  }
457  {
458  ConfigLine cfl;
459  str = "xx _baz'=a pp=qq";
460  KALDI_ASSERT(!cfl.ParseLine(str));
461  }
462  {
463  ConfigLine cfl;
464  str = " baz=g";
465  KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "");
466  bool flag;
467  KALDI_ASSERT(!cfl.GetValue("baz", &flag));
468  }
469  {
470  ConfigLine cfl;
471  str = "xx _baz1=a pp=qq";
472  KALDI_ASSERT(cfl.ParseLine(str));
473 
474  std::string str_value;
475  KALDI_ASSERT(cfl.GetValue("_baz1", &str_value));
476  }
477 }
const std::string & FirstToken() const
Definition: text-utils.h:228
bool ParseLine(const std::string &line)
Definition: text-utils.cc:343
std::string UnusedValues() const
returns e.g.
Definition: text-utils.cc:518
This class is responsible for parsing input like hi-there xx=yyy a=b c empty= f-oo=Append(bar, sss) ba_z=123 bing=&#39;a b c&#39; baz="a b c d=&#39;a b&#39; e" and giving you access to the fields, in this case.
Definition: text-utils.h:205
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool HasUnusedValues() const
Definition: text-utils.cc:510
bool GetValue(const std::string &key, std::string *value)
Definition: text-utils.cc:427

◆ UnitTestConstructor()

static void kaldi::UnitTestConstructor ( )
static

Definition at line 216 of file cu-test.cc.

References CuMatrixBase< Real >::CopyFromMat(), CuSpMatrix< Real >::CopyToSp(), rnnlm::i, rnnlm::j, KALDI_LOG, and kTakeLower.

216  {
217  MatrixIndexT dim = 8;
218  CuMatrix<Real> A(dim,dim);
219  Matrix<Real> B(dim,dim);
220  for (MatrixIndexT i = 0; i < dim; i++) {
221  for (MatrixIndexT j = 0; j <=i; j++)
222  B(i,j) = i+j;
223  for (MatrixIndexT j = i+1; j < dim; j++)
224  B(i,j) = i+j+4;
225  }
226  KALDI_LOG << "A is : ";
227  KALDI_LOG << B;
228  A.CopyFromMat(B);
229  //CuSpMatrix<Real> C(dim);
230  //C.CopyFromMat(A,kTakeLower);
232  SpMatrix<Real> D(dim);
233  C.CopyToSp(&D);
234  KALDI_LOG << "C is : ";
235  for (MatrixIndexT i = 0; i < dim; i++) {
236  for (MatrixIndexT j = 0; j <= i; j++)
237  std::cout << D(i,j) << " ";
238  std::cout << '\n';
239  }
240 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestCopyCols()

static void kaldi::UnitTestCopyCols ( )
static

Definition at line 853 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, rnnlm::j, Rand(), and MatrixBase< Real >::SetRandn().

853  {
854  for (MatrixIndexT p = 0; p < 10; p++) {
855  MatrixIndexT num_cols1 = 10 + Rand() % 10,
856  num_cols2 = 10 + Rand() % 10,
857  num_rows = 10 + Rand() % 10;
858  Matrix<Real> M(num_rows, num_cols1);
859  M.SetRandn();
860 
861  Matrix<Real> N(num_rows, num_cols2), O(num_rows, num_cols2);
862  std::vector<int32> reorder(num_cols2);
863  for (int32 i = 0; i < num_cols2; i++)
864  reorder[i] = -1 + (Rand() % (num_cols1 + 1));
865 
866  N.CopyCols(M, &(reorder[0]));
867 
868  for (int32 i = 0; i < num_rows; i++)
869  for (int32 j = 0; j < num_cols2; j++)
870  if (reorder[j] < 0) O(i, j) = 0;
871  else O(i, j) = M(i, reorder[j]);
872  AssertEqual(N, O);
873  }
874 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCopyFromMat()

static void kaldi::UnitTestCopyFromMat ( )
static

Definition at line 294 of file cu-test.cc.

References CuSpMatrix< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), CuSpMatrix< Real >::CopyToSp(), rnnlm::i, rnnlm::j, KALDI_LOG, kTakeLower, kTakeMean, and kTakeUpper.

294  {
295  MatrixIndexT dim = 8;
296  CuMatrix<Real> A(dim,dim);
297  Matrix<Real> B(dim,dim);
298  for (MatrixIndexT i = 0; i < dim; i++) {
299  for (MatrixIndexT j = 0; j <=i; j++)
300  B(i,j) = i+j;
301  for (MatrixIndexT j = i+1; j < dim; j++)
302  B(i,j) = i+j+4;
303  }
304  KALDI_LOG << "A is : ";
305  KALDI_LOG << B;
306  A.CopyFromMat(B);
307  CuSpMatrix<Real> C(dim);
308  C.CopyFromMat(A,kTakeLower);
309  SpMatrix<Real> D(dim);
310  C.CopyToSp(&D);
311  KALDI_LOG << "C is : ";
312  for (MatrixIndexT i = 0; i < dim; i++) {
313  for (MatrixIndexT j = 0; j <= i; j++)
314  std::cout << D(i,j) << " ";
315  std::cout << '\n';
316  }
317  C.CopyFromMat(A,kTakeUpper);
318  C.CopyToSp(&D);
319  KALDI_LOG << "C is : ";
320  for (MatrixIndexT i = 0; i < dim; i++) {
321  for (MatrixIndexT j = 0; j <= i; j++)
322  std::cout << D(i,j) << " ";
323  std::cout << '\n';
324  }
325 
326  C.CopyFromMat(A,kTakeMean);
327  C.CopyToSp(&D);
328  KALDI_LOG << "C is : ";
329  for (MatrixIndexT i = 0; i < dim; i++) {
330  for (MatrixIndexT j = 0; j <= i; j++)
331  std::cout << D(i,j) << " ";
332  std::cout << '\n';
333  }
334 
335  //KALDI_LOG << D;
336 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestCopyRows()

static void kaldi::UnitTestCopyRows ( )
static

Definition at line 713 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, rnnlm::j, Rand(), MatrixBase< Real >::RowData(), and MatrixBase< Real >::SetRandn().

713  {
714  for (MatrixIndexT p = 0; p < 10; p++) {
715  MatrixIndexT num_rows1 = 10 + Rand() % 10,
716  num_rows2 = 10 + Rand() % 10,
717  num_cols = 10 + Rand() % 10;
718  Matrix<Real> M(num_rows1, num_cols);
719  M.SetRandn();
720 
721  Matrix<Real> N1(num_rows2, num_cols),
722  N2(num_rows2, num_cols), O(num_rows2, num_cols);
723  std::vector<int32> reorder(num_rows2);
724  std::vector<const Real*> reorder_src(num_rows2,
725  static_cast<const Real*>(NULL));
726  for (int32 i = 0; i < num_rows2; i++) {
727  reorder[i] = -1 + (Rand() % (num_rows1 + 1));
728  if (reorder[i] != -1)
729  reorder_src[i] = M.RowData(reorder[i]);
730  }
731 
732  N1.CopyRows(M, &(reorder[0]));
733  N2.CopyRows(&(reorder_src[0]));
734 
735  for (int32 i = 0; i < num_rows2; i++)
736  for (int32 j = 0; j < num_cols; j++)
737  if (reorder[i] < 0) O(i, j) = 0;
738  else O(i, j) = M(reorder[i], j);
739 
740  AssertEqual(N1, O);
741  AssertEqual(N2, O);
742  }
743 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCopyRowsAndCols()

static void kaldi::UnitTestCopyRowsAndCols ( )
static

Definition at line 317 of file matrix-lib-test.cc.

References MatrixBase< Real >::CopyRowsFromVec(), rnnlm::i, KALDI_ASSERT, Rand(), and VectorBase< Real >::SetRandn().

317  {
318  // Test other mode of CopyRowsFromVec, and CopyColsFromVec,
319  // where vector is duplicated.
320  for (MatrixIndexT i = 0; i < 30; i++) {
321  MatrixIndexT dimM = 1 + Rand() % 5, dimN = 1 + Rand() % 5;
322  Vector<float> w(dimN); // test cross-type version of
323  // CopyRowsFromVec.
324  Vector<Real> v(dimM);
325  Matrix<Real> M(dimM, dimN), N(dimM, dimN);
326  v.SetRandn();
327  w.SetRandn();
328  M.CopyColsFromVec(v);
329  N.CopyRowsFromVec(w);
330  for (MatrixIndexT r = 0; r < dimM; r++) {
331  for (MatrixIndexT c = 0; c < dimN; c++) {
332  KALDI_ASSERT(M(r, c) == v(r));
333  KALDI_ASSERT(N(r, c) == w(c));
334  }
335  }
336  }
337 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCopySp() [1/2]

static void kaldi::UnitTestCopySp ( )
static

CuSpMatrix<Real> E(dim);

Definition at line 242 of file cu-test.cc.

References CuMatrixBase< Real >::CopyFromMat(), KALDI_LOG, kTakeLower, kUndefined, Rand(), and CuMatrixBase< Real >::Stride().

242  {
243  // Checking that the various versions of copying
244  // matrix to SpMatrix work the same in the symmetric case.
245  for (MatrixIndexT iter = 0;iter < 5;iter++) {
246  int32 dim = 5 + Rand() % 10;
247  SpMatrix<Real> A(dim), B(dim);
248  A.SetRandn();
249  Matrix<Real> C(A);
250  //CuMatrix<Real> D(C);
251 
252  {
253  CuMatrix<Real> D2(dim,dim);
254  D2.CopyFromMat(C);
255  KALDI_LOG << "D2 is " << D2;
256  CuSpMatrix<Real> E(D2.NumRows(), kUndefined);
257  KALDI_LOG << "D2 is " << D2;
258  E.CopyFromMat(D2, kTakeLower);
259  KALDI_LOG << "D2 is " << D2;
260  }
261 
262  CuMatrix<Real> D(dim,dim);
263  D.CopyFromMat(C);
264  KALDI_LOG << "D stride is : " << D.Stride() <<'\n';
265 
268  //E.CopyFromMat(D,kTakeLower);
269  /*
270  KALDI_LOG << D.NumRows();
271  //E.CopyFromMat(D, kTakeMean);
272  //E(D, kTakeMean);
273  //KALDI_LOG << E.NumRows();
274 
275  E.CopyToMat(&B);
276  AssertEqual(A, B);
277  B.SetZero();
278  //E.CopyFromMat(D, kTakeLower);
279  CuSpMatrix<Real> F(D,kTakeLower);
280  //F(D, kTakeLower);
281  F.CopyToMat(&B);
282  AssertEqual(A, B);
283  B.SetZero();
284  //E.CopyFromMat(D, kTakeUpper);
285  //E(D, kTakeUpper);
286  CuSpMatrix<Real> G(D, kTakeUpper);
287  G.CopyToMat(&B);
288  AssertEqual(A, B);
289  */
290  }
291 
292 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestCopySp() [2/2]

static void kaldi::UnitTestCopySp ( )
static

Definition at line 1051 of file matrix-lib-test.cc.

References AssertEqual(), SpMatrix< Real >::CopyFromMat(), kTakeLower, kTakeMean, kTakeMeanAndCheck, kTakeUpper, Rand(), and PackedMatrix< Real >::SetZero().

1051  {
1052  // Checking that the various versions of copying
1053  // matrix to SpMatrix work the same in the symmetric case.
1054  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1055  int32 dim = 5 + Rand() % 10;
1056  SpMatrix<Real> S(dim), T(dim);
1057  S.SetRandn();
1058  Matrix<Real> M(S);
1059  T.CopyFromMat(M, kTakeMeanAndCheck);
1060  AssertEqual(S, T);
1061  T.SetZero();
1062  T.CopyFromMat(M, kTakeMean);
1063  AssertEqual(S, T);
1064  T.SetZero();
1065  T.CopyFromMat(M, kTakeLower);
1066  AssertEqual(S, T);
1067  T.SetZero();
1068  T.CopyFromMat(M, kTakeUpper);
1069  AssertEqual(S, T);
1070  }
1071 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCopyToRows()

static void kaldi::UnitTestCopyToRows ( )
static

Definition at line 746 of file matrix-lib-test.cc.

References AssertEqual(), MatrixBase< Real >::CopyToRows(), rnnlm::i, rnnlm::j, Rand(), and MatrixBase< Real >::SetRandn().

746  {
747  for (MatrixIndexT p = 0; p < 10; p++) {
748  MatrixIndexT num_rows1 = 10 + Rand() % 10,
749  num_rows2 = 10 + Rand() % 10,
750  num_cols = 10 + Rand() % 10;
751  Matrix<Real> M(num_rows1, num_cols);
752  M.SetRandn();
753 
754  Matrix<Real> N(num_rows2, num_cols), O(num_rows2, num_cols);
755  std::vector<Real*> reorder_dst(num_rows1,
756  static_cast<Real*>(NULL));
757  unordered_map<MatrixIndexT, bool> used_index;
758  for (int32 i = 0; i < num_rows1; i++) {
759  MatrixIndexT index = -1 + (Rand() % (num_rows2 + 1));
760  if (used_index.find(index) == used_index.end()) {
761  used_index[index] = true;
762  } else {
763  index = -1;
764  }
765  if (index != -1) {
766  reorder_dst[i] = N.RowData(index);
767  for (int32 j = 0; j < num_cols; j++)
768  O(index, j) = M(i, j);
769  }
770  }
771 
772  M.CopyToRows(&(reorder_dst[0]));
773 
774  AssertEqual(N, O);
775  }
776 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuApproxEqual()

static void kaldi::UnitTestCuApproxEqual ( )
static

Definition at line 2157 of file cu-matrix-test.cc.

References rnnlm::i, KALDI_ASSERT, Rand(), and CuMatrixBase< Real >::SetRandn().

2157  {
2158  Real tol = 0.1;
2159  for (int32 i = 0; i < 2; i++) {
2160  int32 M = 1 + Rand() % 10, N = 1 + Rand() % 10;
2161  CuMatrix<Real> A(M, N), B(M, N);
2162  A.SetRandn();
2163  B.SetRandn();
2164  Matrix<Real> diff(A), Bm(B);
2165  diff.AddMat(-1.0, Bm);
2166  Real norm = diff.FrobeniusNorm();
2167  KALDI_ASSERT((norm <= tol * A.FrobeniusNorm()) == (A.ApproxEqual(B, tol)));
2168  tol *= 2.0;
2169  }
2170 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuArray()

static void kaldi::UnitTestCuArray ( )
static

Definition at line 53 of file cu-array-test.cc.

References AssertEqual(), CuArrayBase< T >::CopyToHost(), CuArrayBase< T >::CopyToVec(), CuArrayBase< T >::Dim(), rnnlm::i, KALDI_ASSERT, kSetZero, Rand(), CuArray< T >::Resize(), and CuArrayBase< T >::Set().

53  {
54  for (int32 i = 0; i < 30; i++) {
55  int32 size = Rand() % 5;
56  size = size * size * size; // Have a good distribution of sizes, including >256.
57  int32 size2 = Rand() % 4;
58  std::vector<T> vec(size);
59  std::vector<T> garbage_vec(size2); // We just use garbage_vec to make sure
60  // we sometimes resize from empty,
61  // sometimes not.
62 
63  int32 byte_size = size * sizeof(T);
64  std::vector<char> rand_c(byte_size);
65  for (size_t i = 0; i < byte_size; i++)
66  rand_c[i] = Rand() % 256;
67  if (!vec.empty()) {
68  std::memcpy((void*)&(vec[0]), (void*)&(rand_c[0]),
69  byte_size);
70  }
71 
72  { // test constructor from vector and CopyToVec.
73  CuArray<T> cu_vec(vec);
74  std::vector<T> vec2;
75  cu_vec.CopyToVec(&vec2);
76  T *vec22 = new T[vec.size()];
77  cu_vec.CopyToHost(vec22);
78  delete[] vec22;
79  }
80 
81  { // test assignment operator from CuArray.
82  CuArray<T> cu_vec(vec);
83  CuArray<T> cu_vec2(garbage_vec);
84  cu_vec2 = cu_vec;
85  std::vector<T> vec2;
86  cu_vec2.CopyToVec(&vec2);
87  AssertEqual(vec, vec2);
88  KALDI_ASSERT(cu_vec2.Dim() == int32(vec2.size())); // test Dim()
89  }
90 
91  { // test resize with resize_type = kSetZero.
92  CuArray<T> cu_vec(vec);
93  cu_vec.Resize(size, kSetZero);
94  std::vector<T> vec2(vec);
95 
96  if (!vec2.empty())
97  std::memset(&(vec2[0]), 0, vec2.size() * sizeof(T));
98  std::vector<T> vec3;
99  cu_vec.CopyToVec(&vec3);
100  AssertEqual(vec2, vec3); // testing equality of zero arrays.
101  }
102 
103  if (sizeof(T) == sizeof(int32) && size > 0) { // test Set for type int32, or same size.
104  CuArray<T> cu_vec(vec);
105  cu_vec.Set(vec[0]);
106  for (size_t i = 1; i < vec.size(); i++) vec[i] = vec[0];
107  std::vector<T> vec2;
108  cu_vec.CopyToVec(&vec2);
109  AssertEqual(vec, vec2);
110  }
111  }
112 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Class CuArray represents a vector of an integer or struct of type T.
Definition: cu-array.h:32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void AssertEqual(const std::vector< T > &vec1, const std::vector< T > &vec2)

◆ UnitTestCuBlockMatrixAddMatBlock()

static void kaldi::UnitTestCuBlockMatrixAddMatBlock ( )
static

Definition at line 76 of file cu-block-matrix-test.cc.

References CuMatrixBase< Real >::AddMatBlock(), AssertEqual(), rnnlm::i, kNoTrans, kTrans, CuBlockMatrix< Real >::NumCols(), CuBlockMatrix< Real >::NumRows(), Rand(), CuMatrixBase< Real >::SetRandn(), and swap().

76  {
77  for (int32 i = 0; i < 20; i++) {
78  int32 num_blocks = Rand() % 5;
79  std::vector<CuMatrix<Real> > data(num_blocks);
80  for (int32 b = 0; b < num_blocks; b++) {
81  int32 dimM = 100 + Rand() % 255, dimN = 10 + Rand() % 20;
82  // early failures will have small dim for easier eyeballing.
83  if (b % 2 == 0) std::swap(dimM, dimN);
84  data[b].Resize(dimM, dimN);
85  data[b].SetRandn();
86  }
87  CuBlockMatrix<Real> B(data);
88  int32 B_num_rows = B.NumRows(), B_num_cols = B.NumCols();
89  // will do X += A B
90 
91  MatrixTransposeType transB = (i % 2 == 1 ? kTrans : kNoTrans),
92  transA = (i % 3 == 1 ? kTrans : kNoTrans);
93  if (transB == kTrans) std::swap(B_num_rows, B_num_cols);
94 
95  int32 X_num_rows = 100 + Rand() % 255, X_num_cols = B_num_cols,
96  A_num_rows = X_num_rows, A_num_cols = B_num_rows;
97  if (data.size() == 0) { X_num_rows = 0; A_num_rows = 0; }
98  if (transA == kTrans) std::swap(A_num_rows, A_num_cols);
99 
100  Real alpha = 2.0, beta = -1.0;
101  CuMatrix<Real> X(X_num_rows, X_num_cols);
102  X.SetRandn();
103  CuMatrix<Real> A(A_num_rows, A_num_cols);
104  A.SetRandn();
105 
106  CuMatrix<Real> Xcopy(X), Bcopy(B), Xorig(X), Aorig(A);
107  Xcopy.AddMatMat(alpha, A, transA, Bcopy, transB, beta);
108  X.AddMatBlock(alpha, A, transA, B, transB, beta);
109 
110  AssertEqual(X, Xcopy);
111  }
112 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
The class CuBlockMatrix holds a vector of objects of type CuMatrix, say, M_1, M_2, .
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuBlockMatrixAddMatMat()

static void kaldi::UnitTestCuBlockMatrixAddMatMat ( )
static

Definition at line 116 of file cu-block-matrix-test.cc.

References CuBlockMatrix< Real >::AddMatMat(), CuMatrixBase< Real >::AddMatMat(), ApproxEqual(), CuBlockMatrix< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, KALDI_LOG, KALDI_WARN, kNoTrans, kTrans, CuBlockMatrix< Real >::NumCols(), CuBlockMatrix< Real >::NumRows(), Rand(), CuMatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::Sum(), and swap().

116  {
117  for (int32 i = 0; i < 20; i++) {
118  int32 num_blocks = Rand() % 5 + 1;
119  std::vector<CuMatrix<Real> > data(num_blocks);
120  for (int32 b = 0; b < num_blocks; b++) {
121  int32 dimM = 100 + Rand() % 255, dimN = 10 + Rand() % 20;
122  if (i == 0) { dimM = 1; dimN = 1; }
123  // early failures will have small dim for easier eyeballing.
124  if (b % 2 == 0) std::swap(dimM, dimN);
125  data[b].Resize(dimM, dimN);
126  KALDI_LOG << "dimM " << dimM << ", dimN " << dimN << ", stride " << data[b].Stride();
127  data[b].SetRandn();
128  }
129 
130  CuBlockMatrix<Real> B(data);
131  int32 B_num_rows = B.NumRows(), B_num_cols = B.NumCols();
132  // will do B += C D
133 
134  int32 C_num_rows = B_num_rows, C_num_cols = 100 + Rand() % 255;
135  if (C_num_rows == 0) C_num_cols = 0;
136  int32 D_num_rows = C_num_cols, D_num_cols = B_num_cols;
137 
138  MatrixTransposeType transC = (i % 2 == 1 ? kTrans : kNoTrans),
139  transD = (i % 3 == 1 ? kTrans : kNoTrans);
140  if (transC == kTrans) std::swap(C_num_rows, C_num_cols);
141  if (transD == kTrans) std::swap(D_num_rows, D_num_cols);
142 
143  CuMatrix<Real> C(C_num_rows, C_num_cols), D(D_num_rows, D_num_cols);
144  C.SetRandn();
145  D.SetRandn();
146 
147  CuMatrix<Real> Bmat(B);
148 
149  Real alpha = 2.0, beta = -1.0;
150 
151  CuBlockMatrix<Real> Bcopy(B);
152 
153  B.AddMatMat(alpha, C, transC, D, transD, beta);
154 
155  Bmat.AddMatMat(alpha, C, transC, D, transD, beta);
156 
157  // Now check that the block-structured part of Bmat is the
158  // same as B.
159  Bcopy.CopyFromMat(Bmat); // copy block-structured part from Bmat to Bcopy.
160 
161  if (!ApproxEqual(B, Bcopy)) {
162  KALDI_WARN << "CuBlockMatrixTest failure, please report to maintainers: Bcopy = "
163  << Bcopy << ", B = " << B << ", C = " << C << ", D = " << D
164  << ", Bmat = " << B << " transD = " << transD << ", transC = "
165  << transC;
166  KALDI_ERR << "Please give this log to the maintainers.";
167  }
168  KALDI_ASSERT(Bmat.Sum() != 0 || B_num_rows == 0);
169  }
170 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
The class CuBlockMatrix holds a vector of objects of type CuMatrix, say, M_1, M_2, .
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static bool ApproxEqual(const CuBlockMatrix< Real > &A, const CuBlockMatrix< Real > &B, float tol=0.001)
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestCuBlockMatrixIO()

static void kaldi::UnitTestCuBlockMatrixIO ( )
static

Definition at line 46 of file cu-block-matrix-test.cc.

References AssertEqual(), rnnlm::i, KALDI_ASSERT, Rand(), CuBlockMatrix< Real >::Read(), swap(), and CuBlockMatrix< Real >::Write().

46  {
47  for (int32 i = 0; i < 10; i++) {
48  int32 num_blocks = Rand() % 5;
49  std::vector<CuMatrix<Real> > data(num_blocks);
50  for (int32 b = 0; b < num_blocks; b++) {
51  int32 dimM = 100 + Rand() % 255, dimN = 10 + Rand() % 20;
52  if (b % 2 == 0) std::swap(dimM, dimN);
53  data[b].Resize(dimM, dimN);
54  data[b].SetRandn();
55  }
56  CuBlockMatrix<Real> B(data);
57 
58  std::ostringstream os;
59  bool binary = (i % 4 < 2);
60  B.Write(os, binary);
61 
63  std::istringstream is(os.str());
64  B2.Read(is, binary);
65 
66  CuMatrix<Real> mat(B), mat2(B2);
67  AssertEqual(mat, mat2);
68  if (!data.empty())
69  KALDI_ASSERT(mat.Sum() != 0.0);
70  }
71 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
The class CuBlockMatrix holds a vector of objects of type CuMatrix, say, M_1, M_2, .
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void Read(std::istream &is, bool binary)

◆ UnitTestCuCholesky()

static void kaldi::UnitTestCuCholesky ( )
static

Definition at line 112 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMatMat(), CuMatrixBase< Real >::ApproxEqual(), CuMatrixBase< Real >::Cholesky(), CuMatrixBase< Real >::CopyLowerToUpper(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, Rand(), CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SymAddMat2().

112  {
113  for (int32 i = 0; i < 2; i++) {
114  int32 M = 1 + Rand() % 10, N = M + 5;
115 
116  CuMatrix<Real> A(M, N);
117  A.SetRandn();
118  CuMatrix<Real> S(M, M);
119  // SymAddMat2 only copies lower triangle.
120  // it's OK- Cholesky only reads the lower triangle.
121  S.SymAddMat2(1.0, A, kNoTrans, 0.0);
122 
123  CuMatrix<Real> C(S);
124  C.Cholesky();
125 
126  CuMatrix<Real> S2(M, M);
127  S2.AddMatMat(1.0, C, kNoTrans, C, kTrans, 0.0);
128  S.CopyLowerToUpper();
129  KALDI_ASSERT(S.ApproxEqual(S2));
130  }
131 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuCopy()

static void kaldi::UnitTestCuCopy ( )
static

Definition at line 2195 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::ApproxEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, and Rand().

2195  {
2196  for (int32 i = 0; i < 10; i++) {
2197  int32 M = 1 + Rand() % 10, N = 1 + Rand() % 10;
2198  CuMatrix<Real> A(M, N);
2200  CuMatrix<Real> C(B, kTrans);
2201  CuMatrix<Real> D(N, M);
2202  D.CopyFromMat(C, kTrans);
2203  CuMatrix<OtherReal> E(N, M);
2204  E.CopyFromMat(D, kNoTrans);
2205  CuMatrix<Real> F(M, N);
2206  F.CopyFromMat(E, kTrans);
2207 
2208  Matrix<OtherReal> G(M, N);
2209  G.CopyFromMat(F, kNoTrans);
2210  CuMatrix<Real> H(N, M);
2211  H.CopyFromMat(G, kTrans);
2212  Matrix<OtherReal> I(M, N);
2213  I.CopyFromMat(H, kTrans);
2214  CuMatrix<Real> J(I, kTrans);
2215  Matrix<OtherReal> K(J, kTrans);
2216  CuMatrix<Real> L(K, kNoTrans);
2217 
2218  KALDI_ASSERT(A.ApproxEqual(L));
2219  }
2220 
2221 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuDiffLogSoftmax()

static void kaldi::UnitTestCuDiffLogSoftmax ( )
static

Definition at line 2325 of file cu-matrix-test.cc.

References VectorBase< Real >::AddColSumMat(), MatrixBase< Real >::AddMat(), MatrixBase< Real >::ApplyExp(), ApproxEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), CuMatrixBase< Real >::DiffLogSoftmaxPerRow(), rnnlm::i, KALDI_ASSERT, kNoTrans, MatrixBase< Real >::MulRowsVec(), rnnlm::n, MatrixBase< Real >::NumRows(), RandInt(), RandZeroToOneMatrix(), MatrixBase< Real >::Scale(), and MatrixBase< Real >::SetRandn().

2325  {
2326  for (int32 i = 0; i < 4; i++) {
2327  int m = RandInt(10, 280), n = RandInt(10, 280);
2328  Matrix<Real> Hi(m, n);
2329  Matrix<Real> Ho(m, n);
2330  Matrix<Real> Hy(m, n);
2331  Hi.SetRandn();
2332  RandZeroToOneMatrix(&Hy);
2333 
2334  CuMatrix<Real> Di(m, n);
2335  CuMatrix<Real> Do(m, n);
2336  CuMatrix<Real> Dy(m, n);
2337  Di.CopyFromMat(Hi);
2338  Dy.CopyFromMat(Hy);
2339 
2340  //gpu
2341  if (i % 2 == 0) {
2342  Do.DiffLogSoftmaxPerRow(Dy, Di);
2343  } else {
2344  // in-place.
2345  Do.CopyFromMat(Di);
2346  Do.DiffLogSoftmaxPerRow(Dy, Do);
2347  }
2348  //cpu
2349  {
2350  const MatrixBase<Real> &Y(Hy), &E(Hi);
2351  MatrixBase<Real> &D(Ho);
2352  D.CopyFromMat(Y);
2353  D.ApplyExp(); // exp(y)
2354  Vector<Real> E_sum(D.NumRows()); // Initializes to zero
2355  E_sum.AddColSumMat(1.0, E); // Sum(e)
2356  D.MulRowsVec(E_sum); // exp(y) Sum(e)
2357  D.Scale(-1.0); // - exp(y) Sum(e)
2358  D.AddMat(1.0, E, kNoTrans); // e - exp(y_i) Sum(e)
2359  }
2360 
2361  Matrix<Real> Ho2(m, n);
2362  Do.CopyToMat(&Ho2);
2363 
2364  KALDI_ASSERT(ApproxEqual(Ho, Ho2));
2365  }
2366 }
Base class which provides matrix operations not involving resizing or allocation. ...
Definition: kaldi-matrix.h:49
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
struct rnnlm::@11::@12 n
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void RandZeroToOneMatrix(MatrixBase< Real > *mat)
void AddColSumMat(Real alpha, const MatrixBase< Real > &M, Real beta=1.0)
Does *this = alpha * (sum of columns of M) + beta * *this.
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestCuDiffNormalizePerRow()

static void kaldi::UnitTestCuDiffNormalizePerRow ( )
static

Definition at line 593 of file cu-math-test.cc.

References VectorBase< Real >::AddDiagMat2(), VectorBase< Real >::AddDiagMatMat(), MatrixBase< Real >::AddDiagVecMat(), VectorBase< Real >::ApplyFloor(), AssertEqual(), CuMatrixBase< Real >::CopyFromMat(), MatrixBase< Real >::Data(), kaldi::cu::DiffNormalizePerRow(), Timer::Elapsed(), rnnlm::i, KALDI_LOG, kNoTrans, kTrans, kUndefined, MatrixBase< Real >::MulRowsVec(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

593  {
594  for (int32 i = 0; i < 2; i++) {
595  int row = 10 + Rand() % 40;
596  int col = 10 + Rand() % 50;
597 
598  Matrix<Real> Hi(row, col);
599  Matrix<Real> Ho(row, col + 1);
600  Matrix<Real> Hid(row, col);
601  Matrix<Real> Hod(row, col + 1);
602  Hi.SetRandn();
603  Hod.SetRandn();
604  Hi.Scale(5.0);
605 
606  CuMatrix<Real> Di(row, col);
607  CuMatrix<Real> Do(row, col + 1);
608  CuMatrix<Real> Did(row, col);
609  CuMatrix<Real> Dod(row, col + 1);
610  Di.CopyFromMat(Hi);
611  Dod.CopyFromMat(Hod);
612 
613  Real target_rms = 0.3456;
614  bool add_log_stddev = true;
615  const Real kSquaredNormFloor = 1.3552527156068805425e-20; // 2^-66
616 
617  //gpu
618  cu::DiffNormalizePerRow(Di, Dod, target_rms, add_log_stddev, &Did);
619 
620  //cpu
621  {
622  MatrixBase<Real>* in_deriv = &Hid;
623  MatrixBase<Real>& out_deriv(Hod);
624  MatrixBase<Real>& in_value(Hi);
625 
626  const SubMatrix<Real> out_deriv_no_log(out_deriv, 0, out_deriv.NumRows(),
627  0, in_value.NumCols());
628  Vector<Real> dot_products(out_deriv.NumRows());
629  dot_products.AddDiagMatMat(1.0, out_deriv_no_log, kNoTrans, in_value,
630  kTrans, 0.0);
631  Vector<Real> in_norm(in_value.NumRows());
632  Real d_scaled = (in_value.NumCols() * target_rms * target_rms);
633  in_norm.AddDiagMat2(1.0, in_value, kNoTrans, 0.0);
634  if (add_log_stddev) {
635  Vector<Real> log_stddev_deriv(in_norm), // log_stddev deriv as dF/dy .* (x^T x)^-1
636  out_deriv_for_stddev(out_deriv.NumRows(), kUndefined);
637  // f = log(sqrt(max(epsi, x^T x / D)))
638  // df/dx = epsi^2 * D < x^T x ? (1/(x^T x)) * x : 0.
639  // we don't compute this exactly below for the case when x^2 x is very
640  // small, but we do make sure that the deriv isn't infinity when the input
641  // is zero.
642  log_stddev_deriv.ApplyFloor(in_value.NumCols() * kSquaredNormFloor);
643  log_stddev_deriv.ApplyPow(-1.0);
644  out_deriv_for_stddev.CopyColFromMat(out_deriv,
645  (out_deriv.NumCols() - 1));
646  log_stddev_deriv.MulElements(out_deriv_for_stddev);
647  if (in_deriv)
648  in_deriv->AddDiagVecMat(1.0, log_stddev_deriv, in_value, kNoTrans,
649  1.0);
650  }
651  in_norm.Scale(1.0 / d_scaled);
652  in_norm.ApplyFloor(kSquaredNormFloor);
653  in_norm.ApplyPow(-0.5);
654  if (in_deriv) {
655  if (in_deriv->Data() != out_deriv_no_log.Data())
656  in_deriv->AddDiagVecMat(1.0, in_norm, out_deriv_no_log, kNoTrans,
657  1.0);
658  else
659  in_deriv->MulRowsVec(in_norm);
660  in_norm.ReplaceValue(1.0 / sqrt(kSquaredNormFloor), 0.0);
661  in_norm.ApplyPow(3.0);
662  dot_products.MulElements(in_norm);
663 
664  in_deriv->AddDiagVecMat(-1.0 / d_scaled, dot_products, in_value,
665  kNoTrans, 1.0);
666  }
667 
668  Matrix<Real> Hid2(Did);
669  AssertEqual(Hid, Hid2, 0.00001);
670  }
671  }
672 
673  for (int dim = 16; dim <= 1024; dim *= 2) {
674  BaseFloat time_in_secs = 0.025;
675  CuMatrix<Real> id(dim, dim), iv(dim, dim), od(dim, dim + 1);
676  iv.SetRandn();
677  od.SetRandn();
678  Timer tim;
679  int32 iter = 0;
680  for (; tim.Elapsed() < time_in_secs; iter++) {
681  cu::DiffNormalizePerRow(iv, od, Real(0.456), true, &id);
682  }
683  BaseFloat fdim = dim;
684  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
685  KALDI_LOG << "For CuMath::DiffNormalizePerRow"
686  << (sizeof(Real)==8?"<double>":"<float>")
687  << ", for dim = " << dim << ", speed was " << gflops
688  << " gigaflops.";
689  }
690 }
Base class which provides matrix operations not involving resizing or allocation. ...
Definition: kaldi-matrix.h:49
const Real * Data() const
Gives pointer to raw data (const).
Definition: kaldi-matrix.h:79
void AddDiagMat2(Real alpha, const MatrixBase< Real > &M, MatrixTransposeType trans=kNoTrans, Real beta=1.0)
Add the diagonal of a matrix times itself: *this = diag(M M^T) + beta * *this (if trans == kNoTrans)...
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
void ApplyFloor(Real floor_val, MatrixIndexT *floored_count=nullptr)
Applies floor to all elements.
Definition: kaldi-vector.h:149
float BaseFloat
Definition: kaldi-types.h:29
void DiffNormalizePerRow(const CuMatrixBase< Real > &in_value, const CuMatrixBase< Real > &out_deriv, const Real target_rms, const bool add_log_stddev, CuMatrixBase< Real > *in_deriv)
Definition: cu-math.cc:349
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void MulRowsVec(const VectorBase< Real > &scale)
Equivalent to (*this) = diag(scale) * (*this).
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void AddDiagMatMat(Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transM, const MatrixBase< Real > &N, MatrixTransposeType transN, Real beta=1.0)
Add the diagonal of a matrix product: *this = diag(M N), assuming the "trans" arguments are both kNoT...
void AddDiagVecMat(const Real alpha, const VectorBase< Real > &v, const MatrixBase< Real > &M, MatrixTransposeType transM, Real beta=1.0)
*this = beta * *this + alpha * diag(v) * M [or M^T].
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
Sub-matrix representation.
Definition: kaldi-matrix.h:988

◆ UnitTestCuDiffSigmoid()

static void kaldi::UnitTestCuDiffSigmoid ( )
static

Definition at line 2251 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), CuMatrixBase< Real >::DiffSigmoid(), KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), RandZeroToOneMatrix(), and MatrixBase< Real >::SetRandn().

2251  {
2252  Matrix<Real> Hi(100,111);
2253  Matrix<Real> Ho(100,111);
2254  Matrix<Real> Hy(100,111);
2255  Hi.SetRandn();
2256  RandZeroToOneMatrix(&Hy);
2257 
2258  CuMatrix<Real> Di(100,111);
2259  CuMatrix<Real> Do(100,111);
2260  CuMatrix<Real> Dy(100,111);
2261  Di.CopyFromMat(Hi);
2262  Dy.CopyFromMat(Hy);
2263 
2264  //gpu
2265  Do.DiffSigmoid(Dy, Di);
2266  //cpu
2267  for(MatrixIndexT r=0; r<Ho.NumRows(); r++) {
2268  for(MatrixIndexT c=0; c<Ho.NumCols(); c++) {
2269  Ho(r, c) = Hy(r, c)*(1.0 - Hy(r, c)) * Hi(r, c);
2270  }
2271  }
2272 
2273  Matrix<Real> Ho2(100,111);
2274  Do.CopyToMat(&Ho2);
2275 
2276  KALDI_ASSERT(ApproxEqual(Ho,Ho2));
2277 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void RandZeroToOneMatrix(MatrixBase< Real > *mat)
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuDiffSoftmax()

static void kaldi::UnitTestCuDiffSoftmax ( )
static

Definition at line 2281 of file cu-matrix-test.cc.

References VectorBase< Real >::AddDiagMatMat(), MatrixBase< Real >::AddDiagVecMat(), ApproxEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), CuMatrixBase< Real >::DiffSoftmaxPerRow(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, MatrixBase< Real >::MulElements(), rnnlm::n, MatrixBase< Real >::NumRows(), RandInt(), RandZeroToOneMatrix(), and MatrixBase< Real >::SetRandn().

2281  {
2282  for (int32 i = 0; i < 4; i++) {
2283  int m = RandInt(10, 280), n = RandInt(10, 280);
2284  Matrix<Real> Hi(m, n);
2285  Matrix<Real> Ho(m, n);
2286  Matrix<Real> Hy(m, n);
2287  Hi.SetRandn();
2288  RandZeroToOneMatrix(&Hy);
2289 
2290  CuMatrix<Real> Di(m, n);
2291  CuMatrix<Real> Do(m, n);
2292  CuMatrix<Real> Dy(m, n);
2293  Di.CopyFromMat(Hi);
2294  Dy.CopyFromMat(Hy);
2295 
2296  //gpu
2297  if (i % 2 == 0) {
2298  Do.DiffSoftmaxPerRow(Dy, Di);
2299  } else {
2300  // in-place.
2301  Do.CopyFromMat(Di);
2302  Do.DiffSoftmaxPerRow(Dy, Do);
2303  }
2304  //cpu
2305  {
2306  const MatrixBase<Real> &P(Hy), &E(Hi);
2307  MatrixBase<Real> &D(Ho);
2308  D.CopyFromMat(P);
2309  D.MulElements(E);
2310  // At this point, D = P .* E (in matlab notation)
2311  Vector<Real> pe_vec(D.NumRows()); // For each row i, the dot product (p_t . e_t).
2312  pe_vec.AddDiagMatMat(1.0, P, kNoTrans, E, kTrans, 0.0);
2313  D.AddDiagVecMat(-1.0, pe_vec, P, kNoTrans, 1.0); // does D -= diag(pe_vec) * P.
2314  }
2315 
2316  Matrix<Real> Ho2(m, n);
2317  Do.CopyToMat(&Ho2);
2318 
2319  KALDI_ASSERT(ApproxEqual(Ho, Ho2));
2320  }
2321 }
Base class which provides matrix operations not involving resizing or allocation. ...
Definition: kaldi-matrix.h:49
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
struct rnnlm::@11::@12 n
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void AddDiagMatMat(Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transM, const MatrixBase< Real > &N, MatrixTransposeType transN, Real beta=1.0)
Add the diagonal of a matrix product: *this = diag(M N), assuming the "trans" arguments are both kNoT...
static void RandZeroToOneMatrix(MatrixBase< Real > *mat)
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestCuDiffTanh()

static void kaldi::UnitTestCuDiffTanh ( )
static

Definition at line 2593 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), CuMatrixBase< Real >::DiffTanh(), KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), RandZeroToOneMatrix(), and MatrixBase< Real >::SetRandn().

2593  {
2594  Matrix<Real> Hi(100,111);
2595  Matrix<Real> Ho(100,111);
2596  Matrix<Real> Hy(100,111);
2597  Hi.SetRandn();
2598  RandZeroToOneMatrix(&Hy);
2599 
2600  CuMatrix<Real> Di(100,111);
2601  CuMatrix<Real> Do(100,111);
2602  CuMatrix<Real> Dy(100,111);
2603  Di.CopyFromMat(Hi);
2604  Dy.CopyFromMat(Hy);
2605 
2606  //gpu
2607  Do.DiffTanh(Dy, Di);
2608  //cpu
2609  for(MatrixIndexT r=0; r<Ho.NumRows(); r++) {
2610  for(MatrixIndexT c=0; c<Ho.NumCols(); c++) {
2611  Ho(r, c) = (1.0 - Hy(r, c)*Hy(r, c)) * Hi(r, c);
2612  }
2613  }
2614 
2615  Matrix<Real> Ho2(100,111);
2616  Do.CopyToMat(&Ho2);
2617 
2618  KALDI_ASSERT(ApproxEqual(Ho,Ho2));
2619 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void RandZeroToOneMatrix(MatrixBase< Real > *mat)
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuDiffXent()

static void kaldi::UnitTestCuDiffXent ( )
static

Definition at line 2483 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuArray< T >::CopyFromVec(), CuMatrixBase< Real >::CopyToMat(), CuVectorBase< Real >::CopyToVec(), CuMatrixBase< Real >::DiffXent(), rnnlm::i, KALDI_ASSERT, Log(), MatrixBase< Real >::NumRows(), Rand(), and RandZeroToOneMatrix().

2483  {
2484  int32 X=100, Y=111;
2485  //nnet output / diff
2486  Matrix<Real> Hi(X,Y);
2487  RandZeroToOneMatrix(&Hi);
2488  CuMatrix<Real> Di(X,Y);
2489  Di.CopyFromMat(Hi);
2490  //target vector
2491  std::vector<int32> Htgt(X);
2492  for(int32 i=0; i<X; i++) {
2493  Htgt[i] = Rand()%Y;
2494  }
2495  CuArray<int32> Dtgt(X);
2496  Dtgt.CopyFromVec(Htgt);
2497  //logpost vector
2498  Vector<Real> Hlogpost(X);
2499  CuVector<Real> Dlogpost(X);
2500 
2501  //gpu
2502  Di.DiffXent(Dtgt, &Dlogpost);
2503  //cpu
2504  for(MatrixIndexT r=0; r<Hi.NumRows(); r++) {
2505  int32 col_tgt = Htgt[r];
2506  Hlogpost(r) = Log(Hi(r, col_tgt));
2507  Hi(r, col_tgt) -= 1.0;
2508  }
2509 
2510  Matrix<Real> Hi2(X,Y);
2511  Di.CopyToMat(&Hi2);
2512  Vector<Real> Hlogpost2(X);
2513  Dlogpost.CopyToVec(&Hlogpost2);
2514 
2515  KALDI_ASSERT(ApproxEqual(Hi,Hi2));
2516  KALDI_ASSERT(ApproxEqual(Hlogpost,Hlogpost2));
2517 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
double Log(double x)
Definition: kaldi-math.h:100
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void RandZeroToOneMatrix(MatrixBase< Real > *mat)
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuFindRowMaxId()

static void kaldi::UnitTestCuFindRowMaxId ( )
static

Definition at line 2444 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::CopyFromMat(), CuArrayBase< T >::CopyToVec(), CuMatrixBase< Real >::FindRowMaxId(), rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), and MatrixBase< Real >::SetRandn().

2444  {
2445  for (int32 i = 0; i < 2; i++) {
2446  int32 dimM = 100 + Rand() % 200, dimN = 100 + Rand() % 200;
2447  Matrix<Real> Hi(dimM, dimN);
2448  Hi.SetRandn();
2449 
2450  CuMatrix<Real> Di(dimM, dimN);
2451  Di.CopyFromMat(Hi);
2452 
2453  std::vector<int32> Hmax(dimM);
2454  CuArray<int32> Dmax(dimN);
2455 
2456  // on gpu
2457  Di.FindRowMaxId(&Dmax);
2458 
2459  // on cpu
2460  for(MatrixIndexT r=0; r<Hi.NumRows(); r++) {
2461  Real max=-1.0e+20; int32 idx=-1;
2462  for(MatrixIndexT c=0; c<Hi.NumCols(); c++) {
2463  if(Hi(r,c) > max) { idx=c; max=Hi(r,c); }
2464  }
2465  Hmax[r] = idx;
2466  }
2467 
2468  std::vector<int32> Hmax2(dimM);
2469  Dmax.CopyToVec(&Hmax2);
2470 
2471  // If the same value were generated randomly we can get to a case
2472  // where the GPU and CPU return different columns. Both would be correct.
2473  // Thus check that the max for each row is the same and not the index.
2474  for (MatrixIndexT r=0; r<Hi.NumRows(); r++) {
2475  KALDI_ASSERT(Hi(r, Hmax[r]) == Di(r, Hmax2[r]));
2476  }
2477  }
2478 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuLogSoftmax()

static void kaldi::UnitTestCuLogSoftmax ( )
static

Definition at line 2407 of file cu-matrix-test.cc.

References ApproxEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, CuMatrixBase< Real >::LogSoftMaxPerRow(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::Row(), MatrixBase< Real >::Scale(), and MatrixBase< Real >::SetRandn().

2407  {
2408 
2409  for (int32 i = 0; i < 50; i++) {
2410  int row = 10 + Rand() % 300;
2411  int col = 10 + Rand() % 300;
2412 
2413  Matrix<Real> Hi(row, col);
2414  Matrix<Real> Ho(row, col);
2415  Hi.SetRandn();
2416  Hi.Scale(5.0);
2417 
2418  CuMatrix<Real> Di(row, col);
2419  CuMatrix<Real> Do(row, col);
2420  Di.CopyFromMat(Hi);
2421 
2422  //gpu
2423  if (i % 2 == 0) {
2424  Do.LogSoftMaxPerRow(Di);
2425  } else {
2426  // in-place.
2427  Do.CopyFromMat(Di);
2428  Do.LogSoftMaxPerRow(Do);
2429  }
2430  //cpu
2431  Ho.CopyFromMat(Hi);
2432  for(MatrixIndexT r=0; r<Ho.NumRows(); r++) {
2433  Ho.Row(r).ApplyLogSoftMax();
2434  }
2435 
2436  Matrix<Real> Ho2(Do);
2437 
2438  KALDI_ASSERT(ApproxEqual(Ho, Ho2, (Real)0.00001));
2439  }
2440 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMathComputeLstmNonlinearity()

static void kaldi::UnitTestCuMathComputeLstmNonlinearity ( )
static

Definition at line 166 of file cu-math-test.cc.

References AssertEqual(), kaldi::cu::ComputeLstmNonlinearity(), kaldi::cu::CpuComputeLstmNonlinearity(), Timer::Elapsed(), rnnlm::i, KALDI_LOG, Rand(), RandInt(), MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

166  {
167  for (int i = 0; i < 3; i++) {
168  int32 num_rows = 1 + Rand() % 100;
169  int32 cell_dim = 1 + Rand() % 2000;
170  int32 dropout_dim = (RandInt(0, 1) == 0 ? 0 : 3);
171  Matrix<Real> Hinput(num_rows, 5 * cell_dim + dropout_dim);
172  Matrix<Real> Hparams(3, cell_dim);
173  Matrix<Real> Houtput(num_rows, 2 * cell_dim);
174  Hinput.SetRandn();
175  Hparams.SetRandn();
176 
177  CuMatrix<Real> Dinput(Hinput);
178  CuMatrix<Real> Dparams(Hparams);
179  CuMatrix<Real> Doutput(Houtput);
180 
181  cu::CpuComputeLstmNonlinearity(Hinput, Hparams, &Houtput);
182  cu::ComputeLstmNonlinearity(Dinput, Dparams, &Doutput);
183 
184  Matrix<Real> HDoutput(Doutput);
185  AssertEqual(Houtput, HDoutput);
186  }
187 
188  for (int i = 16; i <= 1024; i *= 2) {
189  BaseFloat time_in_secs = 0.025;
190  int32 num_rows = i;
191  int32 cell_dim = i;
192  int32 dropout_dim = (RandInt(0, 1) == 0 ? 0 : 3);
193  CuMatrix<Real> input(num_rows, 5 * cell_dim + dropout_dim);
194  CuMatrix<Real> params(3, cell_dim);
195  CuMatrix<Real> output(num_rows, 2 * cell_dim);
196  input.SetRandn();
197  params.SetRandn();
198 
199  Timer tim;
200  int32 iter = 0;
201  for (; tim.Elapsed() < time_in_secs; iter++)
202  cu::ComputeLstmNonlinearity(input, params, &output);
203 
204  BaseFloat gflops = ((BaseFloat) i * i * iter) / (tim.Elapsed() * 1.0e+09);
205  KALDI_LOG << "For ComputeLstmNonlinearity"
206  << (sizeof(Real)==8 ? "<double>" : "<float>") << ", for dim = "
207  << i << ", speed was " << gflops << " gigaflops";
208  if (tim.Elapsed() > 0.05)
209  break;
210  }
211 }
void CpuComputeLstmNonlinearity(const MatrixBase< Real > &input_mat, const MatrixBase< Real > &params_mat, MatrixBase< Real > *output)
Definition: cu-math.cc:445
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95
void ComputeLstmNonlinearity(const CuMatrixBase< Real > &input, const CuMatrixBase< Real > &params, CuMatrixBase< Real > *output)
this is a special-purpose function used by class LstmNonlinearityComponent, to do its forward propaga...
Definition: cu-math.cc:489

◆ UnitTestCuMathCopy()

static void kaldi::UnitTestCuMathCopy ( )
static

Definition at line 97 of file cu-math-test.cc.

References AssertEqual(), kaldi::cu::Copy(), CuArray< T >::CopyFromVec(), rnnlm::i, rnnlm::j, CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), Rand(), and CuMatrixBase< Real >::SetRandn().

97  {
98  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
99  CuMatrix<Real> src(M, N);
100  CuMatrix<Real> tgt(M, N);
101  CuArray<int32> copy_from_idx;
102 
103  src.SetRandn();
104  int32 n_rows = src.NumRows();
105  int32 n_columns = src.NumCols();
106  std::vector<int32> copy_from_idx_vec;
107 
108  for (int32 i = 0; i < n_columns; i++) {
109  copy_from_idx_vec.push_back(Rand() % n_columns);
110  }
111  copy_from_idx.CopyFromVec(copy_from_idx_vec);
112  cu::Copy(src, copy_from_idx, &tgt);
113 
114  for (int32 i = 0; i < n_rows; i++) {
115  for (int32 j = 0; j < n_columns; j++) {
116  Real src_val = src(i, copy_from_idx_vec.at(j));
117  Real tgt_val = tgt(i, j);
118  AssertEqual(src_val, tgt_val);
119  }
120  }
121 }
void CopyFromVec(const std::vector< T > &src)
This function resizes if needed.
Definition: cu-array-inl.h:120
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void Copy(const CuMatrixBase< Real > &src, const CuArray< int32 > &copy_from_indices, CuMatrixBase< Real > *tgt)
Copies elements from src into tgt as given by copy_from_indices.
Definition: cu-math.cc:173

◆ UnitTestCuMathNormalizePerRow()

static void kaldi::UnitTestCuMathNormalizePerRow ( )
static

Definition at line 479 of file cu-math-test.cc.

References AssertEqual(), MatrixBase< Real >::CopyColFromVec(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), MatrixBase< Real >::Data(), Timer::Elapsed(), rnnlm::i, KALDI_LOG, kNoTrans, kaldi::cu::NormalizePerRow(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

479  {
480 
481  for (int32 i = 0; i < 2; i++) {
482  int row = 10 + Rand() % 40;
483  int col = 10 + Rand() % 50;
484 
485  Matrix<Real> Hi(row,col);
486  Matrix<Real> Ho(row,col+1);
487  Hi.SetRandn();
488  Hi.Scale(5.0);
489 
490  CuMatrix<Real> Di(row, col);
491  CuMatrix<Real> Do(row, col+1);
492  Di.CopyFromMat(Hi);
493 
494  Real target_rms = 0.3456;
495  bool add_log_stddev = true;
496  const Real kSquaredNormFloor = 1.35525271560688e-20; // 2^-66
497 
498  //gpu
499  cu::NormalizePerRow(Di, target_rms, add_log_stddev, &Do);
500 
501  //cpu
502  {
503  MatrixBase<Real>& in(Hi);
504  MatrixBase<Real>& out(Ho);
505  Real target_rms=0.3456;
506  SubMatrix<Real> out_no_log(out, 0, out.NumRows(), 0, in.NumCols());
507  if (in.Data() != out_no_log.Data())
508  out_no_log.CopyFromMat(in);
509  Vector<Real> in_norm(in.NumRows());
510  Real d_scaled = in.NumCols() * target_rms * target_rms;
511  in_norm.AddDiagMat2(1.0 / d_scaled, in, kNoTrans, 0.0);
512  in_norm.ApplyFloor(kSquaredNormFloor);
513  in_norm.ApplyPow(-0.5);
514  out_no_log.MulRowsVec(in_norm);
515  if (add_log_stddev) {
516  in_norm.ApplyLog();
517  in_norm.Scale(-1.0);
518  in_norm.Add(log(target_rms));
519  out.CopyColFromVec(in_norm, in.NumCols());
520  }
521  }
522 
523  Matrix<Real> Ho2(Do);
524  AssertEqual(Ho,Ho2,0.00001);
525  }
526 
527  for (int dim = 16; dim <= 1024; dim *= 2) {
528  BaseFloat time_in_secs = 0.025;
529  CuMatrix<Real> M(dim, dim), N(dim, dim + 1);
530  M.SetRandn();
531  N.SetRandn();
532  Timer tim;
533  int32 iter = 0;
534  for (; tim.Elapsed() < time_in_secs; iter++) {
535  cu::NormalizePerRow(M, Real(1), true, &N);
536  }
537 
538  BaseFloat gflops = ((BaseFloat) dim * dim * iter)
539  / (tim.Elapsed() * 1.0e+09);
540  KALDI_LOG << "For CuMath::NormalizePerRow"
541  << (sizeof(Real)==8?"<double>":"<float>") << ", for dim = "
542  << dim << ", speed was " << gflops << " gigaflops.";
543  if (tim.Elapsed() > 0.05)
544  break;
545  }
546 }
Base class which provides matrix operations not involving resizing or allocation. ...
Definition: kaldi-matrix.h:49
void AddDiagMat2(Real alpha, const MatrixBase< Real > &M, MatrixTransposeType trans=kNoTrans, Real beta=1.0)
Add the diagonal of a matrix times itself: *this = diag(M M^T) + beta * *this (if trans == kNoTrans)...
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void NormalizePerRow(const CuMatrixBase< Real > &in, const Real target_rms, const bool add_log_stddev, CuMatrixBase< Real > *out)
Normalize nonlinearity modifies the vector of activations by scaling it so that the root-mean-square ...
Definition: cu-math.cc:280
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
Sub-matrix representation.
Definition: kaldi-matrix.h:988

◆ UnitTestCuMathNormalizePerRow_v2()

static void kaldi::UnitTestCuMathNormalizePerRow_v2 ( )
static

Definition at line 550 of file cu-math-test.cc.

References MatrixBase< Real >::ApplyFloor(), AssertEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), kNoTrans, MatrixBase< Real >::MulRowsVec(), kaldi::cu::NormalizePerRow(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), MatrixBase< Real >::Scale(), and MatrixBase< Real >::SetRandn().

550  {
551 
552  int row = 128;
553  int col = 1024;
554 
555  Matrix<Real> Hi(row,col);
556  Matrix<Real> Ho(row,col);
557  Hi.SetRandn();
558  Hi.Scale(5.0);
559  Hi.ApplyFloor(0.0); // like ReLU,
560 
561  CuMatrix<Real> Di(row, col);
562  CuMatrix<Real> Do(row, col);
563  Di.CopyFromMat(Hi);
564 
565  Real target_rms = 0.3456;
566  bool add_log_stddev = false;
567  const Real kSquaredNormFloor = 1.35525271560688e-20; // 2^-66
568 
569  //gpu
570  cu::NormalizePerRow(Di, target_rms, add_log_stddev, &Do);
571 
572  //cpu
573  {
574  MatrixBase<Real>& in(Hi);
575  MatrixBase<Real>& out(Ho);
576  Real target_rms=0.3456;
577  Vector<Real> in_norm(in.NumRows());
578  Real d_scaled = in.NumCols() * target_rms * target_rms;
579  in_norm.AddDiagMat2(1.0 / d_scaled, in, kNoTrans, 0.0);
580  in_norm.ApplyFloor(kSquaredNormFloor);
581  in_norm.ApplyPow(-0.5);
582  out.CopyFromMat(in);
583  out.MulRowsVec(in_norm);
584  }
585 
586  Matrix<Real> Ho2(Do);
587  // here the BUG was detected (by processing big-enough matrix),
588  AssertEqual(Ho,Ho2,0.00001);
589 }
Base class which provides matrix operations not involving resizing or allocation. ...
Definition: kaldi-matrix.h:49
void AddDiagMat2(Real alpha, const MatrixBase< Real > &M, MatrixTransposeType trans=kNoTrans, Real beta=1.0)
Add the diagonal of a matrix times itself: *this = diag(M M^T) + beta * *this (if trans == kNoTrans)...
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void NormalizePerRow(const CuMatrixBase< Real > &in, const Real target_rms, const bool add_log_stddev, CuMatrixBase< Real > *out)
Normalize nonlinearity modifies the vector of activations by scaling it so that the root-mean-square ...
Definition: cu-math.cc:280

◆ UnitTestCuMathRandomize()

static void kaldi::UnitTestCuMathRandomize ( )
static

Definition at line 46 of file cu-math-test.cc.

References AssertEqual(), CuArray< T >::CopyFromVec(), rnnlm::i, rnnlm::j, CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), Rand(), kaldi::cu::Randomize(), and CuMatrixBase< Real >::SetRandn().

46  {
47  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
48  CuMatrix<Real> src(M, N);
49  CuMatrix<Real> tgt(M, N);
50  CuArray<int32> copy_from_idx;
51 
52  src.SetRandn();
53  int32 n_rows = src.NumRows();
54  int32 n_columns = src.NumCols();
55  std::vector<int32> copy_from_idx_vec;
56 
57  for (int32 i = 0; i < n_rows; i++) {
58  copy_from_idx_vec.push_back(Rand() % n_rows);
59  }
60  copy_from_idx.CopyFromVec(copy_from_idx_vec);
61  cu::Randomize(src, copy_from_idx, &tgt);
62 
63  for (int32 i = 0; i < n_rows; i++) {
64  for (int32 j = 0; j < n_columns; j++) {
65  Real src_val = src(copy_from_idx_vec.at(i), j);
66  Real tgt_val = tgt(i, j);
67  AssertEqual(src_val, tgt_val);
68  }
69  }
70 }
void CopyFromVec(const std::vector< T > &src)
This function resizes if needed.
Definition: cu-array-inl.h:120
void Randomize(const CuMatrixBase< Real > &src, const CuArray< int32 > &copy_from_idx, CuMatrixBase< Real > *tgt)
Copies a permutation of src into tgt.
Definition: cu-math.cc:80
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuMathSplice()

static void kaldi::UnitTestCuMathSplice ( )
static

Definition at line 124 of file cu-math-test.cc.

References AssertEqual(), CuArray< T >::CopyFromVec(), rnnlm::i, rnnlm::j, CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), Rand(), CuMatrixBase< Real >::SetRandn(), and kaldi::cu::Splice().

124  {
125  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
126  CuMatrix<Real> src(M, N);
127  CuArray<int32> frame_offsets;
128 
129  src.SetRandn();
130  int32 n_rows = src.NumRows();
131  int32 n_columns = src.NumCols();
132  std::vector<int32> frame_offsets_vec;
133 
134  // The number of columns of tgt is rows(src)
135  // times n_frame_offsets, so we keep n_frame_offsets
136  // reasonably small (2 <= n <= 6).
137  int32 n_frame_offsets = Rand() % 7 + 2;
138  for (int32 i = 0; i < n_frame_offsets; i++) {
139  frame_offsets_vec.push_back(Rand() % 2 * n_columns - n_columns);
140  }
141 
142  CuMatrix<Real> tgt(M, N * n_frame_offsets);
143  frame_offsets.CopyFromVec(frame_offsets_vec);
144  cu::Splice(src, frame_offsets, &tgt);
145 
146  Matrix<Real> src_copy(src), tgt_copy(tgt);
147  for (int32 i = 0; i < n_rows; i++) {
148  for (int32 k = 0; k < n_frame_offsets; k++) {
149  for (int32 j = 0; j < n_columns; j++) {
150  Real src_val;
151  if (i + frame_offsets_vec.at(k) >= n_rows) {
152  src_val = src_copy(n_rows-1, j);
153  } else if (i + frame_offsets_vec.at(k) <= 0) {
154  src_val = src_copy(0, j);
155  } else {
156  src_val = src_copy(i + frame_offsets_vec.at(k), j);
157  }
158  Real tgt_val = tgt_copy(i, k * n_columns + j);
159  AssertEqual(src_val, tgt_val);
160  }
161  }
162  }
163 }
void CopyFromVec(const std::vector< T > &src)
This function resizes if needed.
Definition: cu-array-inl.h:120
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void Splice(const CuMatrixBase< Real > &src, const CuArray< int32 > &frame_offsets, CuMatrixBase< Real > *tgt)
Splice concatenates frames of src as specified in frame_offsets into tgt.
Definition: cu-math.cc:132
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuMatrixAdd()

static void kaldi::UnitTestCuMatrixAdd ( )
static

Definition at line 254 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::Add(), MatrixBase< Real >::Add(), ApproxEqual(), KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

254  {
255  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
256  Matrix<Real> H(M, N);
257  H.SetRandn();
258 
259  BaseFloat offset = -1 + (0.33 * (Rand() % 5));
260  CuMatrix<Real> D(H);
261  D.Add(offset);
262  H.Add(offset);
263  Matrix<Real> E(D);
264 
265  KALDI_ASSERT(ApproxEqual(H, E));
266 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAdd2()

static void kaldi::UnitTestCuMatrixAdd2 ( )
static

Definition at line 1803 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::Add(), MatrixBase< Real >::Add(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, and Rand().

1803  {
1804  for (int32 i = 0; i < 10; i++) {
1805  int32 dimM = 100 + Rand() % 200, dimN = 100 + Rand() % 200;
1806  Matrix<Real> M(dimM, dimN);
1807  CuMatrix<Real> Mc(M);
1808  Real alpha = 5.5;
1809  M.Add(alpha);
1810  Mc.Add(alpha);
1811  Matrix<Real> M2(Mc);
1812  KALDI_ASSERT(ApproxEqual(M, M2));
1813  }
1814 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddCols()

static void kaldi::UnitTestCuMatrixAddCols ( )
static

Definition at line 886 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and CuMatrixBase< Real >::SetRandn().

886  {
887  for (int32 p = 0; p < 2; p++) {
888  MatrixIndexT num_cols1 = 10 + Rand() % 10,
889  num_cols2 = 10 + Rand() % 10,
890  num_rows = 10 + Rand() % 10;
891  CuMatrix<Real> M(num_rows, num_cols1);
892  M.SetRandn();
893 
894  CuMatrix<Real> N(num_rows, num_cols2), O(num_rows, num_cols2);
895  std::vector<int32> reorder(num_cols2);
896  for (int32 i = 0; i < num_cols2; i++)
897  reorder[i] = -1 + (Rand() % (num_cols1 + 1));
898 
899  CuArray<int32> reorder_gpu(reorder);
900  N.AddCols(M, reorder_gpu);
901 
902  for (int32 i = 0; i < num_rows; i++)
903  for (int32 j = 0; j < num_cols2; j++)
904  if (reorder[j] < 0) O(i, j) = 0;
905  else O(i, j) = M(i, reorder[j]);
906  KALDI_ASSERT(ApproxEqual(N, O));
907  }
908 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddDiagVecMat()

static void kaldi::UnitTestCuMatrixAddDiagVecMat ( )
static

Definition at line 1236 of file cu-matrix-test.cc.

References CuVectorBase< Real >::AddVec(), ApproxEqual(), CuVectorBase< Real >::CopyColFromMat(), CuVectorBase< Real >::CopyFromVec(), KALDI_ASSERT, kNoTrans, kTrans, Rand(), CuMatrixBase< Real >::Row(), CuVectorBase< Real >::Scale(), CuVectorBase< Real >::SetRandn(), CuMatrixBase< Real >::SetRandn(), CuVectorBase< Real >::Sum(), CuMatrixBase< Real >::Sum(), and CuMatrix< Real >::Transpose().

1236  {
1237  for (int p = 0; p < 4; p++) {
1238  MatrixIndexT dimM = 100 + Rand() % 255, dimN = 100 + Rand() % 255;
1239  //MatrixIndexT dimM = 10 + Rand() % 2, dimN = 10 + Rand() % 2;
1240  Real alpha = 0.43243, beta = 1.423;
1241  CuMatrix<Real> M(dimM, dimN), N(dimM, dimN);
1242  M.SetRandn();
1243  N.SetRandn();
1244  MatrixTransposeType trans = (p % 2 == 0 ? kNoTrans : kTrans);
1245  if (trans == kTrans)
1246  N.Transpose();
1247 
1248  KALDI_ASSERT(M.Sum() != 0.0);
1249  KALDI_ASSERT(N.Sum() != 0.0);
1250 
1251  CuVector<Real> V(dimM);
1252  V.SetRandn();
1253 
1254  KALDI_ASSERT(V.Sum() != 0.0);
1255 
1256  CuMatrix<Real> Mcheck(M);
1257 
1258  for (int32 r = 0; r < dimM; r++) {
1259  CuSubVector<Real> Mcheckrow(Mcheck, r);
1260  CuVector<Real> Nrow(dimN);
1261  if (trans == kTrans) Nrow.CopyColFromMat(N, r);
1262  else Nrow.CopyFromVec(N.Row(r));
1263  Mcheckrow.Scale(beta);
1264  Mcheckrow.AddVec(alpha * V(r), Nrow);
1265  }
1266 
1267  M.AddDiagVecMat(alpha, V, N, trans, beta);
1268  KALDI_ASSERT(ApproxEqual(M, Mcheck));
1269  KALDI_ASSERT(M.Sum() != 0.0);
1270  }
1271 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddElements()

static void kaldi::UnitTestCuMatrixAddElements ( )
static

Definition at line 2822 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddElements(), ApproxEqual(), Int32Pair::first, rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), Int32Pair::second, and CuMatrixBase< Real >::SetRandn().

2822  {
2823  for (int32 i = 0; i < 2; i++) {
2824  int32 dimM = 100 + Rand() % 50, dimN = 100 + Rand() % 50;
2825  // int32 dimM = 256, dimN = 256;
2826  CuMatrix<Real> H(dimM, dimN);
2827  H.SetRandn();
2828  CuMatrix<Real> H_copy(H);
2829  CuMatrix<Real> M(H);
2830  int32 num_elements = 100 + Rand() % 10;
2831  std::vector<MatrixElement<Real> > input;
2832  std::set<Int32Pair> input_index; //Set used to ensure unique elements
2833  std::vector<Int32Pair> input_index_v;
2834  Real *input_value = new Real[num_elements];
2835  BaseFloat scale = -1 + (0.33 * (Rand() % 5));
2836  for (int32 j = 0; j < num_elements; j++) {
2837  Int32Pair tmp_pair;
2838  // Generate a unique random index
2839  do {
2840  tmp_pair.first = Rand() % dimM;
2841  tmp_pair.second = Rand() % dimN;
2842  } while (input_index.find(tmp_pair)!=input_index.end());
2843  input_index.insert(tmp_pair);
2844 
2845  MatrixIndexT r = tmp_pair.first;
2846  MatrixIndexT c = tmp_pair.second;
2847  input_index_v.push_back(tmp_pair);
2848 
2849  Real offset = -1 + (0.33 * (Rand() % 5));
2850  M(r, c) += scale * offset;
2851  MatrixElement<Real> t = {r, c, offset};
2852  input.push_back(t);
2853  input_value[j] = offset;
2854  }
2855 
2856  H.AddElements(scale, input);
2857  CuArray<Int32Pair> cu_input_index(input_index_v);
2858  H_copy.AddElements(scale, cu_input_index, input_value);
2859  delete[] input_value;
2860 
2861  KALDI_ASSERT(ApproxEqual(H, M));
2862  KALDI_ASSERT(ApproxEqual(H_copy, M));
2863  }
2864 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32_cuda second
Definition: cu-matrixdim.h:80
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32_cuda first
Definition: cu-matrixdim.h:79

◆ UnitTestCuMatrixAddMat()

static void kaldi::UnitTestCuMatrixAddMat ( )
static

Definition at line 1367 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMat(), MatrixBase< Real >::AddMat(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), rnnlm::i, KALDI_ASSERT, kSetZero, kTrans, Rand(), CuMatrixBase< Real >::Range(), and MatrixBase< Real >::SetRandn().

1367  {
1368  Matrix<Real> Ha(100,100);
1369  Matrix<Real> Hb(100,100);
1370  Ha.SetRandn();
1371  Hb.SetRandn();
1372 
1373  CuMatrix<Real> Da(100,100);
1374  CuMatrix<Real> Db(100,100);
1375  Da.CopyFromMat(Ha);
1376  Db.CopyFromMat(Hb);
1377 
1378  Da.AddMat(0.5,Db);
1379  Ha.AddMat(0.5,Hb);
1380 
1381  Matrix<Real> Ha2(100,100);
1382  Da.CopyToMat(&Ha2);
1383 
1384  KALDI_ASSERT(ApproxEqual(Ha,Ha2));
1385 
1386  //check use with submatrix
1387  CuMatrix<Real> mat1(10,10,kSetZero);
1388  mat1.AddMat(1.0,Da.Range(5,10,12,10)); //different stride for mat1,mat2
1389  CuMatrix<Real> mat2(Da.Range(5,10,12,10));
1390  KALDI_ASSERT(ApproxEqual(mat1,mat2));
1391 
1392  for (int i = 0; i < 10; i++) {
1393  int32 N = 5 * (10 + Rand() % 10), M = 100 + Rand() % 50;
1394  Matrix<Real> Hc(N,M);
1395  Matrix<Real> Hd(M,N);
1396  Hc.SetRandn();
1397  Hd.SetRandn();
1398 
1399  CuMatrix<Real> Dc(N,M);
1400  CuMatrix<Real> Dd(M,N);
1401  Dc.CopyFromMat(Hc);
1402  Dd.CopyFromMat(Hd);
1403 
1404  Real alpha = 0.5;
1405  Dc.AddMat(alpha,Dd,kTrans);
1406  Hc.AddMat(alpha,Hd,kTrans);
1407 
1408  Matrix<Real> Hc2(N,M);
1409  Dc.CopyToMat(&Hc2);
1410  KALDI_ASSERT(ApproxEqual(Hc,Hc2));
1411 
1412  // check use with submatrix
1413  CuMatrix<Real> mat3(N/5,M,kSetZero);
1414  mat3.AddMat(1.0, Dd.Range(0,M,0,N/5),kTrans);
1415 
1416  CuMatrix<Real> mat4(Dd.Range(0,M,0,N/5),kTrans);
1417  KALDI_ASSERT(ApproxEqual(mat3,mat4));
1418  }
1419 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddMatBlocks1()

static void kaldi::UnitTestCuMatrixAddMatBlocks1 ( )
static

Definition at line 1425 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMat(), CuMatrixBase< Real >::AddMatBlocks(), ApproxEqual(), KALDI_ASSERT, RandInt(), and CuMatrixBase< Real >::SetRandn().

1425  {
1426  for (int32 l = 0; l < 5; l++) {
1427  int32 num_row_blocks = RandInt(1, 10), num_col_blocks = RandInt(1, 20);
1428  int32 block_rows = RandInt(1, 100), block_cols = RandInt(1, 100);
1429  BaseFloat alpha = RandInt(3, 10);
1430  CuMatrix<Real> dst(block_rows, block_cols);
1431  dst.SetRandn();
1432  CuMatrix<Real> src(num_row_blocks * block_rows,
1433  num_col_blocks * block_cols);
1434  src.SetRandn();
1435 
1436  CuMatrix<Real> dst_copy(dst);
1437  for (int32 rb = 0; rb < num_row_blocks; rb++) {
1438  for (int32 cb = 0; cb < num_col_blocks; cb++) {
1439  CuSubMatrix<Real> src_part(src,
1440  rb * block_rows, block_rows,
1441  cb * block_cols, block_cols);
1442  dst_copy.AddMat(alpha, src_part);
1443  }
1444  }
1445  dst.AddMatBlocks(alpha, src);
1446  KALDI_ASSERT(ApproxEqual(dst, dst_copy));
1447  }
1448 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
This class is used for a piece of a CuMatrix.
Definition: matrix-common.h:70
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestCuMatrixAddMatBlocks1Trans()

static void kaldi::UnitTestCuMatrixAddMatBlocks1Trans ( )
static

Definition at line 1452 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMat(), CuMatrixBase< Real >::AddMatBlocks(), ApproxEqual(), KALDI_ASSERT, kTrans, RandInt(), and CuMatrixBase< Real >::SetRandn().

1452  {
1453  for (int32 l = 0; l < 5; l++) {
1454  int32 num_row_blocks = RandInt(1, 10), num_col_blocks = RandInt(1, 20);
1455  int32 block_rows = RandInt(1, 100), block_cols = RandInt(1, 100);
1456  BaseFloat alpha = RandInt(3, 10);
1457  CuMatrix<Real> dst(block_cols, block_rows);
1458  dst.SetRandn();
1459  CuMatrix<Real> src(num_row_blocks * block_rows,
1460  num_col_blocks * block_cols);
1461  src.SetRandn();
1462 
1463  CuMatrix<Real> dst_copy(dst);
1464  for (int32 rb = 0; rb < num_row_blocks; rb++) {
1465  for (int32 cb = 0; cb < num_col_blocks; cb++) {
1466  CuSubMatrix<Real> src_part(src,
1467  rb * block_rows, block_rows,
1468  cb * block_cols, block_cols);
1469  dst_copy.AddMat(alpha, src_part, kTrans);
1470  }
1471  }
1472  dst.AddMatBlocks(alpha, src, kTrans);
1473  KALDI_ASSERT(ApproxEqual(dst, dst_copy));
1474  }
1475 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
This class is used for a piece of a CuMatrix.
Definition: matrix-common.h:70
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestCuMatrixAddMatBlocks2()

static void kaldi::UnitTestCuMatrixAddMatBlocks2 ( )
static

Definition at line 1482 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMat(), CuMatrixBase< Real >::AddMatBlocks(), ApproxEqual(), KALDI_ASSERT, RandInt(), and CuMatrixBase< Real >::SetRandn().

1482  {
1483  for (int32 l = 0; l < 5; l++) {
1484  int32 num_row_blocks = RandInt(1, 10), num_col_blocks = RandInt(1, 20);
1485  int32 block_rows = RandInt(1, 100), block_cols = RandInt(1, 100);
1486  BaseFloat alpha = RandInt(3, 10);
1487  CuMatrix<Real> src(block_rows, block_cols);
1488  src.SetRandn();
1489  CuMatrix<Real> dst(num_row_blocks * block_rows,
1490  num_col_blocks * block_cols);
1491  src.SetRandn();
1492 
1493  CuMatrix<Real> dst_copy(dst);
1494  for (int32 rb = 0; rb < num_row_blocks; rb++) {
1495  for (int32 cb = 0; cb < num_col_blocks; cb++) {
1496  CuSubMatrix<Real> dst_copy_part(dst_copy,
1497  rb * block_rows, block_rows,
1498  cb * block_cols, block_cols);
1499  dst_copy_part.AddMat(alpha, src);
1500  }
1501  }
1502  dst.AddMatBlocks(alpha, src);
1503  KALDI_ASSERT(ApproxEqual(dst, dst_copy));
1504  }
1505 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
This class is used for a piece of a CuMatrix.
Definition: matrix-common.h:70
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestCuMatrixAddMatDiagVec()

static void kaldi::UnitTestCuMatrixAddMatDiagVec ( )
static

Definition at line 1273 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMat(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), KALDI_ASSERT, kNoTrans, kTrans, CuMatrixBase< Real >::MulColsVec(), Rand(), CuMatrixBase< Real >::Scale(), and CuVectorBase< Real >::SetRandn().

1273  {
1274  // M <- alpha * N[^T] * diag(v) + beta * M
1275  for (int p = 0; p < 2; p++) {
1276  MatrixIndexT dimM = 100 + Rand() % 255, dimN = 100 + Rand() % 255;
1277  Real alpha = 0.43243, beta = 1.423;
1278 
1279  CuMatrix<Real> M(dimM, dimN), N(dimM, dimN), buf(dimM, dimN);
1280  M.SetRandn();
1281  N.SetRandn();
1282  buf.CopyFromMat(N);
1283  MatrixTransposeType trans = (p % 2 == 0 ? kNoTrans : kTrans);
1284  if (trans == kTrans)
1285  N.Transpose();
1286 
1287  CuVector<Real> V(dimN);
1288  V.SetRandn();
1289 
1290  CuMatrix<Real> Mcheck(M);
1291  Mcheck.Scale(beta);
1292  buf.MulColsVec(V);
1293  Mcheck.AddMat(alpha, buf, kNoTrans);
1294 
1295  M.AddMatDiagVec(alpha, N, trans, V, beta);
1296  KALDI_ASSERT(ApproxEqual(M, Mcheck));
1297  KALDI_ASSERT(M.Sum() != 0.0);
1298  }
1299 }
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddMatMat()

static void kaldi::UnitTestCuMatrixAddMatMat ( )
static

Definition at line 1660 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddMatMat(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, kNoTrans, kTrans, and MatrixBase< Real >::SetRandn().

1660  {
1661  Matrix<Real> Ha(200,100);
1662  Matrix<Real> Hb(100,200);
1663  Matrix<Real> Hc1(200,200);
1664  Matrix<Real> Hc2(100,100);
1665  Ha.SetRandn();
1666  Hb.SetRandn();
1667 
1668  CuMatrix<Real> Da(200,100);
1669  CuMatrix<Real> Db(100,200);
1670  Da.CopyFromMat(Ha);
1671  Db.CopyFromMat(Hb);
1672  CuMatrix<Real> Dc1(200,200);
1673  CuMatrix<Real> Dc2(100,100);
1674 
1675  Dc1.AddMatMat(0.5f,Da,kNoTrans,Db,kNoTrans,0.0f);
1676  Dc2.AddMatMat(0.5f,Da,kTrans,Db,kTrans,0.0f);
1677  Hc1.AddMatMat(0.5f,Ha,kNoTrans,Hb,kNoTrans,0.0f);
1678  Hc2.AddMatMat(0.5f,Ha,kTrans,Hb,kTrans,0.0f);
1679 
1680  Matrix<Real> Hc1a(200,200);
1681  Matrix<Real> Hc2a(100,100);
1682  Dc1.CopyToMat(&Hc1a);
1683  Dc2.CopyToMat(&Hc2a);
1684 
1685  KALDI_ASSERT(ApproxEqual(Hc1,Hc1a));
1686  KALDI_ASSERT(ApproxEqual(Hc2,Hc2a));
1687 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddMatMatBatched()

static void kaldi::UnitTestCuMatrixAddMatMatBatched ( )
static

Definition at line 1715 of file cu-matrix-test.cc.

References AddMatMatBatched(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, and MatrixBase< Real >::SetRandn().

1715  {
1716  // Random stride is disabled as AddMatMatBatched requires consistent stride
1717 #if HAVE_CUDA == 1
1718  bool old_mode = CuDevice::Instantiate().SetDebugStrideMode(false);
1719 #endif
1720  const int32 batchCount = 10;
1721  std::vector<Matrix<Real>* > Ha(batchCount), Hb(batchCount), Hc1(batchCount), Hc2(batchCount);
1722  std::vector<CuMatrix<Real>* > Da(batchCount), Db(batchCount), Dc1(batchCount), Dc2(batchCount);
1723  std::vector<SubMatrix<Real>* > HA, HB, HC1, HC2;
1724  std::vector<CuSubMatrix<Real>* > DA, DB, DC1, DC2;
1725 
1726  for (int32 i = 0; i < batchCount; i++) {
1727  // first create a Matrix intance and then creat a SubMatrix instance from that
1728  Ha[i] = new Matrix<Real>(200, 100);
1729  Hb[i] = new Matrix<Real>(100, 200);
1730  Hc1[i] = new Matrix<Real>(200, 200);
1731  Hc2[i] = new Matrix<Real>(100, 100);
1732  Ha[i]->SetRandn();
1733  Hb[i]->SetRandn();
1734  HA.push_back(new SubMatrix<Real>(*(Ha[i]), 0, Ha[i]->NumRows(), 0,
1735  Ha[i]->NumCols()));
1736  HB.push_back(new SubMatrix<Real>(*(Hb[i]), 0, Hb[i]->NumRows(), 0,
1737  Hb[i]->NumCols()));
1738  HC1.push_back(new SubMatrix<Real>(*(Hc1[i]), 0, Hc1[i]->NumRows(), 0,
1739  Hc1[i]->NumCols()));
1740  HC2.push_back(new SubMatrix<Real>(*(Hc2[i]), 0, Hc2[i]->NumRows(), 0,
1741  Hc2[i]->NumCols()));
1742 
1743  // first create a CuMatrix intance and then creat a CuSubMatrix instance from that
1744  Da[i] = new CuMatrix<Real>(200, 100);
1745  Db[i] = new CuMatrix<Real>(100, 200);
1746  Dc1[i] = new CuMatrix<Real>(200, 200);
1747  Dc2[i] = new CuMatrix<Real>(100, 100);
1748  Da[i]->CopyFromMat(*(Ha[i]));
1749  Db[i]->CopyFromMat(*(Hb[i]));
1750  DA.push_back(new CuSubMatrix<Real>(*(Da[i]), 0, Da[i]->NumRows(), 0,
1751  Da[i]->NumCols()));
1752  DB.push_back(new CuSubMatrix<Real>(*(Db[i]), 0, Db[i]->NumRows(), 0,
1753  Db[i]->NumCols()));
1754  DC1.push_back(new CuSubMatrix<Real>(*(Dc1[i]), 0, Dc1[i]->NumRows(), 0,
1755  Dc1[i]->NumCols()));
1756  DC2.push_back(new CuSubMatrix<Real>(*(Dc2[i]), 0, Dc2[i]->NumRows(), 0,
1757  Dc2[i]->NumCols()));
1758  }
1759 
1760  AddMatMatBatched(static_cast<Real>(0.5f), DC1, DA, kNoTrans, DB, kNoTrans,
1761  static_cast<Real>(0.0f));
1762  AddMatMatBatched(static_cast<Real>(0.5f), DC2, DA, kTrans, DB, kTrans,
1763  static_cast<Real>(0.0f));
1764 
1765  // used to store results from DC1 and DC2 for equality check
1766  Matrix<Real> Hca1(200,200);
1767  Matrix<Real> Hca2(100,100);
1768 
1769  // equality check
1770  for (int32 i = 0; i< batchCount; i++) {
1771  (*HC1[i]).AddMatMat(0.5f, *(HA[i]), kNoTrans, *(HB[i]), kNoTrans, 0.0f);
1772  (*HC2[i]).AddMatMat(0.5f, *(HA[i]), kTrans, *(HB[i]), kTrans, 0.0f);
1773  DC1[i]->CopyToMat(&Hca1);
1774  DC2[i]->CopyToMat(&Hca2);
1775  KALDI_ASSERT(ApproxEqual(*(HC1[i]), Hca1));
1776  KALDI_ASSERT(ApproxEqual(*(HC2[i]), Hca2));
1777  delete Ha[i]; delete Hb[i]; delete Hc1[i]; delete Hc2[i];
1778  delete HA[i]; delete HB[i]; delete HC1[i]; delete HC2[i];
1779  delete Da[i]; delete Db[i]; delete Dc1[i]; delete Dc2[i];
1780  delete DA[i]; delete DB[i]; delete DC1[i]; delete DC2[i];
1781  }
1782 #if HAVE_CUDA == 1
1783  CuDevice::Instantiate().SetDebugStrideMode(old_mode);
1784 #endif
1785 }
void CopyFromMat(const MatrixBase< OtherReal > &src, MatrixTransposeType trans=kNoTrans)
Definition: cu-matrix.cc:344
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
void AddMatMatBatched(const Real alpha, std::vector< CuSubMatrix< Real > * > &C, const std::vector< CuSubMatrix< Real > * > &A, MatrixTransposeType transA, const std::vector< CuSubMatrix< Real > * > &B, MatrixTransposeType transB, const Real beta)
Does multiple matrix multiplications, executing them in parallel using cuBLAS&#39;s gemmBatched if we are...
Definition: cu-matrix.cc:2207
void SetRandn()
Sets to random values of a normal distribution.
This class is used for a piece of a CuMatrix.
Definition: matrix-common.h:70
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Sub-matrix representation.
Definition: kaldi-matrix.h:988
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddMatMatElements()

static void kaldi::UnitTestCuMatrixAddMatMatElements ( )
static

Definition at line 1301 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMat(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), KALDI_ASSERT, kNoTrans, CuMatrixBase< Real >::MulElements(), Rand(), and CuMatrixBase< Real >::Scale().

1301  {
1302  // M <- alpha *(A .* B) + beta * M
1303  MatrixIndexT dimM = 100 + Rand() % 255, dimN = 100 + Rand() % 255;
1304  Real alpha = 0.43243, beta = 1.423;
1305  CuMatrix<Real> M(dimM, dimN), A(dimM, dimN), B(dimM, dimN), buf(dimM, dimN);
1306  M.SetRandn();
1307  A.SetRandn();
1308  B.SetRandn();
1309 
1310  CuMatrix<Real> Mcheck(M);
1311  buf.CopyFromMat(A); buf.MulElements(B);
1312  Mcheck.Scale(beta); Mcheck.AddMat(alpha, buf, kNoTrans);
1313 
1314  M.AddMatMatElements(alpha, A, B, beta);
1315  KALDI_ASSERT(ApproxEqual(M, Mcheck));
1316  KALDI_ASSERT(M.Sum() != 0.0);
1317 }
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddMatTp()

static void kaldi::UnitTestCuMatrixAddMatTp ( )
static

Definition at line 1849 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMatTp(), MatrixBase< Real >::AddMatTp(), rnnlm::i, KALDI_ASSERT, kNoTrans, Rand(), PackedMatrix< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

1849  {
1850  for (int32 i = 1; i < 10; i++) {
1851  MatrixIndexT dim = 5 * i + Rand() % 10;
1852 
1853  Matrix<Real> A(dim, dim);
1854  Matrix<Real> B(dim, dim);
1855  TpMatrix<Real> C(dim);
1856  A.SetRandn();
1857  B.SetRandn();
1858  C.SetRandn();
1859  CuMatrix<Real> D(A);
1860  CuMatrix<Real> E(B);
1861  CuTpMatrix<Real> F(C);
1862 
1863  A.AddMatTp(1.0, B, kNoTrans, C, kNoTrans, 1.0);
1864  D.AddMatTp(1.0, E, kNoTrans, F, kNoTrans, 1.0);
1865 
1866  CuMatrix<Real> G(A);
1867  KALDI_ASSERT(ApproxEqual<Real>(G, D));
1868  }
1869 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixAddRowRanges()

static void kaldi::UnitTestCuMatrixAddRowRanges ( )
static

Definition at line 713 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddRowRanges(), ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

713  {
714  for (int32 p = 0; p < 10; p++) {
715  MatrixIndexT num_rows1 = 10 + Rand() % 10,
716  num_rows2 = 10 + Rand() % 10,
717  num_cols = 10 + Rand() % 10;
718  Matrix<Real> src(num_rows1, num_cols); src.SetRandn();
719  Matrix<Real> dst(num_rows2, num_cols); dst.SetRandn();
720 
721  // Computes the indexes.
722  std::vector<Int32Pair> indexes(num_rows2);
723  for (MatrixIndexT i = 0; i < num_rows2; i++) {
724  indexes[i].first = Rand() % num_rows1;
725  int32 headroom = num_rows1 - indexes[i].first,
726  size = (Rand() % headroom) + 1;
727  indexes[i].second = indexes[i].first + size;
728  KALDI_ASSERT(indexes[i].second >= indexes[i].first &&
729  indexes[i].second <= num_rows1 &&
730  indexes[i].first >= 0);
731  }
732  // Computes reference matrix.
733  Matrix<Real> dst1(dst);
734  for (MatrixIndexT i = 0; i < num_rows2; i++) {
735  int32 start = indexes[i].first, end = indexes[i].second;
736  for (MatrixIndexT j = 0; j < num_cols; j++) {
737  for (MatrixIndexT i2 = start; i2 < end; i2++)
738  dst1(i, j) += src(i2, j);
739  }
740  }
741 
742  CuMatrix<Real> cu_src(src);
743  CuMatrix<Real> cu_dst(dst);
744  CuArray<Int32Pair> cu_indexes(indexes);
745  cu_dst.AddRowRanges(cu_src, cu_indexes);
746  Matrix<Real> dst2(cu_dst);
747  KALDI_ASSERT(ApproxEqual(dst1, dst2));
748  }
749 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddRows()

static void kaldi::UnitTestCuMatrixAddRows ( )
static

Definition at line 517 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), CuMatrixBase< Real >::RowData(), and CuMatrixBase< Real >::SetRandn().

517  {
518  for (int32 p = 0; p < 2; p++) {
519  MatrixIndexT num_rows1 = 10 + Rand() % 10,
520  num_rows2 = 10 + Rand() % 10,
521  num_cols = 10 + Rand() % 10;
522  CuMatrix<Real> M(num_rows1, num_cols);
523  M.SetRandn();
524 
525  CuMatrix<Real> N1(num_rows2, num_cols),
526  N2(num_rows2, num_cols), O(num_rows2, num_cols);
527  std::vector<int32> reorder(num_rows2);
528  std::vector<const Real*> reorder_src(num_rows2, NULL);
529  for (int32 i = 0; i < num_rows2; i++) {
530  reorder[i] = -1 + (Rand() % (num_rows1 + 1));
531  if (reorder[i] != -1)
532  reorder_src[i] = M.RowData(reorder[i]);
533  }
534 
535  Real alpha =
536  static_cast<Real>((Rand() % num_rows2)) / static_cast<Real>(num_rows1);
537 
538  CuArray<int32> reorder_cuda(reorder);
539  CuArray<const Real*> reorder_src_cuda(reorder_src);
540  N1.AddRows(alpha, M, reorder_cuda);
541  N2.AddRows(alpha, reorder_src_cuda);
542 
543  for (int32 i = 0; i < num_rows2; i++) {
544  if (reorder[i] != -1) {
545  for (int32 j = 0; j < num_cols; j++) {
546  O(i, j) += alpha * M(reorder[i], j);
547  }
548  }
549  }
550 
551  KALDI_ASSERT(ApproxEqual(N1, O));
552  KALDI_ASSERT(ApproxEqual(N2, O));
553  }
554 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddToDiag()

static void kaldi::UnitTestCuMatrixAddToDiag ( )
static

Definition at line 1789 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddToDiag(), MatrixBase< Real >::AddToDiag(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, and Rand().

1789  {
1790  for (int32 i = 0; i < 10; i++) {
1791  int32 dimM = 100 + Rand() % 200, dimN = 100 + Rand() % 200;
1792  Matrix<Real> M(dimM, dimN);
1793  CuMatrix<Real> Mc(M);
1794  Real alpha = 5.5;
1795  M.AddToDiag(alpha);
1796  Mc.AddToDiag(alpha);
1797  Matrix<Real> M2(Mc);
1798  KALDI_ASSERT(ApproxEqual(M, M2));
1799  }
1800 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddToElements()

static void kaldi::UnitTestCuMatrixAddToElements ( )
static

Definition at line 2867 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddToElements(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, Rand(), CuMatrixBase< Real >::SetRandn(), and WithProb().

2867  {
2868  for (int32 i = 0; i < 2; i++) {
2869  int32 NR = 100 + Rand() % 50, NC = 100 + Rand() % 50;
2870  CuMatrix<Real> A(NR, NC);
2871  A.SetRandn();
2872  CuMatrix<Real> A_copy(A);
2873  std::vector<int32> elements(NR, -1);
2874  BaseFloat alpha = -1 + (0.33 * (Rand() % 5));
2875  for (int32 r = 0; r < NR; r++) {
2876  MatrixIndexT c = Rand() % NC;
2877  if (WithProb(0.6)) {
2878  elements[r] = c;
2879  A(r, c) += alpha;
2880  }
2881  }
2882  CuArray<int32> cu_elements(elements);
2883  A_copy.AddToElements(alpha, cu_elements);
2884  KALDI_ASSERT(ApproxEqual(A_copy, A));
2885  }
2886 }
bool WithProb(BaseFloat prob, struct RandomState *state)
Definition: kaldi-math.cc:72
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddToRows()

static void kaldi::UnitTestCuMatrixAddToRows ( )
static

Definition at line 594 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddToRows(), ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and CuMatrixBase< Real >::SetRandn().

594  {
595  for (int32 p = 0; p < 2; p++) {
596  MatrixIndexT num_rows1 = 10 + Rand() % 10,
597  num_rows2 = 10 + Rand() % 10,
598  num_cols = 10 + Rand() % 10;
599  CuMatrix<Real> M(num_rows1, num_cols);
600  M.SetRandn();
601 
602  Real alpha =
603  static_cast<Real>((Rand() % num_rows2)) / static_cast<Real>(num_rows1);
604 
605  CuMatrix<Real> N1(num_rows2, num_cols), N2(num_rows2, num_cols),
606  O(num_rows2, num_cols);
607  std::vector<int32> reorder(num_rows1);
608  std::vector<Real*> reorder_dst(num_rows1, NULL);
609  unordered_map<MatrixIndexT, bool> used_index;
610  for (int32 i = 0; i < num_rows1; i++) {
611  MatrixIndexT index = -1 + (Rand() % (num_rows2 + 1));
612  if (used_index.find(index) == used_index.end()) {
613  used_index[index] = true;
614  } else {
615  index = -1;
616  }
617  reorder[i] = index;
618  if (index != -1) {
619  reorder_dst[i] = N1.RowData(index);
620  for (int32 j = 0; j < num_cols; j++)
621  O(index, j) += alpha * M(i, j);
622  }
623  }
624 
625  CuArray<int32> reorder_cuda(reorder);
626  CuArray<Real*> reorder_dst_cuda(reorder_dst);
627  M.AddToRows(alpha, reorder_dst_cuda);
628  M.AddToRows(alpha, reorder_cuda, &N2);
629  KALDI_ASSERT(ApproxEqual(N1, O));
630  KALDI_ASSERT(ApproxEqual(N2, O));
631  }
632 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddTpMat()

static void kaldi::UnitTestCuMatrixAddTpMat ( )
static

Definition at line 1891 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddTpMat(), MatrixBase< Real >::AddTpMat(), rnnlm::i, KALDI_ASSERT, kNoTrans, Rand(), PackedMatrix< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

1891  {
1892  for (int32 i = 1; i < 10; i++) {
1893  MatrixIndexT dim = 5 * i + Rand() % 10;
1894 
1895  Matrix<Real> A(dim, dim);
1896  Matrix<Real> B(dim, dim);
1897  TpMatrix<Real> C(dim);
1898  A.SetRandn();
1899  B.SetRandn();
1900  C.SetRandn();
1901  CuMatrix<Real> D(A);
1902  CuMatrix<Real> E(B);
1903  CuTpMatrix<Real> F(C);
1904 
1905  A.AddTpMat(1.0, C, kNoTrans, B, kNoTrans, 1.0);
1906  D.AddTpMat(1.0, F, kNoTrans, E, kNoTrans, 1.0);
1907 
1908  CuMatrix<Real> G(A);
1909  KALDI_ASSERT(ApproxEqual<Real>(G, D));
1910  }
1911 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixAddVecToCols()

static void kaldi::UnitTestCuMatrixAddVecToCols ( )
static

Definition at line 1538 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddVecToCols(), MatrixBase< Real >::AddVecToCols(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuMatrixBase< Real >::CopyToMat(), InitRand(), KALDI_ASSERT, and MatrixBase< Real >::SetRandn().

1538  {
1539  Matrix<Real> Hm(100,99);
1540  Vector<Real> Hv(100);
1541  Hm.SetRandn();
1542  InitRand(&Hv);
1543 
1544  CuMatrix<Real> Dm(100,99);
1545  CuVector<Real> Dv(100);
1546  Dm.CopyFromMat(Hm);
1547  Dv.CopyFromVec(Hv);
1548 
1549  Dm.AddVecToCols(0.5,Dv);
1550  Hm.AddVecToCols(0.5,Hv);
1551 
1552  Matrix<Real> Hm2(100,99);
1553  Dm.CopyToMat(&Hm2);
1554 
1555  KALDI_ASSERT(ApproxEqual(Hm,Hm2));
1556 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddVecToRows()

static void kaldi::UnitTestCuMatrixAddVecToRows ( )
static

Definition at line 1561 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddVecToRows(), MatrixBase< Real >::AddVecToRows(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuMatrixBase< Real >::CopyToMat(), InitRand(), KALDI_ASSERT, and MatrixBase< Real >::SetRandn().

1561  {
1562  Matrix<Real> Hm(100,99);
1563  Vector<Real> Hv(99);
1564  Hm.SetRandn();
1565  InitRand(&Hv);
1566 
1567  CuMatrix<Real> Dm(100,99);
1568  CuVector<Real> Dv(99);
1569  Dm.CopyFromMat(Hm);
1570  Dv.CopyFromVec(Hv);
1571 
1572  Dm.AddVecToRows(0.5,Dv);
1573  Hm.AddVecToRows(0.5,Hv);
1574 
1575  Matrix<Real> Hm2(100,99);
1576  Dm.CopyToMat(&Hm2);
1577 
1578  KALDI_ASSERT(ApproxEqual(Hm,Hm2));
1579 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixAddVecVec()

static void kaldi::UnitTestCuMatrixAddVecVec ( )
static

Definition at line 1691 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddVecVec(), MatrixBase< Real >::AddVecVec(), ApproxEqual(), CuVectorBase< Real >::CopyFromVec(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, and VectorBase< Real >::SetRandn().

1691  {
1692  Vector<Real> x(100);
1693  Vector<Real> y(200);
1694  x.SetRandn();
1695  y.SetRandn();
1696 
1697  CuVector<Real> Cux(100);
1698  CuVector<Real> Cuy(200);
1699  Cux.CopyFromVec(x);
1700  Cuy.CopyFromVec(y);
1701 
1702  Matrix<Real> A(100,200);
1703  CuMatrix<Real> CuA(100,200);
1704 
1705  A.AddVecVec(0.5f, x, y);
1706  CuA.AddVecVec(0.5f, Cux, Cuy);
1707  Matrix<Real> A2(100, 200);
1708  CuA.CopyToMat(&A2);
1709 
1710  KALDI_ASSERT(ApproxEqual(A,A2));
1711 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyCeiling()

static void kaldi::UnitTestCuMatrixApplyCeiling ( )
static

Definition at line 933 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyCeiling(), CuMatrixBase< Real >::ApplyCeiling(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kTrans, Rand(), and MatrixBase< Real >::SetRandn().

933  {
934 
935  for (int32 i = 0; i < 3; i++) {
936  BaseFloat ceiling = 0.33 * (Rand() % 6);
937 
938  Matrix<Real> H(10 + Rand() % 600, 10 + Rand() % 20);
939  H.SetRandn();
940  if (i == 2) { Matrix<Real> tmp(H,kTrans); H = tmp; }
941 
942  CuMatrix<Real> cH(H);
943 
944  cH.ApplyCeiling(ceiling);
945 
946  H.ApplyCeiling(ceiling);
947  Matrix<Real> H2(cH);
948 
949  KALDI_ASSERT(ApproxEqual(H, H2));
950  }
951 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyExp()

static void kaldi::UnitTestCuMatrixApplyExp ( )
static

Definition at line 181 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyExp(), CuMatrixBase< Real >::ApplyExp(), ApproxEqual(), KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

181  {
182  int32 M = 10 + Rand() % 20, N = 10 + Rand() % 20;
183  Matrix<Real> H(M, N);
184  H.SetRandn();
185 
186  CuMatrix<Real> D(H);
187 
188  D.ApplyExp();
189  H.ApplyExp();
190 
191  Matrix<Real> H2(D);
192 
193  KALDI_ASSERT(ApproxEqual(H,H2));
194 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyExpLimited()

static void kaldi::UnitTestCuMatrixApplyExpLimited ( )
static

Definition at line 198 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyCeiling(), MatrixBase< Real >::ApplyExp(), CuMatrixBase< Real >::ApplyExpLimited(), MatrixBase< Real >::ApplyFloor(), ApproxEqual(), KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

198  {
199  int32 M = 10 + Rand() % 20, N = 10 + Rand() % 20;
200  Matrix<Real> H(M, N);
201  H.SetRandn();
202 
203  BaseFloat lower_limit = -0.2, upper_limit = 0.2;
204 
205  CuMatrix<Real> D(H);
206  D.ApplyExpLimited(lower_limit, upper_limit);
207 
208  H.ApplyFloor(lower_limit);
209  H.ApplyCeiling(upper_limit);
210  H.ApplyExp();
211  Matrix<Real> H2(D);
212 
213  KALDI_ASSERT(ApproxEqual(H,H2));
214 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyExpSpecial()

static void kaldi::UnitTestCuMatrixApplyExpSpecial ( )
static

Definition at line 165 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyExpSpecial(), CuMatrixBase< Real >::ApplyExpSpecial(), ApproxEqual(), KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

165  {
166  int32 M = 10 + Rand() % 20;
167  int32 N = 10 + Rand() % 20;
168  Matrix<Real> H(M, N);
169  H.SetRandn();
170 
171  CuMatrix<Real> D(H);
172 
173  D.ApplyExpSpecial();
174  H.ApplyExpSpecial();
175 
176  Matrix<Real> H2(D);
177  KALDI_ASSERT(ApproxEqual(H,H2));
178 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyFloor()

static void kaldi::UnitTestCuMatrixApplyFloor ( )
static

Definition at line 912 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyFloor(), CuMatrixBase< Real >::ApplyFloor(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kTrans, Rand(), and MatrixBase< Real >::SetRandn().

912  {
913 
914  for (int32 i = 0; i < 3; i++) {
915  BaseFloat floor = 0.33 * (Rand() % 6);
916 
917  Matrix<Real> H(10 + Rand() % 600, 10 + Rand() % 20);
918  H.SetRandn();
919  if (i == 2) { Matrix<Real> tmp(H, kTrans); H = tmp; }
920 
921  CuMatrix<Real> cH(H);
922 
923  cH.ApplyFloor(floor);
924 
925  H.ApplyFloor(floor);
926  Matrix<Real> H2(cH);
927 
928  KALDI_ASSERT(ApproxEqual(H, H2));
929  }
930 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyHeaviside()

static void kaldi::UnitTestCuMatrixApplyHeaviside ( )
static

Definition at line 954 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyHeaviside(), CuMatrixBase< Real >::ApplyHeaviside(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kTrans, Rand(), MatrixBase< Real >::Row(), and MatrixBase< Real >::SetRandn().

954  {
955 
956  for (int32 i = 0; i < 1; i++) {
957  Matrix<Real> H(10 + Rand() % 60, 10 + Rand() % 20);
958  H.SetRandn();
959  H.Row(0).Set(0.0);
960  if (i == 2) { Matrix<Real> tmp(H, kTrans); H = tmp; }
961 
962 
963  CuMatrix<Real> cH(H);
964 
965  cH.ApplyHeaviside();
966  H.ApplyHeaviside();
967  Matrix<Real> H2(cH);
968  KALDI_ASSERT(ApproxEqual(H, H2));
969  }
970 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyLog()

static void kaldi::UnitTestCuMatrixApplyLog ( )
static

Definition at line 143 of file cu-matrix-test.cc.

References MatrixBase< Real >::Add(), MatrixBase< Real >::ApplyLog(), CuMatrixBase< Real >::ApplyLog(), ApproxEqual(), KALDI_ASSERT, MatrixBase< Real >::MulElements(), Rand(), and MatrixBase< Real >::SetRandUniform().

143  {
144  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
145  Matrix<Real> H(M, N);
146  H.SetRandUniform(); // Using uniform distribution to ensure positive numbers
147  H.Add(0.1); // Add bias to eliminate zeros
148  H.MulElements(H); // make numbers positive
149 
150  CuMatrix<Real> D(H);
151 
152  D.ApplyLog();
153  H.ApplyLog();
154 
155  Matrix<Real> H2(D);
156 
157  KALDI_ASSERT(ApproxEqual(H,H2));
158 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyPow()

static void kaldi::UnitTestCuMatrixApplyPow ( )
static

Definition at line 349 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyPow(), CuMatrixBase< Real >::ApplyPow(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kTrans, MatrixBase< Real >::MulElements(), Rand(), MatrixBase< Real >::Row(), and MatrixBase< Real >::SetRandn().

349  {
350 
351  for (int32 i = 0; i < 2; i++) {
352  BaseFloat pow = 0.5 * (Rand() % 6);
353 
354  Matrix<Real> H(10 + Rand() % 60, 10 + Rand() % 20);
355  H.SetRandn();
356  H.Row(0).Set(0.0);
357  if (i == 2) { Matrix<Real> tmp(H, kTrans); H = tmp; }
358 
359  if (pow != 1.0 && pow != 2.0 && pow != 3.0)
360  H.MulElements(H); //make numbers positive
361 
362  CuMatrix<Real> cH(H);
363 
364  cH.ApplyPow(pow);
365 
366  H.ApplyPow(pow);
367  Matrix<Real> H2(cH);
368  KALDI_ASSERT(ApproxEqual(H, H2));
369  }
370 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixApplyPowAbs()

static void kaldi::UnitTestCuMatrixApplyPowAbs ( )
static

Definition at line 373 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyPowAbs(), CuMatrixBase< Real >::ApplyPowAbs(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kTrans, Rand(), MatrixBase< Real >::Row(), and MatrixBase< Real >::SetRandn().

373  {
374 
375  for (int32 i = 0; i < 2; i++) {
376  BaseFloat pow = 0.5 * (Rand() % 6);
377 
378  Matrix<Real> H(10 + Rand() % 60, 10 + Rand() % 20);
379  H.SetRandn();
380  H.Row(0).Set(0.0);
381  if (i == 2) { Matrix<Real> tmp(H, kTrans); H = tmp; }
382 
383  CuMatrix<Real> cH(H);
384 
385  cH.ApplyPowAbs(pow, true);
386 
387  H.ApplyPowAbs(pow, true);
388  Matrix<Real> H2(cH);
389  KALDI_ASSERT(ApproxEqual(H, H2));
390  }
391 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyCols()

static void kaldi::UnitTestCuMatrixCopyCols ( )
static

Definition at line 753 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and CuMatrixBase< Real >::SetRandn().

753  {
754  for (int32 p = 0; p < 2; p++) {
755  MatrixIndexT num_cols1 = 10 + Rand() % 10,
756  num_cols2 = 10 + Rand() % 10,
757  num_rows = 10 + Rand() % 10;
758  CuMatrix<Real> M(num_rows, num_cols1);
759  M.SetRandn();
760 
761  CuMatrix<Real> N(num_rows, num_cols2), O(num_rows, num_cols2);
762  std::vector<int32> reorder(num_cols2);
763  for (int32 i = 0; i < num_cols2; i++)
764  reorder[i] = -1 + (Rand() % (num_cols1 + 1));
765 
766  CuArray<int32> reorder_gpu(reorder);
767  N.CopyCols(M, reorder_gpu);
768 
769  for (int32 i = 0; i < num_rows; i++)
770  for (int32 j = 0; j < num_cols2; j++)
771  if (reorder[j] < 0) O(i, j) = 0;
772  else O(i, j) = M(i, reorder[j]);
773  KALDI_ASSERT(ApproxEqual(N, O));
774  }
775 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyColsFromVec()

static void kaldi::UnitTestCuMatrixCopyColsFromVec ( )
static

Definition at line 422 of file cu-matrix-test.cc.

References ApproxEqual(), MatrixBase< Real >::CopyColsFromVec(), CuMatrixBase< Real >::CopyColsFromVec(), KALDI_ASSERT, Rand(), and CuVectorBase< Real >::SetRandn().

422  {
423  for (int32 p = 0; p < 2; p++) {
424  int32 num_rows = 100 + Rand() % 255;
425  int32 num_cols = 100 + Rand() % 200;
426 
427  int32 vec_dim;
428  if (p % 2 == 0) vec_dim = num_rows;
429  else vec_dim = num_cols * num_rows;
430 
431  CuVector<Real> cu_vec(vec_dim);
432  cu_vec.SetRandn();
433  Vector<Real> vec(cu_vec);
434 
435  CuMatrix<Real> cu_mat(num_rows, num_cols);
436  cu_mat.CopyColsFromVec(cu_vec);
437  Matrix<Real> mat(num_rows, num_cols);
438  mat.CopyColsFromVec(vec);
439 
440  Matrix<Real> mat2(cu_mat);
441  KALDI_ASSERT(ApproxEqual(mat, mat2));
442  }
443 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyCross()

void kaldi::UnitTestCuMatrixCopyCross ( )

Definition at line 636 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, kTrans, Rand(), and CuMatrixBase< Real >::SetRandn().

636  {
637  for (int32 i = 0; i < 2; i++) {
638  int32 M = 100 + Rand() % 255, N = 100 + Rand() % 255;
639  if (Rand() % 3 == 0) { M = 0; N = 0; }
640  CuMatrix<Real> mat1(M, N);
641  mat1.SetRandn();
642  if (i % 2 == 0) {
643  CuMatrix<float> mat2(M, N);
644  mat2.CopyFromMat(mat1);
645  CuMatrix<Real> mat3(M, N);
646  mat3.CopyFromMat(mat2);
647  KALDI_ASSERT(ApproxEqual(mat1, mat3));
648  } else {
649  CuMatrix<float> mat2(N, M);
650  mat2.CopyFromMat(mat1, kTrans);
651  CuMatrix<Real> mat3(M, N);
652  mat3.CopyFromMat(mat2, kTrans);
653  KALDI_ASSERT(ApproxEqual(mat1, mat3));
654  }
655  }
656 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyCross2()

void kaldi::UnitTestCuMatrixCopyCross2 ( )

Definition at line 658 of file cu-matrix-test.cc.

References ApproxEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, Rand(), and CuMatrixBase< Real >::SetRandn().

658  {
659  for (int32 i = 0; i < 2; i++) {
660  int32 M = 100 + Rand() % 255, N = 100 + Rand() % 255;
661  if (Rand() % 3 == 0) { M = 0; N = 0; }
662  CuMatrix<Real> mat1(M, N);
663  mat1.SetRandn();
664  Matrix<float> mat2(M, N);
665  mat2.CopyFromMat(mat1);
666  CuMatrix<Real> mat3(M, N);
667  mat3.CopyFromMat(mat2);
668  KALDI_ASSERT(ApproxEqual(mat1, mat3));
669  }
670 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyFromMat()

static void kaldi::UnitTestCuMatrixCopyFromMat ( )
static

Definition at line 1818 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

1818  {
1819  for (int32 i = 1; i < 10; i++) {
1820  MatrixIndexT dim = 5 * i + Rand() % 10;
1821 
1822  Matrix<Real> A(dim, dim);
1823  A.SetRandn();
1824  CuMatrix<Real> E(A);
1825  CuMatrix<Real> B(dim, dim);
1826  B.CopyFromMat(E);
1827 
1828  KALDI_ASSERT(ApproxEqual<Real>(B, E));
1829  }
1830 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixCopyFromTp()

static void kaldi::UnitTestCuMatrixCopyFromTp ( )
static

Definition at line 1833 of file cu-matrix-test.cc.

References MatrixBase< Real >::CopyFromTp(), CuMatrixBase< Real >::CopyFromTp(), rnnlm::i, KALDI_ASSERT, kNoTrans, Rand(), and PackedMatrix< Real >::SetRandn().

1833  {
1834  for (int32 i = 1; i < 10; i++) {
1835  MatrixIndexT dim = 5 * i + Rand() % 10;
1836  TpMatrix<Real> A(dim);
1837  A.SetRandn();
1838  CuTpMatrix<Real> E(A);
1839  Matrix<Real> B(dim, dim);
1840  CuMatrix<Real> C(dim, dim);
1841  B.CopyFromTp(A, kNoTrans);
1842  C.CopyFromTp(E, kNoTrans);
1843  CuMatrix<Real> D(B);
1844  KALDI_ASSERT(ApproxEqual<Real>(D, C));
1845  }
1846 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixCopyLowerToUpper()

static void kaldi::UnitTestCuMatrixCopyLowerToUpper ( )
static

Definition at line 2718 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::CopyLowerToUpper(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), CuMatrixBase< Real >::SetRandn(), and MatrixBase< Real >::Trace().

2718  {
2719  for (int i = 1; i < 2; ++i) {
2720  MatrixIndexT dim = 10 * i + Rand() % 4 + (i == 9 ? 255 : 0);
2721  if (i == 8) dim = 0;
2722  CuMatrix<Real> A(dim, dim);
2723  A.SetRandn();
2724  Matrix<Real> A2(A);
2725  A.CopyLowerToUpper();
2726  Matrix<Real> A3(A);
2727  for (int32 i = 0; i < dim; i++) {
2728  for (int32 j = 0; j <= i; j++) {
2729  KALDI_ASSERT(A3(i, j) == A3(j, i));
2730  KALDI_ASSERT(A3(i, j) == A2(i, j));
2731  }
2732  }
2733  KALDI_ASSERT(dim == 0 || A3.Trace() != 0);
2734  }
2735 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixCopyRows()

static void kaldi::UnitTestCuMatrixCopyRows ( )
static

Definition at line 447 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), CuMatrixBase< Real >::RowData(), and CuMatrixBase< Real >::SetRandn().

447  {
448  for (int32 p = 0; p < 2; p++) {
449  MatrixIndexT num_rows1 = 10 + Rand() % 10,
450  num_rows2 = 10 + Rand() % 10,
451  num_cols = 10 + Rand() % 10;
452  CuMatrix<Real> M(num_rows1, num_cols);
453  M.SetRandn();
454 
455  CuMatrix<Real> N1(num_rows2, num_cols),
456  N2(num_rows2, num_cols), O(num_rows2, num_cols);
457  std::vector<int32> reorder(num_rows2);
458  std::vector<const Real*> reorder_src(num_rows2, NULL);
459  for (int32 i = 0; i < num_rows2; i++) {
460  reorder[i] = -1 + (Rand() % (num_rows1 + 1));
461  if (reorder[i] != -1) {
462  reorder_src[i] = M.RowData(reorder[i]);
463  }
464  }
465 
466  CuArray<int32> reorder_cuda(reorder);
467  CuArray<const Real*> reorder_src_cuda(reorder_src);
468  N1.CopyRows(M, reorder_cuda);
469  N2.CopyRows(reorder_src_cuda);
470 
471  for (int32 i = 0; i < num_rows2; i++)
472  for (int32 j = 0; j < num_cols; j++)
473  if (reorder[i] < 0) O(i, j) = 0;
474  else O(i, j) = M(reorder[i], j);
475 
476  KALDI_ASSERT(ApproxEqual(N1, O));
477  KALDI_ASSERT(ApproxEqual(N2, O));
478  }
479 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyRowsFromVec()

static void kaldi::UnitTestCuMatrixCopyRowsFromVec ( )
static

Definition at line 395 of file cu-matrix-test.cc.

References ApproxEqual(), MatrixBase< Real >::CopyRowsFromVec(), CuMatrixBase< Real >::CopyRowsFromVec(), KALDI_ASSERT, Rand(), and CuVectorBase< Real >::SetRandn().

395  {
396  for (int32 p = 0; p < 2; p++) {
397  int32 num_rows = 100 + Rand() % 255, num_cols;
398  if (p <= 2) num_cols = 128;
399  else if (p <= 4) num_cols = 256;
400  else num_cols = 100 + Rand() % 200;
401 
402  int32 vec_dim;
403  if (p % 2 == 0) vec_dim = num_cols;
404  else vec_dim = num_cols * num_rows;
405 
406  CuVector<Real> cu_vec(vec_dim);
407  cu_vec.SetRandn();
408  Vector<Real> vec(cu_vec);
409 
410  CuMatrix<Real> cu_mat(num_rows, num_cols);
411  cu_mat.CopyRowsFromVec(cu_vec);
412  Matrix<Real> mat(num_rows, num_cols);
413  mat.CopyRowsFromVec(vec);
414 
415  Matrix<Real> mat2(cu_mat);
416  KALDI_ASSERT(ApproxEqual(mat, mat2));
417  }
418 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyToRows()

static void kaldi::UnitTestCuMatrixCopyToRows ( )
static

Definition at line 483 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyToRows(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and CuMatrixBase< Real >::SetRandn().

483  {
484  for (int32 p = 0; p < 2; p++) {
485  MatrixIndexT num_rows1 = 10 + Rand() % 10,
486  num_rows2 = 10 + Rand() % 10,
487  num_cols = 10 + Rand() % 10;
488  CuMatrix<Real> M(num_rows1, num_cols);
489  M.SetRandn();
490 
491  CuMatrix<Real> N(num_rows2, num_cols), O(num_rows2, num_cols);
492  std::vector<Real*> reorder_dst(num_rows1, NULL);
493  unordered_map<MatrixIndexT, bool> used_index;
494  for (int32 i = 0; i < num_rows1; i++) {
495  MatrixIndexT index = -1 + (Rand() % (num_rows2 + 1));
496  if (used_index.find(index) == used_index.end()) {
497  used_index[index] = true;
498  } else {
499  index = -1;
500  }
501  if (index != -1) {
502  reorder_dst[i] = N.RowData(index);
503  for (int32 j = 0; j < num_cols; j++)
504  O(index, j) = M(i, j);
505  }
506  }
507 
508  CuArray<Real*> reorder_dst_cuda(reorder_dst);
509  M.CopyToRows(reorder_dst_cuda);
510 
511  KALDI_ASSERT(ApproxEqual(N, O));
512  }
513 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Class CuArray represents a vector of an integer or struct of type T.
Definition: cu-array.h:32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixCopyUpperToLower()

static void kaldi::UnitTestCuMatrixCopyUpperToLower ( )
static

Definition at line 2759 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::CopyUpperToLower(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), CuMatrixBase< Real >::SetRandn(), and MatrixBase< Real >::Trace().

2759  {
2760  for (int i = 1; i < 10; ++i) {
2761  MatrixIndexT dim = 10 * i + Rand() % 4 + (i == 9 ? 255 : 0);
2762  if (i == 8) dim = 0;
2763  CuMatrix<Real> A(dim, dim);
2764  A.SetRandn();
2765  Matrix<Real> A2(A);
2766  A.CopyUpperToLower();
2767  Matrix<Real> A3(A);
2768  //KALDI_LOG << "A2 is " << A2 << " A3 is " << A3;
2769  for (int32 i = 0; i < dim; i++) {
2770  for (int32 j = i; j < dim; j++) {
2771  KALDI_ASSERT(A3(i, j) == A3(j, i));
2772  KALDI_ASSERT(A3(i, j) == A2(i, j));
2773  }
2774  }
2775  KALDI_ASSERT(dim == 0 || A3.Trace() != 0);
2776  }
2777 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixDiffGroupPnorm()

static void kaldi::UnitTestCuMatrixDiffGroupPnorm ( )
static

Definition at line 1164 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyFloor(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), CuMatrixBase< Real >::DiffGroupPnorm(), MatrixBase< Real >::GroupPnorm(), MatrixBase< Real >::GroupPnormDeriv(), rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::MulRowsGroupMat(), Rand(), and MatrixBase< Real >::SetRandn().

1164  {
1165  Real p[] = { 1.234, 2.345, 1, 2, std::numeric_limits<Real>::infinity() };
1166  for (int i = 0; i < 2 * sizeof(p) / sizeof(Real); i++) {
1167  int32 dimM = 100 + Rand() % 200, dimNs = 100 + Rand() % 200;
1168  int32 group_size = 1 + Rand() % 10;
1169  BaseFloat power = p[i / 2];
1170  int32 dimN = group_size * dimNs;
1171  Matrix<Real> Hiv(dimM, dimN);
1172  Matrix<Real> Hov(dimM, dimNs);
1173  Matrix<Real> Hid(dimM, dimN);
1174  Matrix<Real> Hod(dimM, dimNs);
1175  Hiv.SetRandn();
1176  Hod.SetRandn();
1177  if (i % 2 == 0)
1178  Hiv.ApplyFloor(0.0); // will put some zeros in the matrix.. harder to
1179  // do derivatives.
1180  Hov.GroupPnorm(Hiv, power);
1181  CuMatrix<Real> Div(dimM, dimN);
1182  CuMatrix<Real> Dov(dimM, dimNs);
1183  CuMatrix<Real> Did(dimM, dimN);
1184  CuMatrix<Real> Dod(dimM, dimNs);
1185  Div.CopyFromMat(Hiv);
1186  Dod.CopyFromMat(Hod);
1187  Dov.CopyFromMat(Hov);
1188 
1189  // GPU
1190  Did.DiffGroupPnorm(Div, Dov, Dod, power);
1191 
1192  // CPU
1193  Hid.GroupPnormDeriv(Hiv, Hov, power);
1194  Hid.MulRowsGroupMat(Hod);
1195 
1196  Matrix<Real> Hid2(dimM, dimN);
1197  Did.CopyToMat(&Hid2);
1198  KALDI_ASSERT(ApproxEqual(Hid, Hid2));
1199  }
1200 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixDivElements()

static void kaldi::UnitTestCuMatrixDivElements ( )
static

Definition at line 1018 of file cu-matrix-test.cc.

References MatrixBase< Real >::Add(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), MatrixBase< Real >::DivElements(), CuMatrixBase< Real >::DivElements(), rnnlm::i, KALDI_ASSERT, Rand(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandUniform().

1018  {
1019  for (int32 i = 0; i < 2; i++) {
1020  MatrixIndexT dimM = 100 + Rand() % 256, dimN = 100 + Rand() % 256;
1021 
1022  Matrix<Real> Ha(dimM, dimN);
1023  Matrix<Real> Hb(dimM, dimN);
1024  Ha.SetRandn();
1025 
1026  Hb.SetRandUniform(); // Use uniform distirbution t ensure positive numbers
1027  Hb.Add(0.1); // Add bias to ensure we do not divide by zero
1028 
1029  CuMatrix<Real> Da(dimM, dimN);
1030  CuMatrix<Real> Db(dimM, dimN);
1031  Da.CopyFromMat(Ha);
1032  Db.CopyFromMat(Hb);
1033 
1034  Da.DivElements(Db);
1035  Ha.DivElements(Hb);
1036 
1037  Matrix<Real> Ha2(dimM, dimN);
1038  Da.CopyToMat(&Ha2);
1039 
1040  KALDI_ASSERT(ApproxEqual(Ha,Ha2));
1041  }
1042 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixDivRowsVec()

static void kaldi::UnitTestCuMatrixDivRowsVec ( )
static

Definition at line 1342 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuMatrixBase< Real >::CopyToMat(), CuMatrixBase< Real >::DivRowsVec(), InitRand(), VectorBase< Real >::InvertElements(), KALDI_ASSERT, MatrixBase< Real >::MulRowsVec(), and MatrixBase< Real >::SetRandn().

1342  {
1343  MatrixIndexT dimM = 1000, dimN = 5;
1344  Matrix<Real> Hm(dimM, dimN);
1345  Vector<Real> Hv(dimM);
1346  Hm.SetRandn();
1347  InitRand(&Hv);
1348 
1349  CuMatrix<Real> Dm(dimM, dimN);
1350  CuVector<Real> Dv(dimM);
1351  Dm.CopyFromMat(Hm);
1352  Dv.CopyFromVec(Hv);
1353 
1354  Dm.DivRowsVec(Dv);
1355  Hv.InvertElements();
1356  Hm.MulRowsVec(Hv);
1357 
1358  Matrix<Real> Hm2(dimM, dimN);
1359  Dm.CopyToMat(&Hm2);
1360 
1361  KALDI_ASSERT(ApproxEqual(Hm, Hm2));
1362 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixEqualElementMask()

static void kaldi::UnitTestCuMatrixEqualElementMask ( )
static

Definition at line 2920 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::Add(), KALDI_ASSERT, kSetZero, CuMatrixBase< Real >::SetRandUniform(), and CuMatrixBase< Real >::Sum().

2920  {
2921  CuMatrix<Real> m1(10,9), m2(10,9);
2922  CuMatrix<Real> mask_same, mask_different;
2923  m1.SetRandUniform(); // U[0,1]
2924  m2.SetRandUniform(); m2.Add(10.0); // U[10,11]
2925 
2926  m1.EqualElementMask(m1,&mask_same); // all elements ones
2927  m1.EqualElementMask(m2,&mask_different); // all elements zeros
2928 
2929  //KALDI_LOG << m1 << m2 << mask_same << mask_different;
2930  KALDI_ASSERT(mask_same.Sum() == 10*9);
2931  KALDI_ASSERT(mask_different.Sum() == 0.0);
2932 
2933  //check matrices with different strides:
2934  CuMatrix<Real> m3(m1.Range(1,6,2,6));
2935  CuMatrix<Real> m4(5,5,kSetZero);
2936  m1.Range(1,5,2,5).EqualElementMask(m3.Range(0,5,0,5),&m4); // strides 9, 6, 5
2937  KALDI_ASSERT(m4.Sum() == 25);
2938 
2939 }
Real Sum() const
Definition: cu-matrix.cc:3012
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixGroupMax()

static void kaldi::UnitTestCuMatrixGroupMax ( )
static

Definition at line 313 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyFloor(), ApproxEqual(), CuMatrixBase< Real >::GroupMax(), MatrixBase< Real >::GroupMax(), KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

313  {
314  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
315  // M = 256; N = 256;
316  for (int32 K = 5; K < 7; K++) {
317  int32 N_src = N * K;
318  Matrix<Real> H_src(M, N_src);
319  H_src.SetRandn();
320  if (rand () % 2 == 0)
321  H_src.ApplyFloor(0.0); // will put some zeros in the matrix.. harder to
322  // do derivatives.
323  Matrix<Real> H(M, N);
324  H.GroupMax(H_src);
325  CuMatrix<Real> D(H_src);
326  CuMatrix<Real> E(M, N);
327  E.GroupMax(D);
328  Matrix<Real> H2(E);
329  KALDI_ASSERT(ApproxEqual(H,H2));
330  }
331 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixGroupMaxDeriv()

static void kaldi::UnitTestCuMatrixGroupMaxDeriv ( )
static

Definition at line 1204 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyFloor(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), MatrixBase< Real >::GroupMax(), CuMatrixBase< Real >::GroupMaxDeriv(), MatrixBase< Real >::GroupMaxDeriv(), KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

1204  {
1205  int32 dimM = 100 + Rand() % 200, dimNs = 100 + Rand() % 200;
1206  int32 group_size = 1 + Rand() % 10;
1207  // int32 dimM = 256, dimNs = 2;
1208  // int32 group_size = 2;
1209  int32 dimN = group_size * dimNs;
1210  Matrix<Real> Hm(dimM, dimN);
1211  Matrix<Real> Hr(dimM, dimN);
1212  Matrix<Real> Hs(dimM, dimNs);
1213  Hs.SetRandn();
1214  if (rand () % 2 == 0)
1215  Hm.ApplyFloor(0.0); // will put some zeros in the matrix.. harder to
1216  // do derivatives.
1217  Hs.GroupMax(Hm);
1218 
1219  CuMatrix<Real> Dm(dimM, dimN);
1220  CuMatrix<Real> Dr(dimM, dimN);
1221  CuMatrix<Real> Ds(dimM, dimNs);
1222  Dm.CopyFromMat(Hm);
1223  Dr.CopyFromMat(Hr);
1224  Ds.CopyFromMat(Hs);
1225 
1226  // KALDI_LOG << "Hr " << Hr << " Dr " << Dr << "Ds" << Ds << " Hs " << Hs ;
1227  Dr.GroupMaxDeriv(Dm, Ds);
1228  Hr.GroupMaxDeriv(Hm, Hs);
1229 
1230  // KALDI_LOG << "Hr " << Hr << " Dr " << Dr << "Ds" << Ds << " Hs " << Hs ;
1231  Matrix<Real> Hr2(dimM, dimN);
1232  Dr.CopyToMat(&Hr2);
1233  KALDI_ASSERT(ApproxEqual(Hr,Hr2));
1234 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixGroupPnorm()

static void kaldi::UnitTestCuMatrixGroupPnorm ( )
static

Definition at line 288 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyFloor(), ApproxEqual(), CuMatrixBase< Real >::GroupPnorm(), MatrixBase< Real >::GroupPnorm(), rnnlm::i, KALDI_ASSERT, Rand(), and MatrixBase< Real >::SetRandn().

288  {
289  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
290  Real power[] = { 1.4, 1.6, 0.1234, 2.123, 0, 1, 2,
291  std::numeric_limits<Real>::infinity() };
292  for (int32 K = 5; K < 7; K++) {
293  for (int32 i = 0; i < 2 * sizeof(power) / sizeof(Real); ++i) {
294  Real p = power[i / 2];
295  int32 N_src = N * K;
296  Matrix<Real> H_src(M, N_src);
297  H_src.SetRandn();
298  if (i % 2 == 0)
299  H_src.ApplyFloor(0.0); // will put some zeros in the matrix.. harder to
300  // do derivatives.
301  Matrix<Real> H(M, N);
302  H.GroupPnorm(H_src, p);
303  CuMatrix<Real> D(H_src);
304  CuMatrix<Real> E(M, N);
305  E.GroupPnorm(D, p);
306  Matrix<Real> H2(E);
307  KALDI_ASSERT(ApproxEqual(H, H2));
308  }
309  }
310 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixHeaviside()

static void kaldi::UnitTestCuMatrixHeaviside ( )
static

Definition at line 974 of file cu-matrix-test.cc.

References MatrixBase< Real >::ApplyHeaviside(), ApproxEqual(), CuMatrixBase< Real >::Heaviside(), rnnlm::i, KALDI_ASSERT, kTrans, kUndefined, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::Row(), and MatrixBase< Real >::SetRandn().

974  {
975 
976  for (int32 i = 0; i < 1; i++) {
977  Matrix<Real> H(10 + Rand() % 60, 10 + Rand() % 20);
978  H.SetRandn();
979  H.Row(0).Set(0.0);
980  if (i == 2) { Matrix<Real> tmp(H, kTrans); H = tmp; }
981 
982  CuMatrix<Real> cH(H);
983  CuMatrix<Real> cH2(H.NumRows(), H.NumCols(), kUndefined);
984  cH2.Heaviside(cH);
985  H.ApplyHeaviside();
986  Matrix<Real> H2(cH2);
987  KALDI_ASSERT(ApproxEqual(H, H2));
988  }
989 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void Heaviside(const CuMatrixBase< Real > &src)
Set each element to the Heaviside function of the corresponding element of "src", which we define as ...
Definition: cu-matrix.cc:2435
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixInvertElements()

static void kaldi::UnitTestCuMatrixInvertElements ( )
static

Definition at line 2093 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), InitRand(), MatrixBase< Real >::InvertElements(), CuMatrixBase< Real >::InvertElements(), and KALDI_ASSERT.

2093  {
2094  Matrix<Real> Hm(77, 77);
2095  InitRand(&Hm);
2096 
2097  CuMatrix<Real> Dm(77, 77);
2098  Dm.CopyFromMat(Hm);
2099 
2100  Dm.InvertElements();
2101  Hm.InvertElements();
2102 
2103  Matrix<Real> Hm2(77, 77);
2104  Dm.CopyToMat(&Hm2);
2105 
2106  KALDI_ASSERT(ApproxEqual(Hm,Hm2));
2107 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixIO()

static void kaldi::UnitTestCuMatrixIO ( )
static

Definition at line 2111 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, Rand(), CuMatrix< Real >::Read(), CuMatrixBase< Real >::SetRandn(), swap(), and CuMatrixBase< Real >::Write().

2111  {
2112  for (int32 i = 0; i < 10; i++) {
2113  int32 dimM = 100 + Rand() % 255, dimN = 10 + Rand() % 20;
2114  if (i % 2 == 0) std::swap(dimM, dimN);
2115  if (i % 5 == 0) { dimM = 0; dimN = 0; }
2116  CuMatrix<Real> mat(dimM, dimN);
2117  mat.SetRandn();
2118  std::ostringstream os;
2119  bool binary = (i % 4 < 2);
2120  mat.Write(os, binary);
2121 
2122  CuMatrix<Real> mat2;
2123  std::istringstream is(os.str());
2124  mat2.Read(is, binary);
2125  KALDI_ASSERT(ApproxEqual(mat, mat2));
2126  }
2127 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Read(std::istream &is, bool binary)
I/O functions.
Definition: cu-matrix.cc:494
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixLookup()

static void kaldi::UnitTestCuMatrixLookup ( )
static

Definition at line 2889 of file cu-matrix-test.cc.

References Int32Pair::first, rnnlm::i, rnnlm::j, KALDI_ASSERT, CuMatrixBase< Real >::Lookup(), Rand(), Int32Pair::second, and CuMatrixBase< Real >::SetRandn().

2889  {
2890  for (int32 i = 0; i < 2; i++) {
2891  int32 dimM = 100 + Rand() % 200, dimN = 100 + Rand() % 200;
2892  CuMatrix<Real> H(dimM, dimN);
2893  H.SetRandn();
2894 
2895  int32 num_elements = 10 + Rand() % 10;
2896  std::vector<Int32Pair> indices;
2897  std::vector<Real> reference;
2898  std::vector<Real> output;
2899  output.resize(num_elements);
2900 
2901  // Generates the indices and the reference.
2902  for (int32 j = 0; j < num_elements; j++) {
2903  MatrixIndexT r = Rand() % dimM;
2904  MatrixIndexT c = Rand() % dimN;
2905 
2906  Int32Pair tmp_pair;
2907  tmp_pair.first = r;
2908  tmp_pair.second = c;
2909  indices.push_back(tmp_pair);
2910  reference.push_back(H(r, c));
2911  }
2912 
2913  H.Lookup(indices, &(output[0]));
2914 
2915  KALDI_ASSERT(reference == output);
2916  }
2917 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32_cuda second
Definition: cu-matrixdim.h:80
int32_cuda first
Definition: cu-matrixdim.h:79

◆ UnitTestCuMatrixMax()

static void kaldi::UnitTestCuMatrixMax ( )
static

Definition at line 1045 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, MatrixBase< Real >::Max(), CuMatrixBase< Real >::Max(), and MatrixBase< Real >::SetRandn().

1045  {
1046  Matrix<Real> Ha(100,100);
1047  Matrix<Real> Hb(100,100);
1048  Ha.SetRandn();
1049  Hb.SetRandn();
1050 
1051  CuMatrix<Real> Da(100,100);
1052  CuMatrix<Real> Db(100,100);
1053 
1054  Da.CopyFromMat(Ha);
1055  Db.CopyFromMat(Hb);
1056 
1057  Da.Max(Db);
1058  Ha.Max(Hb);
1059 
1060  Matrix<Real> Ha2(100,100);
1061  Da.CopyToMat(&Ha2);
1062 
1063  KALDI_ASSERT(ApproxEqual(Ha,Ha2));
1064 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixMin()

static void kaldi::UnitTestCuMatrixMin ( )
static

Definition at line 1067 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, MatrixBase< Real >::Min(), CuMatrixBase< Real >::Min(), and MatrixBase< Real >::SetRandn().

1067  {
1068  Matrix<Real> Ha(100,100);
1069  Matrix<Real> Hb(100,100);
1070  Ha.SetRandn();
1071  Hb.SetRandn();
1072 
1073  CuMatrix<Real> Da(100,100);
1074  CuMatrix<Real> Db(100,100);
1075  Da.CopyFromMat(Ha);
1076  Db.CopyFromMat(Hb);
1077 
1078  Da.Min(Db);
1079  Ha.Min(Hb);
1080 
1081  Matrix<Real> Ha2(100,100);
1082  Da.CopyToMat(&Ha2);
1083 
1084  KALDI_ASSERT(ApproxEqual(Ha, Ha2));
1085 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixMulColsVec()

static void kaldi::UnitTestCuMatrixMulColsVec ( )
static

Definition at line 1090 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuMatrixBase< Real >::CopyToMat(), InitRand(), KALDI_ASSERT, MatrixBase< Real >::MulColsVec(), CuMatrixBase< Real >::MulColsVec(), and MatrixBase< Real >::SetRandn().

1090  {
1091  Matrix<Real> Hm(100,99);
1092  Vector<Real> Hv(99);
1093  Hm.SetRandn();
1094  InitRand(&Hv);
1095 
1096  CuMatrix<Real> Dm(100,99);
1097  CuVector<Real> Dv(99);
1098  Dm.CopyFromMat(Hm);
1099  Dv.CopyFromVec(Hv);
1100 
1101  Dm.MulColsVec(Dv);
1102  Hm.MulColsVec(Hv);
1103 
1104  Matrix<Real> Hm2(100,99);
1105  Dm.CopyToMat(&Hm2);
1106 
1107  KALDI_ASSERT(ApproxEqual(Hm,Hm2));
1108 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixMulElements()

static void kaldi::UnitTestCuMatrixMulElements ( )
static

Definition at line 993 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::MulElements(), CuMatrixBase< Real >::MulElements(), Rand(), and MatrixBase< Real >::SetRandn().

993  {
994  for (int32 i = 0; i < 2; i++) {
995  MatrixIndexT dimM = 100 + Rand() % 256, dimN = 100 + Rand() % 256;
996 
997  Matrix<Real> Ha(dimM, dimN);
998  Matrix<Real> Hb(dimM, dimN);
999  Ha.SetRandn();
1000  Hb.SetRandn();
1001 
1002  CuMatrix<Real> Da(dimM, dimN);
1003  CuMatrix<Real> Db(dimM, dimN);
1004  Da.CopyFromMat(Ha);
1005  Db.CopyFromMat(Hb);
1006 
1007  Da.MulElements(Db);
1008  Ha.MulElements(Hb);
1009 
1010  Matrix<Real> Ha2(dimM, dimN);
1011  Da.CopyToMat(&Ha2);
1012 
1013  KALDI_ASSERT(ApproxEqual(Ha,Ha2));
1014  }
1015 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixMulRows()

static void kaldi::UnitTestCuMatrixMulRows ( )
static

Definition at line 558 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, Rand(), CuMatrixBase< Real >::RowData(), and CuMatrixBase< Real >::SetRandn().

558  {
559  for (int32 p = 0; p < 2; p++) {
560  MatrixIndexT num_rows1 = 10 + Rand() % 10,
561  num_rows2 = 10 + Rand() % 10,
562  num_cols = 10 + Rand() % 10;
563  CuMatrix<Real> M(num_rows1, num_cols);
564  M.SetRandn();
565 
566  CuMatrix<Real> N1(num_rows2, num_cols),
567  O(num_rows2, num_cols);
568  std::vector<int32> reorder(num_rows2);
569  std::vector<const Real*> reorder_src(num_rows2, NULL);
570  for (int32 i = 0; i < num_rows2; i++) {
571  reorder[i] = -1 + (Rand() % (num_rows1 + 1));
572  if (reorder[i] != -1)
573  reorder_src[i] = M.RowData(reorder[i]);
574  }
575 
576  CuArray<int32> reorder_cuda(reorder);
577  N1.MulRows(M, reorder_cuda);
578 
579  for (int32 i = 0; i < num_rows2; i++) {
580  if (reorder[i] != -1) {
581  CuSubVector<Real> O_row(O, i),
582  M_row(M, reorder[i]);
583  O_row.MulElements(M_row);
584  }
585  }
586 
587  KALDI_ASSERT(ApproxEqual(N1, O));
588  }
589 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixMulRowsGroupMat()

static void kaldi::UnitTestCuMatrixMulRowsGroupMat ( )
static

Definition at line 1138 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::MulRowsGroupMat(), CuMatrixBase< Real >::MulRowsGroupMat(), Rand(), and MatrixBase< Real >::SetRandn().

1138  {
1139  for (int32 i = 0; i < 2; i++) {
1140  int32 dimM = 100 + Rand() % 200, dimNs = 100 + Rand() % 200;
1141  int32 group_size = 1 + Rand() % 10;
1142  //int32 group_size = 1;
1143  int32 dimN = group_size * dimNs;
1144  Matrix<Real> Hm(dimM, dimN);
1145  Matrix<Real> Hs(dimM, dimNs);
1146  Hm.SetRandn();
1147  Hs.SetRandn();
1148 
1149  CuMatrix<Real> Dm(dimM, dimN);
1150  CuMatrix<Real> Ds(dimM, dimNs);
1151  Dm.CopyFromMat(Hm);
1152  Ds.CopyFromMat(Hs);
1153 
1154  Dm.MulRowsGroupMat(Ds);
1155  Hm.MulRowsGroupMat(Hs);
1156 
1157  Matrix<Real> Hm2(dimM, dimN);
1158  Dm.CopyToMat(&Hm2);
1159  KALDI_ASSERT(ApproxEqual(Hm,Hm2));
1160  }
1161 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixMulRowsVec()

static void kaldi::UnitTestCuMatrixMulRowsVec ( )
static

Definition at line 1113 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuMatrixBase< Real >::CopyToMat(), rnnlm::i, InitRand(), KALDI_ASSERT, MatrixBase< Real >::MulRowsVec(), CuMatrixBase< Real >::MulRowsVec(), Rand(), and MatrixBase< Real >::SetRandn().

1113  {
1114  for (int32 i = 0; i < 2; i++) {
1115  int32 dimM = 100 + Rand() % 200, dimN = 100 + Rand() % 200;
1116  // int32 dimM = 256, dimN = 256;
1117  Matrix<Real> Hm(dimM, dimN);
1118  Vector<Real> Hv(dimM);
1119  Hm.SetRandn();
1120  InitRand(&Hv);
1121 
1122  CuMatrix<Real> Dm(dimM, dimN);
1123  CuVector<Real> Dv(dimM);
1124  Dm.CopyFromMat(Hm);
1125  Dv.CopyFromVec(Hv);
1126 
1127  Dm.MulRowsVec(Dv);
1128  Hm.MulRowsVec(Hv);
1129 
1130  Matrix<Real> Hm2(dimM, dimN);
1131  Dm.CopyToMat(&Hm2);
1132 
1133  KALDI_ASSERT(ApproxEqual(Hm,Hm2));
1134  }
1135 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixObjfDeriv()

static void kaldi::UnitTestCuMatrixObjfDeriv ( )
static

Definition at line 2781 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::Add(), CuMatrixBase< Real >::ApplyFloor(), CuMatrixBase< Real >::ApplyLog(), ApproxEqual(), CuMatrix< Real >::CompObjfAndDeriv(), rnnlm::i, CuMatrixBase< Real >::InvertElements(), rnnlm::j, KALDI_ASSERT, kTrans, Rand(), RandUniform(), CuMatrixBase< Real >::Set(), CuMatrixBase< Real >::SetRandn(), and TraceMatMat().

2781  {
2782  int32 n_r = 100 + Rand() % 200, n_c = 20 + Rand() % 30;
2783  CuMatrix<Real> A(n_r, n_c), B(n_r, n_c);
2784  B.SetRandn();
2785  B.Add(1.0);
2786  B.ApplyFloor(1.0e-10);
2787 
2788  std::vector<MatrixElement<Real> > labels;
2789  for(int i = 0; i < n_r; i++) {
2790  for(int j = 0; j < n_c; j++) {
2791  // have approximately one weight per row of the matrix.
2792  if (Rand() % n_c == 0) {
2793  A(i, j) = RandUniform();
2794  MatrixElement<Real> t = {i, j, A(i, j)};
2795  labels.push_back(t);
2796  }
2797  }
2798  }
2799  CuMatrix<Real> C(n_r, n_c);
2800  C.Set(0);
2801  Real a = 0, b = 0;
2802 
2803  // (sv_labels, logprobs, &tot_objf, &tot_weight)
2804  C.CompObjfAndDeriv(labels, B, &a, &b);
2805 
2806  KALDI_ASSERT(ApproxEqual(b, A.Sum()));
2807 
2808  Real sum2; // sum(i, j) A(i, j) log(B(i, j));
2809  {
2810  CuMatrix<Real> Bcopy(B);
2811  Bcopy.ApplyLog();
2812  sum2 = TraceMatMat(Bcopy, A, kTrans);
2813  }
2814  KALDI_ASSERT(ApproxEqual(a, sum2));
2815 
2816  B.InvertElements();
2817  A.MulElements(B); // each element of A is now A(i, j) / B(i, j);
2818  KALDI_ASSERT(ApproxEqual(A, C));
2819 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixReduceMax()

static void kaldi::UnitTestCuMatrixReduceMax ( )
static

Definition at line 1520 of file cu-matrix-test.cc.

References ApproxEqual(), KALDI_ASSERT, MatrixBase< Real >::Max(), CuMatrixBase< Real >::Max(), Rand(), and CuMatrixBase< Real >::SetRandn().

1520  {
1521  int32 M = 100 + Rand() % 300, N = 100 + Rand() % 300;
1522  CuMatrix<Real> A(M, N);
1523  A.SetRandn();
1524  Matrix<Real> mA(A);
1525  KALDI_ASSERT(ApproxEqual(mA.Max(), A.Max()));
1526 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixReduceMin()

static void kaldi::UnitTestCuMatrixReduceMin ( )
static

Definition at line 1529 of file cu-matrix-test.cc.

References ApproxEqual(), KALDI_ASSERT, MatrixBase< Real >::Min(), CuMatrixBase< Real >::Min(), Rand(), and CuMatrixBase< Real >::SetRandn().

1529  {
1530  int32 M = 100 + Rand() % 300, N = 100 + Rand() % 300;
1531  CuMatrix<Real> A(M, N);
1532  A.SetRandn();
1533  Matrix<Real> mA(A);
1534  KALDI_ASSERT(ApproxEqual(mA.Min(), A.Min()));
1535 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixReduceSum()

static void kaldi::UnitTestCuMatrixReduceSum ( )
static

Definition at line 1511 of file cu-matrix-test.cc.

References ApproxEqual(), KALDI_ASSERT, Rand(), CuMatrixBase< Real >::SetRandn(), MatrixBase< Real >::Sum(), and CuMatrixBase< Real >::Sum().

1511  {
1512  int32 M = 100 + Rand() % 300, N = 100 + Rand() % 300;
1513  CuMatrix<Real> A(M, N);
1514  A.SetRandn();
1515  Matrix<Real> mA(A);
1516  KALDI_ASSERT(ApproxEqual(mA.Sum(), A.Sum()));
1517 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixScale()

static void kaldi::UnitTestCuMatrixScale ( )
static

Definition at line 239 of file cu-matrix-test.cc.

References ApproxEqual(), KALDI_ASSERT, Rand(), MatrixBase< Real >::Scale(), CuMatrixBase< Real >::Scale(), and MatrixBase< Real >::SetRandn().

239  {
240  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
241  Matrix<Real> H(M, N);
242  H.SetRandn();
243 
244  BaseFloat scale = -1 + (0.33 * (Rand() % 5));
245  CuMatrix<Real> D(H);
246  D.Scale(scale);
247  H.Scale(scale);
248  Matrix<Real> E(D);
249 
250  KALDI_ASSERT(ApproxEqual(H, E));
251 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSet()

static void kaldi::UnitTestCuMatrixSet ( )
static

Definition at line 334 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, Rand(), MatrixBase< Real >::Set(), and CuMatrixBase< Real >::Set().

334  {
335  for (int32 i = 0; i < 2; i++) {
336  BaseFloat value= 0.333;
337  int32 dimM = 10 + Rand() % 600, dimN = 10 + Rand() % 400;
338  CuMatrix<Real> m1(dimM, dimN);
339  Matrix<Real> m2(dimM, dimN);
340  m1.Set(value);
341  m2.Set(value);
342  Matrix<Real> m3(m1);
343  KALDI_ASSERT(ApproxEqual(m2, m3));
344  }
345 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSetMatMatDivMat()

static void kaldi::UnitTestCuMatrixSetMatMatDivMat ( )
static

Definition at line 1319 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMatMatElements(), CuMatrixBase< Real >::ApplyFloor(), ApproxEqual(), CuMatrixBase< Real >::DivElements(), KALDI_ASSERT, Rand(), CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetZero().

1319  {
1320  // M = a * b / c (by element; when c = 0, M = a)
1321  MatrixIndexT dimM = 100 + Rand() % 255, dimN = 100 + Rand() % 255;
1322  CuMatrix<Real> M(dimM, dimN), A(dimM, dimN), B(dimM, dimN), C(dimM, dimN);
1323  CuMatrix<Real> ref(dimM, dimN);
1324  M.SetRandn();
1325  A.SetRandn();
1326  B.SetRandn();
1327  C.SetRandn();
1328 
1329  C.ApplyFloor(0.01); // make sure there are no zeros.
1330 
1331  M.SetMatMatDivMat(A,B,C);
1332  ref.AddMatMatElements(1.0, A, B, 0.0);
1333  ref.DivElements(C);
1334  KALDI_ASSERT(ApproxEqual(M, ref));
1335 
1336  C.SetZero();
1337  M.SetMatMatDivMat(A,B,C);
1338  KALDI_ASSERT(ApproxEqual(M, A));
1339 }
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSetRandn()

static void kaldi::UnitTestCuMatrixSetRandn ( )
static

Definition at line 2627 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::ApplyPow(), ApproxEqual(), DoubleFactorial(), rnnlm::i, KALDI_ASSERT, Rand(), MatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::Sum().

2627  {
2628 
2629 
2630  if (false) {
2631  // This block tests consistency when called twice.
2632  // It has been disabled since we added multi-threaded testing,
2633  // since consistency wouldn't be expected if other threads were running.
2634  int32 dimM = 100 + Rand() % 200, dimN = 100 + Rand() % 200;
2635  Matrix<Real> M(dimM, dimN), N(dimM, dimN);
2636  srand(104);
2637  M.SetRandn();
2638  srand(104);
2639  N.SetRandn();
2640  KALDI_ASSERT(ApproxEqual(M, N));
2641  }
2642 
2643  for (int32 i = 0; i < 5; i++) {
2644  MatrixIndexT rows = 100 + Rand() % 50, cols = 100 + Rand() % 50;
2645  CuMatrix<Real> M(rows, cols);
2646  M.SetRandn();
2647 
2648  for (int32 pow = 1; pow < 5; pow++) {
2649  // test moments 1 through 4 of
2650  // the distribution.
2651  CuMatrix<Real> Mpow(M);
2652  Mpow.ApplyPow(pow);
2653  Real observed_moment = Mpow.Sum() / (rows * cols);
2654  // see http://en.wikipedia.org/wiki/Normal_distribution#Moments,
2655  // note that mu = 0 and sigma = 1.
2656  Real expected_moment = (pow % 2 == 1 ? 0 : DoubleFactorial(pow - 1));
2657  Real expected_twice_moment = DoubleFactorial(2 * pow - 1);
2658  Real k = 10.0; // This is just a constant we use to give us some wiggle
2659  // room before rejecting the distribution... e.g. 20 sigma,
2660  // quite approximately.
2661  // VAR(X) = E(X^2) - (E(X))^2
2662  Real deviation = sqrt(expected_twice_moment - expected_moment * expected_moment);
2663  Real allowed_deviation = k * deviation / sqrt(static_cast<Real>(rows * cols));
2664  // give it a bit more wiggle room for higher powers.. this is quite
2665  // unscientific, it would be better to involve the absolute moments or
2666  // something like that, and use one of those statistical inequalities,
2667  // but it involves the gamma function and it's too much hassle to implement.
2668  Real lower_bound = expected_moment - allowed_deviation,
2669  upper_bound = expected_moment + allowed_deviation;
2670  KALDI_ASSERT(observed_moment >= lower_bound && observed_moment <= upper_bound);
2671  }
2672  }
2673 }
static int32 DoubleFactorial(int32 i)
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSetRandUniform()

static void kaldi::UnitTestCuMatrixSetRandUniform ( )
static

Definition at line 2677 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::Add(), CuMatrixBase< Real >::ApplyPow(), VectorBase< Real >::Dim(), rnnlm::i, KALDI_ERR, KALDI_LOG, Rand(), CuMatrixBase< Real >::SetRandUniform(), and CuMatrixBase< Real >::Sum().

2677  {
2678  for (int32 i = 0; i < 2; i++) {
2679  MatrixIndexT rows = 180 + Rand() % 200, cols = 200 + Rand() % 200;
2680  CuMatrix<Real> M(rows, cols);
2681  M.SetRandUniform();
2682 
2683  M.Add(-0.5); // we'll be testing the central moments, so
2684  // center it around zero first.
2685  // Got these moments from http://mathworld.wolfram.com/UniformDistribution.html
2686  Vector<Real> central_moments(5);
2687  central_moments(0) = 0.0;
2688  central_moments(1) = 0.0;
2689  central_moments(2) = 1.0 / 12; // times (b - a)^2, which equals 1.
2690  central_moments(3) = 0.0;
2691  central_moments(4) = 1.0 / 80; // times (b - a)^4, which equals 1.
2692 
2693  for (int32 pow = 1; pow < central_moments.Dim(); pow++) {
2694  CuMatrix<Real> Mpow(M);
2695  Mpow.ApplyPow(pow);
2696  Real observed_moment = Mpow.Sum() / (rows * cols);
2697  // see http://en.wikipedia.org/wiki/Normal_distribution#Moments,
2698  // note that mu = 0 and sigma = 1.
2699  Real expected_moment = central_moments(pow);
2700  Real k = 20.0; // This is just a constant we use to give us some wiggle
2701  // room before rejecting the distribution... e.g. 10 sigma,
2702  // quite approximately.
2703  Real allowed_deviation = k / sqrt(static_cast<Real>(rows * cols));
2704  Real lower_bound = expected_moment - allowed_deviation,
2705  upper_bound = expected_moment + allowed_deviation;
2706  if (!(observed_moment >= lower_bound && observed_moment <= upper_bound)) {
2707  KALDI_LOG << "Random matrix is " << M;
2708  KALDI_ERR << "Bad observed " << pow << "'th moment " << observed_moment
2709  << ", expected " << expected_moment << ", allowed range "
2710  << lower_bound << " to " << upper_bound;
2711  }
2712  }
2713  }
2714 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestCuMatrixSetZeroAboveDiag()

static void kaldi::UnitTestCuMatrixSetZeroAboveDiag ( )
static

Definition at line 2738 of file cu-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), CuMatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetZeroAboveDiag().

2738  {
2739  for (int i = 1; i < 2; ++i) {
2740  MatrixIndexT dim = 10 * i + Rand() % 4 + (i == 9 ? 255 : 0);
2741  if (i == 8) dim = 0;
2742  CuMatrix<Real> A(dim, dim);
2743  A.SetRandn();
2744  Matrix<Real> A_orig(A);
2745  A.SetZeroAboveDiag();
2746  Matrix<Real> A_copy(A);
2747 
2748  for (int32 i = 0; i < dim; i++) {
2749  for (int32 j = 0; j < dim; j++) {
2750  Real aval = A_copy(i, j), aorigval = A_orig(i, j);
2751  KALDI_ASSERT(aval == (j > i ? 0.0 : aorigval));
2752  }
2753  }
2754  }
2755 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuMatrixSigmoid()

static void kaldi::UnitTestCuMatrixSigmoid ( )
static

Definition at line 219 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::MulElements(), Rand(), MatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::Sigmoid(), and MatrixBase< Real >::Sigmoid().

219  {
220  for (int32 i = 0; i < 2; i++) {
221  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
222  Matrix<Real> H(M, N);
223  H.SetRandn();
224  H.MulElements(H); // make numbers positive
225 
226  CuMatrix<Real> D(H);
227  CuMatrix<Real> E(M, N);
228 
229  E.Sigmoid(D);
230  H.Sigmoid(H);
231 
232  Matrix<Real> H2(E);
233 
234  KALDI_ASSERT(ApproxEqual(H, H2));
235  }
236 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSoftHinge()

static void kaldi::UnitTestCuMatrixSoftHinge ( )
static

Definition at line 270 of file cu-matrix-test.cc.

References ApproxEqual(), KALDI_ASSERT, MatrixBase< Real >::MulElements(), Rand(), MatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::SoftHinge(), and MatrixBase< Real >::SoftHinge().

270  {
271  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
272  Matrix<Real> H(M, N);
273  H.SetRandn();
274  H.MulElements(H); // make numbers positive
275 
276  CuMatrix<Real> D(H);
277  CuMatrix<Real> E(M, N);
278 
279  E.SoftHinge(D);
280  H.SoftHinge(H);
281 
282  Matrix<Real> H2(E);
283 
284  KALDI_ASSERT(ApproxEqual(H,H2));
285 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSumColumnRanges()

static void kaldi::UnitTestCuMatrixSumColumnRanges ( )
static

Definition at line 673 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, kUndefined, Rand(), MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SumColumnRanges().

673  {
674  for (int32 p = 0; p < 2; p++) {
675  MatrixIndexT num_cols1 = 10 + Rand() % 10,
676  num_cols2 = 10 + Rand() % 10,
677  num_rows = 10 + Rand() % 10;
678  Matrix<Real> src(num_rows, num_cols1);
679  Matrix<Real> dst(num_rows, num_cols2);
680  std::vector<Int32Pair> indices(num_cols2);
681  for (int32 i = 0; i < num_cols2; i++) {
682  indices[i].first = Rand() % num_cols1;
683  int32 headroom = num_cols1 - indices[i].first,
684  size = (Rand() % headroom) + 1;
685  indices[i].second = indices[i].first + size;
686  KALDI_ASSERT(indices[i].second >= indices[i].first &&
687  indices[i].second <= num_cols1 &&
688  indices[i].first >= 0);
689  // In the test we allow second == first.
690  }
691  src.SetRandn();
692  // Simple computation:
693  for (MatrixIndexT i = 0; i < num_rows; i++) {
694  for (MatrixIndexT j = 0; j < num_cols2; j++) {
695  int32 start = indices[j].first, end = indices[j].second;
696  Real sum = 0.0;
697  for (MatrixIndexT j2 = start; j2 < end; j2++)
698  sum += src(i, j2);
699  dst(i, j) = sum;
700  }
701  }
702  CuMatrix<Real> cu_src(src);
703  CuMatrix<Real> cu_dst(num_rows, num_cols2, kUndefined);
704  CuArray<Int32Pair> indices_tmp(indices);
705  cu_dst.SumColumnRanges(cu_src, indices_tmp);
706  Matrix<Real> dst2(cu_dst);
707  KALDI_ASSERT(ApproxEqual(dst, dst2));
708  }
709 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSymAddMat2()

static void kaldi::UnitTestCuMatrixSymAddMat2 ( )
static

Definition at line 1583 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMatMat(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, Rand(), CuMatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::SymAddMat2(), and CuMatrix< Real >::Transpose().

1583  {
1584  for (int32 i = 0; i < 2; i++) {
1585  int32 dimM = 10 + Rand() % 200, dimN = 10 + Rand() % 30;
1586  if (i == 8) {
1587  dimM = 0;
1588  dimN = 0;
1589  }
1590  CuMatrix<Real> M(dimM, dimM); // square matrix..
1591  CuMatrix<Real> N(dimM, dimN);
1592  M.SetRandn();
1593  N.SetRandn();
1594  MatrixTransposeType trans = (i % 2 == 0 ? kTrans : kNoTrans),
1595  other_trans = (trans == kTrans ? kNoTrans : kTrans);
1596  if (trans == kTrans) N.Transpose();
1597  CuMatrix<Real> M2(M);
1598  Real alpha = 0.3, beta = 1.75432;
1599  M.SymAddMat2(alpha, N, trans, beta);
1600 
1601  M2.AddMatMat(alpha, N, trans, N, other_trans, beta);
1602 
1603  CuTpMatrix<Real> T1(M), T2(M2);
1604  CuMatrix<Real> X1(T1), X2(T2); // so we can test equality.
1605  KALDI_ASSERT(ApproxEqual(X1, X2));
1606  KALDI_ASSERT(dimM == 0 || X1.Trace() != 0);
1607  }
1608 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixSymInvertPosDef()

static void kaldi::UnitTestCuMatrixSymInvertPosDef ( )
static

Definition at line 1613 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMatMat(), ApproxEqual(), rnnlm::i, SpMatrix< Real >::Invert(), CuMatrixBase< Real >::IsUnit(), KALDI_ASSERT, kNoTrans, kTakeLower, kTrans, Rand(), CuMatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::SymAddMat2(), CuMatrixBase< Real >::SymInvertPosDef(), SpMatrix< Real >::Trace(), and CuMatrix< Real >::Transpose().

1613  {
1614  for (int32 i = 0; i < 2; i++) {
1615  int32 dimM = 10 + Rand() % 200, dimN = dimM + 20;
1616  // dimN > dimM, so will be PSD almost surely.
1617  if (i == 8) {
1618  dimM = 0;
1619  dimN = 0;
1620  }
1621  if (i == 0) {
1622  dimM = 2;
1623  dimN = 5;
1624  }
1625  if (i == 1) {
1626  dimM = 9;
1627  dimN = 20;
1628  }
1629  CuMatrix<Real> M(dimM, dimM); // square matrix..
1630  CuMatrix<Real> N(dimM, dimN);
1631  N.SetRandn();
1632  MatrixTransposeType trans = (i % 2 == 0 ? kTrans : kNoTrans);
1633  // MatrixTranposeType other_trans = (trans == kTrans ? kNoTrans : kTrans);
1634 
1635  if (trans == kTrans) N.Transpose();
1636  CuMatrix<Real> M2(M);
1637  Real alpha = 0.3, beta = 1.75432;
1638  M.SymAddMat2(alpha, N, trans, beta);
1639  // M.AddMatMat(alpha, N, trans, N, other_trans, beta);
1640  CuSpMatrix<Real> spTemp(M, kTakeLower);
1641  SpMatrix<Real> S(spTemp);
1642  S.Invert();
1643  CuSpMatrix<Real> spTemp2(M, kTakeLower);
1644  CuMatrix<Real> M_orig(spTemp2);
1645  M.SymInvertPosDef();
1646  CuSpMatrix<Real> spTemp3(M, kTakeLower);
1647  CuMatrix<Real> M_inverted(spTemp3);
1648  CuMatrix<Real> M_prod(dimM, dimM);
1649  M_prod.AddMatMat(Real(1.0), M_orig, kNoTrans, M_inverted, kNoTrans, Real(0.0));
1650  KALDI_ASSERT(M_prod.IsUnit());
1651  CuSpMatrix<Real> spTemp4(M, kTakeLower);
1652  SpMatrix<Real> S2(spTemp4);
1653  KALDI_ASSERT(ApproxEqual(S, S2, (Real)0.1));
1654  KALDI_ASSERT(dimM == 0 || S.Trace() != 0);
1655  }
1656 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixTraceMatMat()

static void kaldi::UnitTestCuMatrixTraceMatMat ( )
static

Definition at line 76 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::Add(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, Rand(), CuMatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::SetRandUniform(), MatrixBase< Real >::Sum(), CuMatrixBase< Real >::Sum(), and TraceMatMat().

76  {
77  for (int32 i = 0; i < 2; i++) {
78  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
79  CuMatrix<Real> A(M, N);
80  A.SetRandUniform();
81  // Add bias to avoid numbers close to zero
82  A.Add(0.1);
83  if (i % 2 == 1) {
84  CuMatrix<Real> B(M, N);
85  B.SetRandn();
86  // add a bias to avoid numerical failure when comparing r2 and r3
87  B.Add(0.1);
88  Real r1 = TraceMatMat(A, B, kTrans),
91  Matrix<Real> X(B, kTrans);
92  KALDI_LOG << "Xsum = " << X.Sum();
93  Matrix<Real> Y(B, kTrans);
94  KALDI_LOG << "Ysum = " << Y.Sum();
95  KALDI_LOG << "Bsum = " << B.Sum();
96  KALDI_ASSERT(ApproxEqual(r1, r2));
97  KALDI_ASSERT(ApproxEqual(r2, r3));
98  } else {
99  CuMatrix<Real> B(N, M);
100  B.SetRandn();
101  Real r1 = TraceMatMat(A, B, kNoTrans),
104  KALDI_ASSERT(ApproxEqual(r1, r2));
105  KALDI_ASSERT(ApproxEqual(r2, r3));
106  }
107  }
108 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuMatrixTranspose()

static void kaldi::UnitTestCuMatrixTranspose ( )
static

Definition at line 1873 of file cu-matrix-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, kTrans, Rand(), CuMatrixBase< Real >::SetRandn(), and Matrix< Real >::Transpose().

1873  {
1874  for (int32 i = 1; i < 2; i++) {
1875  MatrixIndexT dimM = 5 * i + Rand() % 10,
1876  dimN = dimM;
1877  if (i % 2 == 0) dimN += 5;
1878 
1879  CuMatrix<Real> A(dimM, dimN);
1880  A.SetRandn();
1881  CuMatrix<Real> B(A, kTrans);
1882 
1883  Matrix<Real> hA(A);
1884  Matrix<Real> hB(B);
1885  hB.Transpose();
1886  KALDI_ASSERT(ApproxEqual(hA, hB));
1887  }
1888 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuPackedMatrixAddToDiag()

static void kaldi::UnitTestCuPackedMatrixAddToDiag ( )
static

Definition at line 195 of file cu-packed-matrix-test.cc.

References CuPackedMatrix< Real >::AddToDiag(), AssertDiagEqual(), rnnlm::i, Rand(), and PackedMatrix< Real >::SetRandn().

195  {
196  for (MatrixIndexT i = 1; i < 10; i++) {
197  MatrixIndexT dim = 5 * i + Rand() % 10;
198 
199  PackedMatrix<Real> A(dim);
200  A.SetRandn();
202 
203  Real value = Rand() % 50;
204  B.AddToDiag(value);
205 
206  AssertDiagEqual(A, B, value);
207  }
208 }
static void AssertDiagEqual(const PackedMatrix< Real > &A, const PackedMatrix< Real > &B, float value, float tol=0.001)
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed matrix: base class for triangular and symmetric matrices.
Definition: matrix-common.h:64
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Matrix for CUDA computing.
Definition: matrix-common.h:75

◆ UnitTestCuPackedMatrixConstructor()

static void kaldi::UnitTestCuPackedMatrixConstructor ( )
static

Definition at line 114 of file cu-packed-matrix-test.cc.

References AssertEqual(), rnnlm::i, and PackedMatrix< Real >::SetRandn().

114  {
115  for (MatrixIndexT i = 1; i < 10; i++) {
116  MatrixIndexT dim = 10 * i;
117 
118  PackedMatrix<Real> A(dim);
119  A.SetRandn();
122  AssertEqual(B, C);
123  }
124 }
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
Packed matrix: base class for triangular and symmetric matrices.
Definition: matrix-common.h:64
Matrix for CUDA computing.
Definition: matrix-common.h:75

◆ UnitTestCuPackedMatrixCopy()

static void kaldi::UnitTestCuPackedMatrixCopy ( )
static

Definition at line 127 of file cu-packed-matrix-test.cc.

References AssertEqual(), CuPackedMatrix< Real >::CopyFromPacked(), CuPackedMatrix< Real >::CopyToPacked(), rnnlm::i, and PackedMatrix< Real >::SetRandn().

127  {
128  for (MatrixIndexT i = 1; i < 10; i++) {
129  MatrixIndexT dim = 10 * i;
130 
131  PackedMatrix<Real> A(dim);
132  A.SetRandn();
134 
135  CuPackedMatrix<Real> C(dim);
136  C.CopyFromPacked(A);
137  CuPackedMatrix<Real> D(dim);
138  D.CopyFromPacked(B);
139  AssertEqual(C, D);
140 
141  PackedMatrix<Real> E(dim);
142  D.CopyToPacked(&E);
143  AssertEqual(A, E);
144  }
145 }
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
Packed matrix: base class for triangular and symmetric matrices.
Definition: matrix-common.h:64
Matrix for CUDA computing.
Definition: matrix-common.h:75

◆ UnitTestCuPackedMatrixScale()

static void kaldi::UnitTestCuPackedMatrixScale ( )
static

Definition at line 161 of file cu-packed-matrix-test.cc.

References AssertEqual(), rnnlm::i, Rand(), CuPackedMatrix< Real >::Scale(), PackedMatrix< Real >::Scale(), and PackedMatrix< Real >::SetRandn().

161  {
162  for (MatrixIndexT i = 1; i < 10; i++) {
163  MatrixIndexT dim = 5 * i + Rand() % 10;
164 
165  PackedMatrix<Real> A(dim);
166  A.SetRandn();
168 
169  Real scale_factor = 23.5896223;
170  A.Scale(scale_factor);
171  B.Scale(scale_factor);
172  AssertEqual(A, B);
173  }
174 }
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
Packed matrix: base class for triangular and symmetric matrices.
Definition: matrix-common.h:64
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Matrix for CUDA computing.
Definition: matrix-common.h:75

◆ UnitTestCuPackedMatrixScaleDiag()

static void kaldi::UnitTestCuPackedMatrixScaleDiag ( )
static

Definition at line 177 of file cu-packed-matrix-test.cc.

References AssertEqual(), rnnlm::i, Rand(), CuPackedMatrix< Real >::ScaleDiag(), PackedMatrix< Real >::ScaleDiag(), and PackedMatrix< Real >::SetRandn().

177  {
178  for (MatrixIndexT i = 1; i < 10; i++) {
179  MatrixIndexT dim = 5 * i + Rand() % 10;
180 
181  PackedMatrix<Real> A(dim);
182  A.SetRandn();
184 
185  Real scale_factor = 23.5896223;
186  A.ScaleDiag(scale_factor);
187  B.ScaleDiag(scale_factor);
188  AssertEqual(A, B);
189  }
190 }
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
Packed matrix: base class for triangular and symmetric matrices.
Definition: matrix-common.h:64
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Matrix for CUDA computing.
Definition: matrix-common.h:75

◆ UnitTestCuPackedMatrixSetUnit()

static void kaldi::UnitTestCuPackedMatrixSetUnit ( )
static

Definition at line 211 of file cu-packed-matrix-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, CuPackedMatrix< Real >::NumRows(), Rand(), and CuPackedMatrix< Real >::SetUnit().

211  {
212  for (MatrixIndexT i = 1; i < 10; i++) {
213  MatrixIndexT dim = 5 * i + Rand() % 10;
214 
215  CuPackedMatrix<Real> A(dim);
216  A.SetUnit();
217 
218  for (MatrixIndexT i = 0; i < A.NumRows(); i++) {
219  for (MatrixIndexT j = 0; j < A.NumRows(); j++) {
220  if (i != j) {
221  KALDI_ASSERT(A(i, j) == 0);
222  } else {
223  KALDI_ASSERT(A(i, j) == 1.0);
224  }
225  }
226  }
227  }
228 }
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Matrix for CUDA computing.
Definition: matrix-common.h:75

◆ UnitTestCuPackedMatrixTrace()

static void kaldi::UnitTestCuPackedMatrixTrace ( )
static

Definition at line 148 of file cu-packed-matrix-test.cc.

References AssertEqual(), rnnlm::i, Rand(), PackedMatrix< Real >::SetRandn(), PackedMatrix< Real >::Trace(), and CuPackedMatrix< Real >::Trace().

148  {
149  for (MatrixIndexT i = 1; i < 10; i++) {
150  MatrixIndexT dim = 5 * i + Rand() % 10;
151 
152  PackedMatrix<Real> A(dim);
153  A.SetRandn();
155 
156  AssertEqual(A.Trace(), B.Trace());
157  }
158 }
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
Packed matrix: base class for triangular and symmetric matrices.
Definition: matrix-common.h:64
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Matrix for CUDA computing.
Definition: matrix-common.h:75

◆ UnitTestCuSigmoid()

static void kaldi::UnitTestCuSigmoid ( )
static

Definition at line 2224 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::Sigmoid().

2224  {
2225  Matrix<Real> Hi(100,111);
2226  Matrix<Real> Ho(100,111);
2227  Hi.SetRandn();
2228 
2229  CuMatrix<Real> Di(100,111);
2230  CuMatrix<Real> Do(100,111);
2231  Di.CopyFromMat(Hi);
2232 
2233  //gpu
2234  Do.Sigmoid(Di);
2235  //cpu
2236  for(MatrixIndexT r=0; r < Hi.NumRows(); r++) {
2237  for(MatrixIndexT c=0; c < Hi.NumCols(); c++) {
2238  Ho(r, c) = 1.0/(1.0+exp(-Hi(r, c)));
2239  }
2240  }
2241 
2242  Matrix<Real> Ho2(100,111);
2243  Do.CopyToMat(&Ho2);
2244 
2245  KALDI_ASSERT(ApproxEqual(Ho,Ho2));
2246 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuSoftmax()

static void kaldi::UnitTestCuSoftmax ( )
static

Definition at line 2370 of file cu-matrix-test.cc.

References ApproxEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::Row(), MatrixBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SoftMaxPerRow().

2370  {
2371 
2372  for (int32 i = 0; i < 4; i++) {
2373  int row = 10 + Rand() % 40;
2374  int col = 10 + Rand() % 50;
2375 
2376  Matrix<Real> Hi(row,col);
2377  Matrix<Real> Ho(row,col);
2378  Hi.SetRandn();
2379  Hi.Scale(5.0);
2380 
2381  CuMatrix<Real> Di(row, col);
2382  CuMatrix<Real> Do(row, col);
2383  Di.CopyFromMat(Hi);
2384 
2385  //gpu
2386  if (i % 2 == 0) {
2387  Do.SoftMaxPerRow(Di);
2388  } else {
2389  // in-place
2390  Do.CopyFromMat(Di);
2391  Do.SoftMaxPerRow(Do);
2392  }
2393  //cpu
2394  Ho.CopyFromMat(Hi);
2395  for(MatrixIndexT r=0; r<Ho.NumRows(); r++) {
2396  Ho.Row(r).ApplySoftMax();
2397  }
2398 
2399  Matrix<Real> Ho2(Do);
2400 
2401  KALDI_ASSERT(ApproxEqual(Ho,Ho2,(Real)0.00001));
2402  }
2403 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuSparseMatrixConstructFromIndexes()

static void kaldi::UnitTestCuSparseMatrixConstructFromIndexes ( )
static

Definition at line 34 of file cu-sparse-matrix-test.cc.

References AssertEqual(), CuSparseMatrix< Real >::CopyToMat(), SparseMatrix< Real >::CopyToMat(), rnnlm::i, kNoTrans, kTrans, CuSparseMatrix< Real >::NumCols(), SparseMatrix< Real >::NumCols(), CuSparseMatrix< Real >::NumRows(), SparseMatrix< Real >::NumRows(), and Rand().

34  {
35  for (int32 i = 0; i < 2; i++) {
36  MatrixIndexT row = 10 + Rand() % 40;
37  MatrixIndexT col = 10 + Rand() % 50;
38 
39  MatrixTransposeType trans = (i % 2 == 0 ? kNoTrans : kTrans);
40 
41  std::vector<int32> idx(row);
42  Vector<Real> weights(row);
43  for (int i = 0; i < row; ++i) {
44  idx[i] = Rand() % col;
45  weights(i) = Rand() % 100;
46  }
47  CuArray<int32> cuidx(idx);
48  CuVector<Real> cuweights(weights);
49 
50  // construct smat
51  SparseMatrix<Real> smat1(idx, col, trans);
52  CuSparseMatrix<Real> cusmat1(cuidx, col, trans);
53 
54  // copy to mat
55  Matrix<Real> mat1(smat1.NumRows(), smat1.NumCols());
56  smat1.CopyToMat(&mat1);
57  CuMatrix<Real> cumat1(cusmat1.NumRows(), cusmat1.NumCols());
58  cusmat1.CopyToMat(&cumat1);
59 
60  // compare
61  Matrix<Real> mat1ver2(cumat1);
62  AssertEqual(mat1, mat1ver2, 0.00001);
63 
64  // construct smat with weights
65  SparseMatrix<Real> smat2(idx, weights, col, trans);
66  CuSparseMatrix<Real> cusmat2(cuidx, cuweights, col, trans);
67 
68  // copy to mat
69  Matrix<Real> mat2(smat2.NumRows(), smat2.NumCols());
70  smat2.CopyToMat(&mat2);
71  CuMatrix<Real> cumat2(cusmat2.NumRows(), cusmat2.NumCols());
72  cusmat2.CopyToMat(&cumat2);
73 
74  // compare
75  Matrix<Real> mat2ver2(cumat2);
76  AssertEqual(mat2, mat2ver2, 0.00001);
77  }
78 }
void CopyToMat(MatrixBase< OtherReal > *dst, MatrixTransposeType trans=kNoTrans) const
Definition: cu-matrix.cc:447
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSparseMatrixCopyToSmat()

static void kaldi::UnitTestCuSparseMatrixCopyToSmat ( )
static

Definition at line 202 of file cu-sparse-matrix-test.cc.

References AssertEqual(), CuSparseMatrix< Real >::CopyToMat(), CuSparseMatrix< Real >::CopyToSmat(), rnnlm::i, Rand(), and SparseMatrix< Real >::SetRandn().

202  {
203  for (int32 i = 0; i < 2; i++) {
204  MatrixIndexT row = 10 + Rand() % 40;
205  MatrixIndexT col = 10 + Rand() % 50;
206 
207  SparseMatrix<Real> smat1(row, col);
208  smat1.SetRandn(0.8);
209  CuSparseMatrix<Real> cu_smat1(smat1);
210 
211  SparseMatrix<Real> smat2(col, row);
212  cu_smat1.CopyToSmat(&smat2);
213  CuSparseMatrix<Real> cu_smat2(smat2);
214 
215  CuMatrix<Real> mat1(row, col);
216  CuMatrix<Real> mat2(row, col);
217 
218  cu_smat1.CopyToMat(&mat1);
219  cu_smat2.CopyToMat(&mat2);
220 
221  AssertEqual(mat1, mat2, 0.00001);
222  }
223 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSparseMatrixFrobeniusNorm()

static void kaldi::UnitTestCuSparseMatrixFrobeniusNorm ( )
static

Definition at line 181 of file cu-sparse-matrix-test.cc.

References AssertEqual(), CuSparseMatrix< Real >::CopyToMat(), CuSparseMatrix< Real >::FrobeniusNorm(), CuMatrixBase< Real >::FrobeniusNorm(), rnnlm::i, Rand(), SparseMatrix< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

181  {
182  for (int32 i = 0; i < 2; i++) {
183  MatrixIndexT row = 10 + Rand() % 40;
184  MatrixIndexT col = 10 + Rand() % 50;
185 
186  CuMatrix<Real> mat(row, col);
187  mat.SetRandn();
188 
189  SparseMatrix<Real> smat(row, col);
190  smat.SetRandn(0.8);
191  CuSparseMatrix<Real> cu_smat(smat);
192 
193  cu_smat.CopyToMat(&mat);
194 
195  Real sum1 = cu_smat.FrobeniusNorm();
196  Real sum2 = mat.FrobeniusNorm();
197  AssertEqual(sum1, sum2, 0.00001);
198  }
199 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSparseMatrixSelectRowsAndTranspose()

static void kaldi::UnitTestCuSparseMatrixSelectRowsAndTranspose ( )
static

Definition at line 82 of file cu-sparse-matrix-test.cc.

References AssertEqual(), CuSparseMatrix< Real >::CopyToMat(), rnnlm::i, kTrans, CuSparseMatrix< Real >::NumCols(), CuSparseMatrix< Real >::NumRows(), Rand(), CuSparseMatrix< Real >::SelectRows(), SparseMatrix< Real >::SelectRows(), and SparseMatrix< Real >::SetRandn().

82  {
83  for (int32 i = 0; i < 2; i++) {
84  MatrixIndexT row = 10 + Rand() % 40;
85  MatrixIndexT col = 10 + Rand() % 50;
86 
87  SparseMatrix<Real> sp_input(row, col);
88  sp_input.SetRandn(0.8);
89  CuSparseMatrix<Real> cusp_input(sp_input);
90 
91  std::vector<int32> idx(row + col);
92  for (auto && e : idx) {
93  e = Rand() % row;
94  }
95  CuArray<int32> cu_idx(idx);
96 
97  // select on cpu
98  SparseMatrix<Real> sp_selected2;
99  sp_selected2.SelectRows(idx, sp_input);
100  // select on gpu
101  CuSparseMatrix<Real> cusp_selected;
102  cusp_selected.SelectRows(cu_idx, cusp_input);
103 
104  // transpose by CopyToMat
105  CuSparseMatrix<Real> cusp_selected2(sp_selected2);
106  CuMatrix<Real> cu_selected2_trans(cusp_selected2.NumCols(),
107  cusp_selected2.NumRows());
108  cusp_selected2.CopyToMat(&cu_selected2_trans, kTrans);
109  // transpose by Constructor
110  CuSparseMatrix<Real> cusp_selected_trans(cusp_selected, kTrans);
111  CuMatrix<Real> cu_selected_trans(cusp_selected_trans.NumRows(),
112  cusp_selected_trans.NumCols());
113  cusp_selected_trans.CopyToMat(&cu_selected_trans);
114 
115  CuMatrix<Real> cu_selected(row+col, col);
116  CuMatrix<Real> cu_selected2(row+col, col);
117  cusp_selected.CopyToMat(&cu_selected);
118  cusp_selected2.CopyToMat(&cu_selected2);
119 
120  AssertEqual(cu_selected, cu_selected2, 0.00001);
121  AssertEqual(cu_selected_trans, cu_selected2_trans, 0.00001);
122  }
123 }
void SelectRows(const std::vector< int32 > &row_indexes, const SparseMatrix< Real > &smat_other)
Select a subset of the rows of a SparseMatrix.
void CopyToMat(CuMatrixBase< OtherReal > *dest, MatrixTransposeType trans=kNoTrans) const
void CopyToMat(MatrixBase< OtherReal > *dst, MatrixTransposeType trans=kNoTrans) const
Definition: cu-matrix.cc:447
void SelectRows(const CuArray< int32 > &row_indexes, const CuSparseMatrix< Real > &smat_other)
Select a subset of the rows of a CuSparseMatrix.
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSparseMatrixSum()

static void kaldi::UnitTestCuSparseMatrixSum ( )
static

Definition at line 160 of file cu-sparse-matrix-test.cc.

References CuSparseMatrix< Real >::CopyToMat(), rnnlm::i, KALDI_ASSERT, Rand(), SparseMatrix< Real >::SetRandn(), CuMatrixBase< Real >::SetRandn(), CuSparseMatrix< Real >::Sum(), and CuMatrixBase< Real >::Sum().

160  {
161  for (int32 i = 0; i < 2; i++) {
162  MatrixIndexT row = 10 + Rand() % 40;
163  MatrixIndexT col = 10 + Rand() % 50;
164 
165  CuMatrix<Real> mat(row, col);
166  mat.SetRandn();
167 
168  SparseMatrix<Real> smat(row, col);
169  smat.SetRandn(0.8);
170  CuSparseMatrix<Real> cu_smat(smat);
171 
172  cu_smat.CopyToMat(&mat);
173 
174  Real sum1 = cu_smat.Sum();
175  Real sum2 = mat.Sum();
176  KALDI_ASSERT(fabs(sum1 - sum2) < 1.0e-04);
177  }
178 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuSparseMatrixSwap()

static void kaldi::UnitTestCuSparseMatrixSwap ( )
static

Definition at line 226 of file cu-sparse-matrix-test.cc.

References AssertEqual(), CuSparseMatrix< Real >::CopyToMat(), rnnlm::i, CuSparseMatrix< Real >::NumCols(), SparseMatrix< Real >::NumCols(), CuSparseMatrix< Real >::NumRows(), SparseMatrix< Real >::NumRows(), Rand(), CuMatrix< Real >::Resize(), SparseMatrix< Real >::SetRandn(), and CuSparseMatrix< Real >::Swap().

226  {
227  for (int32 i = 0; i < 2; i++) {
228  MatrixIndexT row = 10 + Rand() % 40;
229  MatrixIndexT col = 10 + Rand() % 50;
230 
231  CuMatrix<Real> mat1, mat2, mat3, mat4;
232 
233  SparseMatrix<Real> smat1(row, col);
234  smat1.SetRandn(0.8);
235  SparseMatrix<Real> smat2 = smat1;
236  mat2.Resize(smat2.NumRows(), smat2.NumCols());
237  CuSparseMatrix<Real> tmp1(smat2);
238  tmp1.CopyToMat(&mat2);
239 
240  SparseMatrix<Real> smat3(col, row);
241  smat3.SetRandn(0.5);
242  CuSparseMatrix<Real> cu_smat1(smat3);
243  CuSparseMatrix<Real> cu_smat2 = cu_smat1;
244  mat4.Resize(cu_smat2.NumRows(), cu_smat2.NumCols());
245  cu_smat2.CopyToMat(&mat4);
246 
247  cu_smat1.Swap(&smat1);
248 
249  mat1.Resize(smat1.NumRows(), smat1.NumCols());
250  mat3.Resize(cu_smat1.NumRows(), cu_smat1.NumCols());
251  CuSparseMatrix<Real> tmp2(smat1);
252  tmp2.CopyToMat(&mat1);
253  cu_smat1.CopyToMat(&mat3);
254 
255  AssertEqual(mat3, mat2, 0.00001);
256  AssertEqual(mat1, mat4, 0.00001);
257 
258  cu_smat2.Swap(&cu_smat1);
259 
260  mat1.Resize(cu_smat1.NumRows(), cu_smat1.NumCols());
261  cu_smat1.CopyToMat(&mat1);
262  mat2.Resize(cu_smat2.NumRows(), cu_smat2.NumCols());
263  cu_smat2.CopyToMat(&mat2);
264 
265  AssertEqual(mat3, mat2, 0.00001);
266  AssertEqual(mat1, mat4, 0.00001);
267  }
268 }
MatrixIndexT NumRows() const
void CopyToMat(CuMatrixBase< OtherReal > *dest, MatrixTransposeType trans=kNoTrans) const
void Swap(SparseMatrix< Real > *smat)
Swap with CPU-based matrix.
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
MatrixIndexT NumCols() const
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
MatrixIndexT NumRows() const
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void Resize(MatrixIndexT rows, MatrixIndexT cols, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Allocate the memory.
Definition: cu-matrix.cc:50
MatrixIndexT NumCols() const

◆ UnitTestCuSparseMatrixTraceMatSmat()

static void kaldi::UnitTestCuSparseMatrixTraceMatSmat ( )
static

Definition at line 126 of file cu-sparse-matrix-test.cc.

References AssertEqual(), CuSparseMatrix< Real >::CopyToMat(), rnnlm::i, kNoTrans, kTrans, Rand(), SparseMatrix< Real >::SetRandn(), CuMatrixBase< Real >::SetRandn(), TraceMatMat(), and TraceMatSmat().

126  {
127  for (int32 i = 0; i < 2; i++) {
128  MatrixIndexT row = 10 + Rand() % 40;
129  MatrixIndexT col = 10 + Rand() % 50;
130 
131  CuMatrix<Real> mat1(row, col);
132  CuMatrix<Real> mat2(col, row);
133  CuMatrix<Real> mat3(row, col);
134  mat1.SetRandn();
135  mat2.SetRandn();
136  mat3.SetRandn();
137 
138  SparseMatrix<Real> smat1(row, col);
139  SparseMatrix<Real> smat2(col, row);
140  smat1.SetRandn(0.8);
141  smat2.SetRandn(0.8);
142  CuSparseMatrix<Real> cu_smat1x(smat1);
143  CuSparseMatrix<Real> cu_smat1(cu_smat1x); // Test constructor.
144  CuSparseMatrix<Real> cu_smat2(smat2);
145 
146  cu_smat1.CopyToMat(&mat1);
147  cu_smat2.CopyToMat(&mat2);
148 
149  Real trace1 = TraceMatMat(mat3, mat1, kTrans);
150  Real trace2 = TraceMatSmat(mat3, cu_smat1, kTrans);
151  AssertEqual(trace1, trace2, 0.00001);
152 
153  trace1 = TraceMatMat(mat3, mat2, kNoTrans);
154  trace2 = TraceMatSmat(mat3, cu_smat2, kNoTrans);
155  AssertEqual(trace1, trace2, 0.00001);
156  }
157 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Real TraceMatSmat(const MatrixBase< Real > &A, const SparseMatrix< Real > &B, MatrixTransposeType trans)

◆ UnitTestCuSpMatrixAddMat2()

static void kaldi::UnitTestCuSpMatrixAddMat2 ( )
static

Definition at line 206 of file cu-sp-matrix-test.cc.

References CuSpMatrix< Real >::AddMat2(), SpMatrix< Real >::AddMat2(), AssertEqual(), CuSpMatrix< Real >::CopyToSp(), rnnlm::i, kTrans, Rand(), PackedMatrix< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

206  {
207  for (MatrixIndexT i = 1; i < 10; i++) {
208  MatrixIndexT dim_row = 15 * i + Rand() % 10;
209  MatrixIndexT dim_col = 7 *i + Rand() % 10;
210  Matrix<Real> A(dim_row, dim_col);
211  A.SetRandn();
212  CuMatrix<Real> B(A);
213 
214  SpMatrix<Real> C(dim_col);
215  C.SetRandn();
216  CuSpMatrix<Real> D(C);
217 
218  const Real alpha = 2.0;
219  const Real beta = 3.0;
220 
221  C.AddMat2(alpha, A, kTrans, beta);
222  D.AddMat2(alpha, B, kTrans, beta);
223 
224  SpMatrix<Real> E(dim_col);
225  D.CopyToSp(&E);
226 
227  AssertEqual(C, E);
228  }
229 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixAddSp() [1/2]

static void kaldi::UnitTestCuSpMatrixAddSp ( )
static

Definition at line 232 of file cu-sp-matrix-test.cc.

References CuSpMatrix< Real >::AddSp(), SpMatrix< Real >::AddSp(), AssertEqual(), CuSpMatrix< Real >::CopyToSp(), rnnlm::i, Rand(), and PackedMatrix< Real >::SetRandn().

232  {
233  for (MatrixIndexT i = 1; i < 50; i++) {
234  MatrixIndexT dim = 7 * i + Rand() % 10;
235 
236  SpMatrix<Real> A(dim);
237  A.SetRandn();
238  CuSpMatrix<Real> B(A);
239 
240  SpMatrix<Real> C(dim);
241  C.SetRandn();
242  const CuSpMatrix<Real> D(C);
243 
244  const Real alpha = 2.0;
245 
246  A.AddSp(alpha, C);
247  B.AddSp(alpha, D);
248 
249  SpMatrix<Real> E(dim);
250  B.CopyToSp(&E);
251 
252  AssertEqual(A, E);
253  }
254 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixAddSp() [2/2]

static void kaldi::UnitTestCuSpMatrixAddSp ( )
static

Definition at line 323 of file cu-sp-matrix-test.cc.

References CuSpMatrix< Real >::AddSp(), SpMatrix< Real >::AddSp(), AssertEqual(), rnnlm::i, Rand(), and PackedMatrix< Real >::SetRandn().

323  {
324  for (MatrixIndexT i = 1; i < 10; i++) {
325  MatrixIndexT dim = 100 * i + Rand() % 255;
326 
327  SpMatrix<Real> A(dim);
328  A.SetRandn();
329  const CuSpMatrix<Real> B(A);
330  SpMatrix<OtherReal> C(dim);
331  C.SetRandn();
332  const CuSpMatrix<OtherReal> D(C);
333 
334  A.AddSp(1.0, C);
335  B.AddSp(1.0, D);
336 
337  AssertEqual(A, B);
338 
339  }
340 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixAddToDiag()

static void kaldi::UnitTestCuSpMatrixAddToDiag ( )
static

Definition at line 110 of file cu-sp-matrix-test.cc.

References CuPackedMatrix< Real >::AddToDiag(), PackedMatrix< Real >::AddToDiag(), AssertEqual(), CuSpMatrix< Real >::CopyToSp(), rnnlm::i, and PackedMatrix< Real >::SetRandn().

110  {
111  for (MatrixIndexT i = 1; i < 10; i++) {
112  MatrixIndexT dim = 10*i;
113  SpMatrix<Real> A(dim);
114  A.SetRandn();
115  CuSpMatrix<Real> B(A);
116 
117  Matrix<Real> D(A);
118  A.AddToDiag(i);
119 
120  CuMatrix<Real> C(B);
121  B.AddToDiag(i);
122 
123  SpMatrix<Real> E(dim);
124  B.CopyToSp(&E);
125 
126  AssertEqual(A, E);
127  }
128 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixAddVec2()

static void kaldi::UnitTestCuSpMatrixAddVec2 ( )
static

Definition at line 183 of file cu-sp-matrix-test.cc.

References CuSpMatrix< Real >::AddVec2(), SpMatrix< Real >::AddVec2(), AssertEqual(), CuSpMatrix< Real >::CopyToSp(), rnnlm::i, Rand(), RandGauss(), VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

183  {
184  for (int32 i = 0; i < 50; i++) {
185  MatrixIndexT dim = 1 + Rand() % 200;
186  SpMatrix<Real> A(dim);
187  A.SetRandn();
188  CuSpMatrix<Real> B(A);
189 
190  Vector<Real> C(dim);
191  C.SetRandn();
192  CuVector<Real> D(C);
193  Real alpha = RandGauss();
194 
195  A.AddVec2(alpha, C);
196  B.AddVec2(alpha, D);
197 
198  SpMatrix<Real> E(dim);
199  B.CopyToSp(&E);
200 
201  AssertEqual(A, E);
202  }
203 }
Packed symetric matrix class.
Definition: matrix-common.h:62
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixApproxEqual()

static void kaldi::UnitTestCuSpMatrixApproxEqual ( )
static

Definition at line 73 of file cu-sp-matrix-test.cc.

References SpMatrix< Real >::AddSp(), SpMatrix< Real >::FrobeniusNorm(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), and PackedMatrix< Real >::SetRandn().

73  {
74 
75  for (int32 i = 0; i < 10; i++) {
76  int32 dim = 1 + Rand() % 10;
77  SpMatrix<Real> A(dim), B(dim);
78  A.SetRandn();
79  B.SetRandn();
80  BaseFloat threshold = 0.01;
81  for (int32 j = 0; j < 20; j++, threshold *= 1.3) {
82  bool b1 = A.ApproxEqual(B, threshold);
83  SpMatrix<Real> diff(A);
84  diff.AddSp(-1.0, B);
85  bool b2 = (diff.FrobeniusNorm() < threshold * std::max(A.FrobeniusNorm(),
86  B.FrobeniusNorm()));
87  KALDI_ASSERT(b1 == b2);
88  }
89  }
90 
91 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuSpMatrixConstructor()

static void kaldi::UnitTestCuSpMatrixConstructor ( )
static

Definition at line 44 of file cu-sp-matrix-test.cc.

References AssertEqual(), CuSpMatrix< Real >::CopyToSp(), rnnlm::i, SpMatrix< Real >::IsUnit(), KALDI_ASSERT, kTakeLower, PackedMatrix< Real >::SetDiag(), MatrixBase< Real >::SetRandn(), and PackedMatrix< Real >::SetZero().

44  {
45  for (MatrixIndexT i = 1; i < 10; i++) {
46  MatrixIndexT dim = 10 * i;
47 
48  Matrix<Real> A(dim, dim);
49  A.SetRandn();
51 
52  CuMatrix<Real> C(A);
54 
55  SpMatrix<Real> E(dim);
56  D.CopyToSp(&E);
57 
58  SpMatrix<Real> F(D);
59 
60  AssertEqual(F, B);
61  //added by hxu, to test copy from SpMatrix to CuSpMatrix
62 
63  AssertEqual(B, E);
64 
65  KALDI_ASSERT(!B.IsUnit());
66  B.SetZero();
67  B.SetDiag(1.0);
68  KALDI_ASSERT(B.IsUnit());
69  }
70 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixCopyFromMat() [1/2]

static void kaldi::UnitTestCuSpMatrixCopyFromMat ( int32  dim,
SpCopyType  copy_type 
)
static

Definition at line 84 of file cu-sp-matrix-speed-test.cc.

References CuSpMatrix< Real >::CopyFromMat(), Timer::Elapsed(), KALDI_LOG, kTakeLower, and kTakeUpper.

84  {
85  BaseFloat time_in_secs = 0.01;
86  int32 iter = 0;
87  Timer tim;
88  CuMatrix<Real> A(dim, dim);
89  CuSpMatrix<Real> S(dim);
90 
91  for (;tim.Elapsed() < time_in_secs; iter++) {
92  S.CopyFromMat(A, copy_type);
93  }
94  BaseFloat fdim = dim;
95  BaseFloat gflops = (fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
96  KALDI_LOG << "For CuSpMatrix::CopyFromMat" << NameOf<Real>()
97  << ", with copy-type "
98  <<(copy_type == kTakeLower ? "kTakeLower" :
99  (copy_type == kTakeUpper ? "kTakeUpper" :
100  "kTakeMeanAndCheck")) << " and dim = "
101  << dim << ", speed was " << gflops << " gigaflops.";
102 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestCuSpMatrixCopyFromMat() [2/2]

static void kaldi::UnitTestCuSpMatrixCopyFromMat ( )
static

Definition at line 132 of file cu-sp-matrix-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, KALDI_ERR, kTakeLower, kTakeMean, kTakeUpper, Rand(), CuMatrixBase< Real >::SetRandn(), and SpMatrix< Real >::Trace().

132  {
133  for (MatrixIndexT i = 1; i < 10; i++) {
134  SpCopyType copy_type = (i % 3 == 0 ? kTakeMean :
135  (i % 3 == 1 ? kTakeLower : kTakeUpper));
136  MatrixIndexT dim = 10 * i + Rand() % 5;
137  CuMatrix<Real> A(dim, dim);
138  A.SetRandn();
139  Matrix<Real> A2(A);
140 
141  CuSpMatrix<Real> B(A, copy_type);
142  SpMatrix<Real> B2(A2, copy_type);
143  SpMatrix<Real> B3(B);
144  if (!ApproxEqual(B2, B3) ) {
145  KALDI_ERR << "Matrices differ, A = " << A << ", B2 = " << B2 << ", B3(CUDA) = " << B3;
146  }
147  KALDI_ASSERT(B3.Trace() != 0);
148  }
149 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuSpMatrixInvert() [1/2]

static void kaldi::UnitTestCuSpMatrixInvert ( int32  dim)
static

Definition at line 43 of file cu-sp-matrix-speed-test.cc.

References CuSpMatrix< Real >::AddMat2(), CuPackedMatrix< Real >::AddToDiag(), AssertEqual(), CuSpMatrix< Real >::CopyToSp(), Timer::Elapsed(), CuSpMatrix< Real >::Invert(), KALDI_ASSERT, KALDI_LOG, kTrans, CuPackedMatrix< Real >::SetRandn(), and CuPackedMatrix< Real >::Trace().

43  {
44  BaseFloat time_in_secs = 0.01;
45  int32 iter = 0;
46  Timer tim;
47  CuSpMatrix<Real> A(dim);
48  A.SetRandn();
49  for (;tim.Elapsed() < time_in_secs; iter++) {
50  KALDI_ASSERT(A.Trace() != 0.0); // true with probability 1...
51  CuSpMatrix<Real> B(A);
52 
53  if (iter > 0) {
54  B.Invert();
55  } else { // do some more testing...
56 
57  CuMatrix<Real> D(A);
58  A.AddMat2(1.0, D, kTrans, 1.0);
59  A.AddToDiag(0.1 * dim);
60 
61  CuMatrix<Real> C(B);
62  B.AddMat2(1.0, C, kTrans, 1.0);
63  B.AddToDiag(0.1 * dim);
64 
65  A.Invert();
66  B.Invert();
67 
68  SpMatrix<Real> E(dim);
69  B.CopyToSp(&E);
70 
71  SpMatrix<Real> A2(A);
72  AssertEqual(A2, E);
73  }
74  }
75  BaseFloat fdim = dim;
76  BaseFloat gflops = (fdim * fdim * fdim * iter) / (tim.Elapsed() * 1.0e+09);
77  KALDI_LOG << "For CuSpMatrix::Invert" << NameOf<Real>() << ", for dim = "
78  << dim << ", speed was " << gflops << " gigaflops.";
79 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestCuSpMatrixInvert() [2/2]

static void kaldi::UnitTestCuSpMatrixInvert ( )
static

Definition at line 152 of file cu-sp-matrix-test.cc.

References CuSpMatrix< Real >::AddMat2(), SpMatrix< Real >::AddMat2(), CuMatrixBase< Real >::AddMatMat(), CuPackedMatrix< Real >::AddToDiag(), PackedMatrix< Real >::AddToDiag(), AssertEqual(), rnnlm::i, CuSpMatrix< Real >::Invert(), SpMatrix< Real >::Invert(), CuMatrixBase< Real >::IsUnit(), KALDI_ASSERT, kNoTrans, kTrans, Rand(), CuPackedMatrix< Real >::SetRandn(), and CuPackedMatrix< Real >::Trace().

152  {
153  for (MatrixIndexT i = 1; i < 10; i++) {
154  MatrixIndexT dim = 10*i + Rand() % 5;
155  CuSpMatrix<Real> A(dim);
156  A.SetRandn();
157  KALDI_ASSERT(A.Trace() != 0.0); // true with probability 1...
158  SpMatrix<Real> B(A);
159 
160  CuMatrix<Real> D(A);
161  A.AddMat2(1.0, D, kTrans, 1.0);
162  A.AddToDiag(i);
163 
164  Matrix<Real> C(B);
165  B.AddMat2(1.0, C, kTrans, 1.0);
166  B.AddToDiag(i);
167 
168  CuSpMatrix<Real> Acopy(A);
169  A.Invert();
170  B.Invert();
171 
172  SpMatrix<Real> A2(A);
173  AssertEqual(A2, B);
174 
175  CuMatrix<Real> I(dim, dim);
176  I.AddMatMat(1.0, CuMatrix<Real>(Acopy), kNoTrans, CuMatrix<Real>(A), kNoTrans, 0.0);
177  KALDI_ASSERT(I.IsUnit(0.01));
178  }
179 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixIO()

static void kaldi::UnitTestCuSpMatrixIO ( )
static

Definition at line 302 of file cu-sp-matrix-test.cc.

References AssertEqual(), rnnlm::i, Rand(), CuPackedMatrix< Real >::Read(), CuPackedMatrix< Real >::SetRandn(), and CuPackedMatrix< Real >::Write().

302  {
303  for (int32 i = 0; i < 10; i++) {
304  int32 dimM = Rand() % 255;
305  if (i % 5 == 0) { dimM = 0; }
306  CuSpMatrix<Real> mat(dimM);
307  mat.SetRandn();
308  std::ostringstream os;
309  bool binary = (i % 4 < 2);
310  mat.Write(os, binary);
311 
312  CuSpMatrix<Real> mat2;
313  std::istringstream is(os.str());
314  mat2.Read(is, binary);
315  AssertEqual(mat, mat2);
316  }
317 }
kaldi::int32 int32
void Read(std::istream &in, bool binary)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuSpMatrixOperator()

static void kaldi::UnitTestCuSpMatrixOperator ( )
static

Definition at line 96 of file cu-sp-matrix-test.cc.

References CuSpMatrix< Real >::CopyFromSp(), rnnlm::i, rnnlm::j, KALDI_ASSERT, PackedMatrix< Real >::NumRows(), and PackedMatrix< Real >::SetRandn().

96  {
97  SpMatrix<Real> A(100);
98  A.SetRandn();
99 
100  CuSpMatrix<Real> B(100);
101  B.CopyFromSp(A);
102 
103  for (MatrixIndexT i = 0; i < A.NumRows(); i++) {
104  for (MatrixIndexT j = 0; j <= i; j++)
105  KALDI_ASSERT(std::abs(A(i, j) - B(i, j)) < 0.0001);
106  }
107 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuSpMatrixSetUnit()

void kaldi::UnitTestCuSpMatrixSetUnit ( )

Definition at line 275 of file cu-sp-matrix-test.cc.

References CuPackedMatrix< Real >::AddToDiag(), AssertEqual(), SpMatrix< Real >::FrobeniusNorm(), rnnlm::i, KALDI_LOG, Rand(), CuPackedMatrix< Real >::SetRandn(), PackedMatrix< Real >::SetUnit(), and CuPackedMatrix< Real >::SetZero().

275  {
276  for (MatrixIndexT i = 1; i < 10; i++) {
277  MatrixIndexT dim = 100 * i + Rand() % 255;
278  if (i % 5 == 0) dim = 0;
279  CuSpMatrix<Real> S1(dim), S2(dim), S4(dim);
280  S1.SetRandn();
281  S2.SetRandn();
282  S4.SetRandn();
283  SpMatrix<Real> S3(dim);
284  S3.SetUnit();
285  S1.SetUnit();
286  S2.SetZero();
287  S2.SetDiag(1.0);
288  S4.SetZero();
289  S4.AddToDiag(0.4);
290  S4.AddToDiag(0.6);
291  CuSpMatrix<Real> cu_S3(S3);
292  KALDI_LOG << "S1 norm is " << S1.FrobeniusNorm();
293  KALDI_LOG << "S2 norm is " << S2.FrobeniusNorm();
294  KALDI_LOG << "S3 norm is " << S3.FrobeniusNorm();
295  AssertEqual(S1, cu_S3);
296  AssertEqual(S2, cu_S3);
297  AssertEqual(S4, cu_S3);
298  }
299 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestCuSpMatrixTraceSpSp()

static void kaldi::UnitTestCuSpMatrixTraceSpSp ( )
static

Definition at line 257 of file cu-sp-matrix-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, Rand(), PackedMatrix< Real >::SetRandn(), and TraceSpSp().

257  {
258  for (MatrixIndexT i = 1; i < 2; i++) {
259  MatrixIndexT dim = 100 + Rand() % 255;
260 
261  SpMatrix<Real> A(dim);
262  A.SetRandn();
263  const CuSpMatrix<Real> B(A);
264  SpMatrix<OtherReal> C(dim);
265  C.SetRandn();
266  const CuSpMatrix<OtherReal> D(C);
267 
268  Real t1 = TraceSpSp(A, C), t2 = TraceSpSp(B, D);
269  KALDI_ASSERT(ApproxEqual(t1, t2));
270  }
271 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
double TraceSpSp(const SpMatrix< double > &A, const SpMatrix< double > &B)
Definition: sp-matrix.cc:326
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuSubMatrix()

static void kaldi::UnitTestCuSubMatrix ( )
static

Definition at line 2029 of file cu-matrix-test.cc.

References KALDI_ASSERT, rnnlm::n, Rand(), CuMatrixBase< Real >::Range(), and CuMatrixBase< Real >::SetRandn().

2029  {
2030  for (int32 iter = 0 ; iter < 10; iter++) {
2031  int32 M1 = 1 + rand () % 10, M2 = 1 + Rand() % 1, M3 = 1 + Rand() % 10, M = M1 + M2 + M3,
2032  N1 = 1 + rand () % 10, N2 = 1 + Rand() % 1, N3 = 1 + Rand() % 10, N = N1 + N2 + N3,
2033  m = Rand() % M2, n = Rand() % N2;
2034  CuMatrix<Real> mat(M, N);
2035  mat.SetRandn();
2036  CuSubMatrix<Real> submat1(mat, M1, M2,
2037  N1, N2),
2038  submat2 = mat.Range(M1, M2, N1, N2);
2039  Real f1 = mat(M1 + m, N1 + n), f2 = submat1(m, n), f3 = submat2(m, n);
2040  KALDI_ASSERT(f1 == f2);
2041  KALDI_ASSERT(f2 == f3);
2042  }
2043 }
CuSubMatrix< Real > Range(const MatrixIndexT row_offset, const MatrixIndexT num_rows, const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
Definition: cu-matrix.h:653
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
struct rnnlm::@11::@12 n
This class is used for a piece of a CuMatrix.
Definition: matrix-common.h:70
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuSubVector()

static void kaldi::UnitTestCuSubVector ( )
static

Definition at line 85 of file cu-vector-test.cc.

References KALDI_ASSERT, Rand(), CuVectorBase< Real >::Range(), and CuVectorBase< Real >::SetRandn().

85  {
86  for (int32 iter = 0 ; iter < 10; iter++) {
87  int32 M1 = 1 + rand () % 10, M2 = 1 + Rand() % 1, M3 = 1 + Rand() % 10, M = M1 + M2 + M3,
88  m = Rand() % M2;
89  CuVector<Real> vec(M);
90  vec.SetRandn();
91  CuSubVector<Real> subvec1(vec, M1, M2),
92  subvec2 = vec.Range(M1, M2);
93  Real f1 = vec(M1 + m), f2 = subvec1(m), f3 = subvec2(m);
94  KALDI_ASSERT(f1 == f2);
95  KALDI_ASSERT(f2 == f3);
96  }
97 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
CuSubVector< Real > Range(const MatrixIndexT o, const MatrixIndexT l)
Definition: cu-vector.h:160
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestCuTanh()

void kaldi::UnitTestCuTanh ( )

Definition at line 2574 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, MatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), CuMatrixBase< Real >::NumRows(), MatrixBase< Real >::SetRandn(), CuMatrixBase< Real >::Tanh(), and MatrixBase< Real >::Tanh().

2574  {
2575  Matrix<Real> H(100,110);
2576  H.SetRandn();
2577  CuMatrix<Real> D(100,110);
2578  D.CopyFromMat(H);
2579 
2580  //gpu
2581  CuMatrix<Real> Di(100,110);
2582  Di.Tanh(D);
2583  Matrix<Real> Df(Di.NumRows(), Di.NumCols());
2584  Di.CopyToMat(&Df);
2585 
2586  //cpu
2587  Matrix<Real> Hf(H.NumRows(), H.NumCols());
2588  Hf.Tanh(H);
2589  KALDI_ASSERT(ApproxEqual(Df,Hf));
2590 }
void Tanh(const MatrixBase< Real > &src)
Set each element to the tanh of the corresponding element of "src".
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuTpMatrixCholesky()

static void kaldi::UnitTestCuTpMatrixCholesky ( )
static

Definition at line 134 of file cu-tp-matrix-test.cc.

References SpMatrix< Real >::AddMat2(), CuTpMatrix< Real >::Cholesky(), TpMatrix< Real >::Cholesky(), rnnlm::i, kNoTrans, Rand(), PackedMatrix< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

134  {
135  for (MatrixIndexT i = 1; i < 10; i++) {
136  MatrixIndexT dim = 1 + Rand() % 10;
137  if (i > 4) {
138  dim += 32 * (Rand() % 5);
139  }
140 
141  Matrix<Real> M(dim, dim + 2);
142  M.SetRandn();
143  SpMatrix<Real> A(dim);
144  A.AddMat2(1.0, M, kNoTrans, 0.0); // sets A to random almost-surely +ve
145  // definite matrix.
146  CuSpMatrix<Real> B(A);
147 
148  TpMatrix<Real> C(dim);
149  C.SetRandn();
150  CuTpMatrix<Real> D(C);
151  C.Cholesky(A);
152  D.Cholesky(B);
153 
154  AssertEqual<Real>(C, D);
155  }
156 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ UnitTestCuTpMatrixCopyFromMat()

static void kaldi::UnitTestCuTpMatrixCopyFromMat ( )
static

Definition at line 112 of file cu-tp-matrix-test.cc.

References AssertEqual(), CuTpMatrix< Real >::CopyFromMat(), TpMatrix< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, Rand(), CuMatrixBase< Real >::SetRandn(), and PackedMatrix< Real >::Trace().

112  {
113  for (MatrixIndexT i = 1; i < 10; i++) {
114  MatrixTransposeType trans = (i % 2 == 0 ? kNoTrans : kTrans);
115 
116  MatrixIndexT dim = 10*i + Rand() % 5;
117  CuMatrix<Real> A(dim, dim);
118  A.SetRandn();
119  Matrix<Real> A2(A);
120 
121  CuTpMatrix<Real> B(dim);
122  B.CopyFromMat(A, trans);
123  TpMatrix<Real> B2(dim);
124  B2.CopyFromMat(A2, trans);
125  TpMatrix<Real> B3(B);
126  AssertEqual(B2, B3);
127  KALDI_ASSERT(B3.Trace() != 0);
128  }
129 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32

◆ UnitTestCuTpMatrixCopyFromTp()

static void kaldi::UnitTestCuTpMatrixCopyFromTp ( )
static

Definition at line 95 of file cu-tp-matrix-test.cc.

References CuTpMatrix< Real >::CopyFromTp(), rnnlm::i, Rand(), and PackedMatrix< Real >::SetRandn().

95  {
96  for (MatrixIndexT i = 1; i < 10; i++) {
97  MatrixIndexT dim = 5 * i + Rand() % 10;
98 
99  TpMatrix<Real> A(dim);
100  A.SetRandn();
101  CuTpMatrix<Real> B(dim);
102  B.CopyFromTp(A);
103  CuTpMatrix<Real> C(dim);
104  C.CopyFromTp(B);
105 
106  AssertEqual<Real>(A, B);
107  AssertEqual<Real>(B, C);
108  }
109 }
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ UnitTestCuTpMatrixInvert()

static void kaldi::UnitTestCuTpMatrixInvert ( )
static

Definition at line 79 of file cu-tp-matrix-test.cc.

References rnnlm::i, Rand(), and PackedMatrix< Real >::SetRandn().

79  {
80  for (MatrixIndexT i = 1; i < 10; i++) {
81  MatrixIndexT dim = 5 * i + Rand() % 10;
82 
83  TpMatrix<Real> A(dim);
84  A.SetRandn();
85  CuTpMatrix<Real> B(A);
86 
87  AssertEqual<Real>(A, B, 0.005);
88  A.Invert();
89  B.Invert();
90  AssertEqual<Real>(A, B, 0.005);
91  }
92 }
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ UnitTestCuTpMatrixIO()

static void kaldi::UnitTestCuTpMatrixIO ( )
static

Definition at line 159 of file cu-tp-matrix-test.cc.

References AssertEqual(), rnnlm::i, Rand(), CuPackedMatrix< Real >::Read(), CuPackedMatrix< Real >::SetRandn(), and CuPackedMatrix< Real >::Write().

159  {
160  for (int32 i = 0; i < 3; i++) {
161  int32 dimM = Rand() % 255 + 10;
162  if (i % 5 == 0) { dimM = 0; }
163  CuTpMatrix<Real> mat(dimM);
164  mat.SetRandn();
165  std::ostringstream os;
166  bool binary = (i % 4 < 2);
167  mat.Write(os, binary);
168 
169  CuTpMatrix<Real> mat2;
170  std::istringstream is(os.str());
171  mat2.Read(is, binary);
172  AssertEqual(mat, mat2);
173  }
174 }
kaldi::int32 int32
static void AssertEqual(const PackedMatrix< Real > &A, const CuPackedMatrix< Real > &B, float tol=0.001)
void Read(std::istream &in, bool binary)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ UnitTestCuVectorAddColSumMat()

static void kaldi::UnitTestCuVectorAddColSumMat ( )
static

Definition at line 2000 of file cu-matrix-test.cc.

References CuVectorBase< Real >::AddColSumMat(), VectorBase< Real >::AddColSumMat(), VectorBase< Real >::AddVec(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), KALDI_ASSERT, VectorBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and VectorBase< Real >::SetZero().

2000  {
2001  const int32 X=19, Y=4321;
2002  Real alpha=0.5, beta=0.7;
2003 
2004  Matrix<Real> Hm(X,Y);
2005  Vector<Real> Hv(X);
2006  Vector<Real> Hv_accu(X);
2007  Hm.SetRandn();
2008  InitRand(&Hv);
2009 
2010  CuMatrix<Real> Dm(X,Y);
2011  CuVector<Real> Dv(X);
2012  Dm.CopyFromMat(Hm);
2013  Dv.CopyFromVec(Hv);
2014 
2015  Dv.AddColSumMat(alpha,Dm,beta);
2016 
2017  Hv_accu.SetZero();
2018  Hv_accu.AddColSumMat(1.0, Hm);
2019  Hv.Scale(beta);
2020  Hv.AddVec(alpha, Hv_accu);
2021 
2022  Vector<Real> Hv2(X);
2023  Dv.CopyToVec(&Hv2);
2024 
2025  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
2026 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorAddColSumMatLarge()

static void kaldi::UnitTestCuVectorAddColSumMatLarge ( )
static

Definition at line 2048 of file cu-matrix-test.cc.

References CuVectorBase< Real >::AddColSumMat(), VectorBase< Real >::AddColSumMat(), VectorBase< Real >::AddVec(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), KALDI_ASSERT, VectorBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and VectorBase< Real >::SetZero().

2048  {
2049  Matrix<Real> Hm(1000,990);
2050  Vector<Real> Hv(1000);
2051  Vector<Real> Hv_accu(1000);
2052  Hm.SetRandn();
2053  InitRand(&Hv);
2054 
2055  CuMatrix<Real> Dm(1000,990);
2056  CuVector<Real> Dv(1000);
2057  Dm.CopyFromMat(Hm);
2058  Dv.CopyFromVec(Hv);
2059 
2060  Dv.AddColSumMat(0.5, Dm, 0.7);
2061 
2062  Hv_accu.SetZero();
2063  Hv_accu.AddColSumMat(1.0, Hm);
2064  Hv.Scale(0.7);
2065  Hv.AddVec(0.5,Hv_accu);
2066 
2067  Vector<Real> Hv2(1000);
2068  Dv.CopyToVec(&Hv2);
2069 
2070  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
2071 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorAddRowSumMat()

static void kaldi::UnitTestCuVectorAddRowSumMat ( )
static

Definition at line 1941 of file cu-matrix-test.cc.

References CuVectorBase< Real >::AddRowSumMat(), VectorBase< Real >::AddRowSumMat(), VectorBase< Real >::AddVec(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), KALDI_ASSERT, VectorBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and VectorBase< Real >::SetZero().

1941  {
1942  const int32 X=4321, Y=19;
1943  Real alpha=0.1, beta=0.7;
1944 
1945  Matrix<Real> Hm(X,Y);
1946  Vector<Real> Hv(Y);
1947  Vector<Real> Hv_accu(Y);
1948  Hm.SetRandn();
1949  InitRand(&Hv);
1950 
1951  CuMatrix<Real> Dm(X,Y);
1952  CuVector<Real> Dv(Y);
1953  Dm.CopyFromMat(Hm);
1954  Dv.CopyFromVec(Hv);
1955 
1956  Dv.AddRowSumMat(alpha,Dm,beta);
1957 
1958  Hv_accu.SetZero();
1959  Hv_accu.AddRowSumMat(1.0, Hm);
1960  Hv.Scale(beta);
1961  Hv.AddVec(alpha,Hv_accu);
1962 
1963  Vector<Real> Hv2(Y);
1964  Dv.CopyToVec(&Hv2);
1965 
1966  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
1967 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorAddRowSumMatLarge()

static void kaldi::UnitTestCuVectorAddRowSumMatLarge ( )
static

Definition at line 1972 of file cu-matrix-test.cc.

References CuVectorBase< Real >::AddRowSumMat(), VectorBase< Real >::AddRowSumMat(), VectorBase< Real >::AddVec(), ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), KALDI_ASSERT, VectorBase< Real >::Scale(), MatrixBase< Real >::SetRandn(), and VectorBase< Real >::SetZero().

1972  {
1973  Matrix<Real> Hm(1000,990);
1974  Vector<Real> Hv(990);
1975  Vector<Real> Hv_accu(990);
1976  Hm.SetRandn();
1977  InitRand(&Hv);
1978 
1979  CuMatrix<Real> Dm(1000,990);
1980  CuVector<Real> Dv(990);
1981  Dm.CopyFromMat(Hm);
1982  Dv.CopyFromVec(Hv);
1983 
1984  Dv.AddRowSumMat(0.5,Dm,0.7);
1985 
1986  Hv_accu.SetZero();
1987  Hv_accu.AddRowSumMat(1.0, Hm);
1988  Hv.Scale(0.7);
1989  Hv.AddVec(0.5,Hv_accu);
1990 
1991  Vector<Real> Hv2(990);
1992  Dv.CopyToVec(&Hv2);
1993 
1994  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
1995 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorAddTp()

static void kaldi::UnitTestCuVectorAddTp ( )
static

Definition at line 122 of file cu-vector-test.cc.

References CuVectorBase< Real >::AddTpVec(), VectorBase< Real >::AddTpVec(), AssertEqual(), rnnlm::i, kNoTrans, VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

122  {
123  for (int32 i = 1; i < 10; i++) {
124  MatrixIndexT dim = 10 * i;
125  Vector<Real> A(dim);
126  A.SetRandn();
127  TpMatrix<Real> B(dim);
128  B.SetRandn();
129  Vector<Real> C(dim);
130  C.SetRandn();
131 
132  CuVector<Real> D(A);
133  CuTpMatrix<Real> E(B);
134  CuVector<Real> F(C);
135 
136  A.AddTpVec(1.0, B, kNoTrans, C, 1.0);
137  D.AddTpVec(1.0, E, kNoTrans, F, 1.0);
138 
139  CuVector<Real> G(A);
140  AssertEqual(D, G);
141  }
142 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuVectorAddTpVec()

static void kaldi::UnitTestCuVectorAddTpVec ( )
static

Definition at line 2131 of file cu-matrix-test.cc.

References CuVectorBase< Real >::AddTpVec(), VectorBase< Real >::AddTpVec(), ApproxEqual(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), KALDI_ASSERT, kNoTrans, and PackedMatrix< Real >::SetRandn().

2131  {
2132  Vector<Real> Hv(300);
2133  InitRand(&Hv);
2134  CuVector<Real> Dv(300);
2135  Dv.CopyFromVec(Hv);
2136  Vector<Real> Hv1(300);
2137  InitRand(&Hv1);
2138  CuVector<Real> Dv1(300);
2139  Dv1.CopyFromVec(Hv1);
2140 
2141  TpMatrix<Real> Hm(300);
2142  Hm.SetRandn();
2143  CuTpMatrix<Real> Dm(Hm);
2144 
2145  //gpu
2146  Dv.AddTpVec(1.0,Dm,kNoTrans,Dv1,1.0);
2147  //cpu
2148  Hv.AddTpVec(1.0,Hm,kNoTrans,Hv1,1.0);
2149 
2150  Vector<Real> Hv2(300);
2151  Dv.CopyToVec(&Hv2);
2152 
2153  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
2154 }
Packed symetric matrix class.
Definition: matrix-common.h:63
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorAddVec()

static void kaldi::UnitTestCuVectorAddVec ( )
static

Definition at line 1917 of file cu-matrix-test.cc.

References CuVectorBase< Real >::AddVec(), VectorBase< Real >::AddVec(), ApproxEqual(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), KALDI_ASSERT, and VectorBase< Real >::Scale().

1917  {
1918  Vector<Real> Hv(777);
1919  Vector<Real> Hw(777);
1920  InitRand(&Hv);
1921  InitRand(&Hw);
1922 
1923  CuVector<Real> Dv(777);
1924  CuVector<Real> Dw(777);
1925  Dv.CopyFromVec(Hv);
1926  Dw.CopyFromVec(Hw);
1927 
1928  Dv.AddVec(0.1,Dw,0.9);
1929  Hv.Scale(0.9);
1930  Hv.AddVec(0.1,Hw);
1931 
1932  Vector<Real> Hv2(777);
1933  Dv.CopyToVec(&Hv2);
1934 
1935  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
1936 }
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorCopyFromVec()

static void kaldi::UnitTestCuVectorCopyFromVec ( )
static

Definition at line 67 of file cu-vector-test.cc.

References AssertEqual(), CuVectorBase< Real >::CopyFromVec(), VectorBase< Real >::CopyFromVec(), rnnlm::i, and VectorBase< Real >::SetRandn().

67  {
68  for (int32 i = 1; i < 10; i++) {
69  MatrixIndexT dim = 10 * i;
70  Vector<Real> A(dim);
71  A.SetRandn();
73  Vector<Real> C(B);
74  CuVector<Real> D(dim);
75  D.CopyFromVec(C);
76  Vector<OtherReal> E(dim);
77  E.CopyFromVec(D);
78  CuVector<Real> F(E);
79  CuVector<Real> A2(A);
80  AssertEqual(F, A2);
81  }
82 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuVectorInvertElements()

static void kaldi::UnitTestCuVectorInvertElements ( )
static

Definition at line 2076 of file cu-matrix-test.cc.

References ApproxEqual(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), CuVectorBase< Real >::InvertElements(), VectorBase< Real >::InvertElements(), and KALDI_ASSERT.

2076  {
2077  Vector<Real> Hv(777);
2078  InitRand(&Hv);
2079 
2080  CuVector<Real> Dv(777);
2081  Dv.CopyFromVec(Hv);
2082 
2083  Dv.InvertElements();
2084  Hv.InvertElements();
2085 
2086  Vector<Real> Hv2(777);
2087  Dv.CopyToVec(&Hv2);
2088 
2089  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
2090 }
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorIO()

static void kaldi::UnitTestCuVectorIO ( )
static

Definition at line 48 of file cu-vector-test.cc.

References AssertEqual(), rnnlm::i, Rand(), CuVector< Real >::Read(), CuVectorBase< Real >::SetRandn(), and CuVector< Real >::Write().

48  {
49  for (int32 i = 0; i < 10; i++) {
50  int32 dimM = Rand() % 255;
51  if (i % 5 == 0) { dimM = 0; }
52  CuVector<Real> vec(dimM);
53  vec.SetRandn();
54  std::ostringstream os;
55  bool binary = (i % 4 < 2);
56  vec.Write(os, binary);
57 
58  CuVector<Real> vec2;
59  std::istringstream is(os.str());
60  vec2.Read(is, binary);
61  AssertEqual(vec, vec2);
62  }
63 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void Read(std::istream &is, bool binary)
I/O.
Definition: cu-vector.cc:963
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuVectorMulTp() [1/2]

static void kaldi::UnitTestCuVectorMulTp ( )
static

Definition at line 102 of file cu-vector-test.cc.

References AssertEqual(), rnnlm::i, kNoTrans, CuVectorBase< Real >::MulTp(), VectorBase< Real >::MulTp(), VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

102  {
103  for (int32 i = 1; i < 10; i++) {
104  MatrixIndexT dim = 10 * i;
105  Vector<Real> A(dim);
106  A.SetRandn();
107  TpMatrix<Real> B(dim);
108  B.SetRandn();
109 
110  CuVector<Real> C(A);
111  CuTpMatrix<Real> D(B);
112 
113  A.MulTp(B, kNoTrans);
114  C.MulTp(D, kNoTrans);
115 
116  CuVector<Real> E(A);
117  AssertEqual(C, E);
118  }
119 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuVectorMulTp() [2/2]

static void kaldi::UnitTestCuVectorMulTp ( )
static

Definition at line 2173 of file cu-matrix-test.cc.

References ApproxEqual(), CuVectorBase< Real >::CopyFromVec(), CuVectorBase< Real >::CopyToVec(), InitRand(), KALDI_ASSERT, kNoTrans, CuVectorBase< Real >::MulTp(), VectorBase< Real >::MulTp(), and PackedMatrix< Real >::SetRandn().

2173  {
2174  Vector<Real> Hv(300);
2175  InitRand(&Hv);
2176  CuVector<Real> Dv(300);
2177  Dv.CopyFromVec(Hv);
2178 
2179  TpMatrix<Real> Hm(300);
2180  Hm.SetRandn();
2181  CuTpMatrix<Real> Dm(Hm);
2182 
2183  //gpu
2184  Dv.MulTp(Dm,kNoTrans);
2185  //cpu
2186  Hv.MulTp(Hm,kNoTrans);
2187 
2188  Vector<Real> Hv2(300);
2189  Dv.CopyToVec(&Hv2);
2190 
2191  KALDI_ASSERT(ApproxEqual(Hv,Hv2));
2192 }
Packed symetric matrix class.
Definition: matrix-common.h:63
static void InitRand(MatrixBase< Real > *M)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestCuVectorReplaceValue()

static void kaldi::UnitTestCuVectorReplaceValue ( )
static

Definition at line 298 of file cu-vector-test.cc.

References AssertEqual(), rnnlm::i, Rand(), CuVectorBase< Real >::ReplaceValue(), VectorBase< Real >::ReplaceValue(), and VectorBase< Real >::SetRandn().

298  {
299  for (int32 i = 0; i < 5; i++) {
300  int32 dim = 100 + Rand() % 200;
301  Real orig = 0.1 * (Rand() % 100), changed = 0.1 * (Rand() % 50);
302  Vector<Real> vec(dim);
303  vec.SetRandn();
304  vec(dim / 2) = orig;
305  CuVector<Real> vec1(vec);
306  vec.ReplaceValue(orig, changed);
307  vec1.ReplaceValue(orig, changed);
308  Vector<Real> vec2(vec1);
309  AssertEqual(vec, vec2);
310  }
311 }
kaldi::int32 int32
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestCuVectorSum()

static void kaldi::UnitTestCuVectorSum ( )
static

Definition at line 313 of file cu-vector-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, RandInt(), and VectorBase< Real >::Range().

313  {
314  for (int32 i = 0; i < 200; i++) {
315  int32 start_dim = RandInt(1, 500), end_dim = RandInt(1, 500);
316  int32 dim = RandInt(10, 12000) + start_dim + end_dim;
317  Real quiet_nan = nan(""); // this is from <cmath>.
318  Vector<BaseFloat> vec(start_dim + dim + end_dim);
319  vec.Range(0, start_dim).Set(quiet_nan);
320  vec.Range(start_dim, dim).Set(1.0);
321  vec.Range(start_dim + dim, end_dim).Set(quiet_nan);
322  BaseFloat sum = vec.Range(start_dim, dim).Sum();
323  KALDI_ASSERT(ApproxEqual(sum, dim));
324  }
325 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestDct()

static void kaldi::UnitTestDct ( )
static

Definition at line 3409 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), ComputeDctMatrix(), rnnlm::i, MatrixBase< Real >::IsUnit(), KALDI_ASSERT, kNoTrans, kTrans, and Rand().

3409  {
3410 
3411  // Check that DCT matrix is orthogonal (i.e. M^T M = I);
3412  for (MatrixIndexT i = 0; i < 10; i++) {
3413  MatrixIndexT N = 1 + Rand() % 10;
3414  Matrix<Real> M(N, N);
3415  ComputeDctMatrix(&M);
3416  Matrix<Real> I(N, N);
3417  I.AddMatMat(1.0, M, kTrans, M, kNoTrans, 0.0);
3418  KALDI_ASSERT(I.IsUnit());
3419  }
3420 
3421 }
void ComputeDctMatrix(Matrix< Real > *M)
ComputeDctMatrix computes a matrix corresponding to the DCT, such that M * v equals the DCT of vector...
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestDefines()

void kaldi::UnitTestDefines ( )

Definition at line 190 of file kaldi-math-test.cc.

References DBL_EPSILON, Exp(), FLT_EPSILON, KALDI_ASSERT, KALDI_ISFINITE, KALDI_ISINF, KALDI_ISNAN, kLogZeroDouble, kLogZeroFloat, M_2PI, M_LOG_2PI, and M_PI.

Referenced by main().

190  { // Yes, we even unit-test the preprocessor statements.
191  KALDI_ASSERT(Exp(kLogZeroFloat) == 0.0);
193  BaseFloat den = 0.0;
194  KALDI_ASSERT(KALDI_ISNAN(0.0 / den));
195  KALDI_ASSERT(!KALDI_ISINF(0.0 / den));
196  KALDI_ASSERT(!KALDI_ISFINITE(0.0 / den));
197  KALDI_ASSERT(!KALDI_ISNAN(1.0 / den));
198  KALDI_ASSERT(KALDI_ISINF(1.0 / den));
199  KALDI_ASSERT(!KALDI_ISFINITE(1.0 / den));
201  KALDI_ASSERT(!KALDI_ISINF(0.0));
202  KALDI_ASSERT(!KALDI_ISNAN(0.0));
203 
204  std::cout << 1.0+DBL_EPSILON;
205  std::cout << 1.0 + 0.5*DBL_EPSILON;
206  KALDI_ASSERT(1.0 + DBL_EPSILON != 1.0 && 1.0 + (0.5*DBL_EPSILON) == 1.0
207  && "If this test fails, you can probably just comment it out-- "
208  "may mean your CPU exceeds expected floating point precision");
209  KALDI_ASSERT(1.0f + FLT_EPSILON != 1.0f && 1.0f + (0.5f*FLT_EPSILON) == 1.0f
210  && "If this test fails, you can probably just comment it out-- "
211  "may mean your CPU exceeds expected floating point precision");
212  KALDI_ASSERT(std::abs(sin(M_PI)) < 1.0e-05
213  && std::abs(cos(M_PI)+1.0) < 1.0e-05);
214  KALDI_ASSERT(std::abs(sin(M_2PI)) < 1.0e-05
215  && std::abs(cos(M_2PI)-1.0) < 1.0e-05);
216  KALDI_ASSERT(std::abs(sin(Exp(M_LOG_2PI))) < 1.0e-05);
217  KALDI_ASSERT(std::abs(cos(Exp(M_LOG_2PI)) - 1.0) < 1.0e-05);
218 }
double Exp(double x)
Definition: kaldi-math.h:83
#define M_LOG_2PI
Definition: kaldi-math.h:60
#define DBL_EPSILON
Definition: kaldi-math.h:37
#define M_PI
Definition: kaldi-math.h:44
#define KALDI_ISINF
Definition: kaldi-math.h:73
#define KALDI_ISFINITE(x)
Definition: kaldi-math.h:74
float BaseFloat
Definition: kaldi-types.h:29
#define FLT_EPSILON
Definition: kaldi-math.h:40
#define KALDI_ISNAN
Definition: kaldi-math.h:72
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define M_2PI
Definition: kaldi-math.h:52
const float kLogZeroFloat
Definition: kaldi-math.h:128
const double kLogZeroDouble
Definition: kaldi-math.h:129

◆ UnitTestDelay()

static void kaldi::UnitTestDelay ( )
static

Definition at line 219 of file pitch-functions-test.cc.

References OnlinePitchFeature::AcceptWaveform(), ApproxEqual(), ProcessPitchOptions::delay, ProcessPitchOptions::delta_pitch_noise_stddev, VectorBase< Real >::Dim(), OnlineProcessPitch::Dim(), OnlineProcessPitch::GetFrame(), rnnlm::i, OnlinePitchFeature::InputFinished(), KALDI_ASSERT, KALDI_ERR, KALDI_LOG, M_2PI, rnnlm::n, PitchExtractionOptions::nccf_ballast_online, MatrixBase< Real >::NumCols(), OnlineProcessPitch::NumFramesReady(), pitch_use_naive_search, RandGauss(), Matrix< Real >::Resize(), and PitchExtractionOptions::samp_freq.

Referenced by UnitTestFeatNoKeele().

219  {
220  KALDI_LOG << "=== UnitTestDelay() ===\n";
221  for (int32 n = 0; n < 10; n++) {
222  // the parametrization object
223  PitchExtractionOptions ext_opt;
224  ProcessPitchOptions pro_opt1, pro_opt2;
225  pro_opt1.delta_pitch_noise_stddev = 0.0; // to avoid mismatch of delta_log_pitch
226  // brought by rand noise.
227  pro_opt2.delta_pitch_noise_stddev = 0.0; // to avoid mismatch of delta_log_pitch
228  // brought by rand noise.
229  pro_opt2.delay = rand() % 50;
230  ext_opt.nccf_ballast_online = true; // this is necessary for the computation
231  // to be identical regardless how many pieces we break the signal into.
232 
233  int32 size = 1000 + rand() % 5000;
234 
235  Vector<BaseFloat> v(size);
236  // init with noise plus a sine-wave whose frequency is changing randomly.
237 
238  double cur_freq = 200.0, normalized_time = 0.0;
239 
240  for (int32 i = 0; i < size; i++) {
241  v(i) = RandGauss() + cos(normalized_time * M_2PI);
242  cur_freq += RandGauss(); // let the frequency wander a little.
243  if (cur_freq < 100.0) cur_freq = 100.0;
244  if (cur_freq > 300.0) cur_freq = 300.0;
245  normalized_time += cur_freq / ext_opt.samp_freq;
246  }
247 
248  Matrix<BaseFloat> m1, m2;
249  // compute it online with multiple pieces.
250  OnlinePitchFeature pitch_extractor(ext_opt);
251  OnlineProcessPitch pitch_processor(pro_opt1, &pitch_extractor);
252  OnlineProcessPitch pitch_processor_delayed(pro_opt2, &pitch_extractor);
253  int32 start_samp = 0;
254  while (start_samp < v.Dim()) {
255  int32 num_samp = rand() % (v.Dim() + 1 - start_samp);
256  SubVector<BaseFloat> v_part(v, start_samp, num_samp);
257  pitch_extractor.AcceptWaveform(ext_opt.samp_freq, v_part);
258  start_samp += num_samp;
259  }
260  pitch_extractor.InputFinished();
261 
262  int32 num_frames = pitch_processor.NumFramesReady();
263  m1.Resize(num_frames, pitch_processor.Dim());
264  for (int32 frame = 0; frame < num_frames; frame++) {
265  SubVector<BaseFloat> rowp(m1, frame);
266  pitch_processor.GetFrame(frame, &rowp);
267  }
268 
269  int32 num_frames_delayed = pitch_processor_delayed.NumFramesReady();
270  m2.Resize(num_frames_delayed, pitch_processor_delayed.Dim());
271  for (int32 frame = 0; frame < num_frames_delayed; frame++) {
272  SubVector<BaseFloat> rowp(m2, frame);
273  pitch_processor_delayed.GetFrame(frame, &rowp);
274  }
275 
276  KALDI_ASSERT(num_frames_delayed == num_frames + pro_opt2.delay);
277  SubMatrix<BaseFloat> m3(m2, pro_opt2.delay, num_frames, 0, m2.NumCols());
278  if (!ApproxEqual(m1, m3)) {
279  KALDI_ERR << "Post-processed pitch differs: " << m1 << " vs. " << m3;
280  }
281  KALDI_LOG << "Test passed :)\n";
282  }
283 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
This online-feature class implements post processing of pitch features.
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
struct rnnlm::@11::@12 n
#define KALDI_ERR
Definition: kaldi-error.h:147
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define M_2PI
Definition: kaldi-math.h:52
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
#define KALDI_LOG
Definition: kaldi-error.h:153
Sub-matrix representation.
Definition: kaldi-matrix.h:988
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestDeterminant()

static void kaldi::UnitTestDeterminant ( )
static

Definition at line 1181 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMat(), MatrixBase< Real >::AddMatMat(), SpMatrix< Real >::CopyFromMat(), rnnlm::i, InitRandNonsingular(), MatrixBase< Real >::IsZero(), KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, SpMatrix< Real >::LogDet(), MatrixBase< Real >::LogDet(), SpMatrix< Real >::LogPosDefDet(), Rand(), MatrixBase< Real >::SetZero(), TraceMatMat(), and TraceSpSp().

1181  { // also tests matrix axpy and IsZero() and TraceOfProduct{, T}
1182  for (MatrixIndexT iter = 0;iter < 5;iter++) { // First test the 2 det routines are the same
1183  int dimM = 10 + Rand() % 10;
1184  Matrix<Real> M(dimM, dimM), N(dimM, dimM);
1185  InitRandNonsingular(&M);
1186  N.AddMatMat(1.0, M, kNoTrans, M, kTrans, 0.0); // N:=M*M^T.
1187  for (MatrixIndexT i = 0;i < (MatrixIndexT)dimM;i++) N(i, i) += 0.0001; // Make sure numerically +ve det-- can by chance be almost singular the way we initialized it (I think)
1188  SpMatrix<Real> S(dimM);
1189  S.CopyFromMat(N); // symmetric so should not crash.
1190  Real logdet = S.LogPosDefDet();
1191  Real logdet2, logdet3, sign2, sign3;
1192  logdet2 = N.LogDet(&sign2);
1193  logdet3 = S.LogDet(&sign3);
1194  KALDI_ASSERT(sign2 == 1.0 && sign3 == 1.0 && std::abs(logdet2-logdet) < 0.1 && std::abs(logdet2 - logdet3) < 0.1);
1195  Matrix<Real> tmp(dimM, dimM); tmp.SetZero();
1196  tmp.AddMat(1.0, N);
1197  tmp.AddMat(-1.0, N, kTrans);
1198  // symmetric so tmp should be zero.
1199  if ( ! tmp.IsZero(1.0e-04)) {
1200  printf("KALDI_ERR: matrix is not zero\n");
1201  KALDI_LOG << tmp;
1202  KALDI_ASSERT(0);
1203  }
1204 
1205  Real a = TraceSpSp(S, S), b = TraceMatMat(N, N), c = TraceMatMat(N, N, kTrans);
1206  KALDI_ASSERT(std::abs(a-b) < 0.1 && std::abs(b-c) < 0.1);
1207  }
1208 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
double TraceSpSp(const SpMatrix< double > &A, const SpMatrix< double > &B)
Definition: sp-matrix.cc:326
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void InitRandNonsingular(SpMatrix< Real > *M)
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestDeterminantSign()

static void kaldi::UnitTestDeterminantSign ( )
static

Definition at line 1211 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), AssertEqual(), SpMatrix< Real >::CopyFromMat(), rnnlm::i, InitRandNonsingular(), KALDI_ASSERT, kNoTrans, kTrans, Log(), SpMatrix< Real >::LogDet(), MatrixBase< Real >::LogDet(), SpMatrix< Real >::LogPosDefDet(), Rand(), MatrixBase< Real >::Row(), PackedMatrix< Real >::Scale(), MatrixBase< Real >::Scale(), and MatrixBase< Real >::Svd().

1211  {
1212 
1213  for (MatrixIndexT iter = 0;iter < 20;iter++) { // First test the 2 det routines are the same
1214  int dimM = 10 + Rand() % 10;
1215  Matrix<Real> M(dimM, dimM), N(dimM, dimM);
1216  InitRandNonsingular(&M);
1217  N.AddMatMat(1.0, M, kNoTrans, M, kTrans, 0.0); // N:=M*M^T.
1218  for (MatrixIndexT i = 0;i < (MatrixIndexT)dimM;i++) N(i, i) += 0.0001; // Make sure numerically +ve det-- can by chance be almost singular the way we initialized it (I think)
1219  SpMatrix<Real> S(dimM);
1220  S.CopyFromMat(N); // symmetric so should not crash.
1221  Real logdet = S.LogPosDefDet();
1222  Real logdet2, logdet3, sign2, sign3;
1223  logdet2 = N.LogDet(&sign2);
1224  logdet3 = S.LogDet(&sign3);
1225  KALDI_ASSERT(sign2 == 1.0 && sign3 == 1.0 && std::abs(logdet2-logdet) < 0.01 && std::abs(logdet2 - logdet3) < 0.01);
1226 
1227  MatrixIndexT num_sign_changes = Rand() % 5;
1228  for (MatrixIndexT change = 0; change < num_sign_changes; change++) {
1229  // Change sign of S's det by flipping one eigenvalue, and N by flipping one row.
1230  {
1231  Matrix<Real> M(S);
1232  Matrix<Real> U(dimM, dimM), Vt(dimM, dimM);
1233  Vector<Real> s(dimM);
1234  M.Svd(&s, &U, &Vt); // SVD: M = U diag(s) Vt
1235  s(Rand() % dimM) *= -1;
1236  U.MulColsVec(s);
1237  M.AddMatMat(1.0, U, kNoTrans, Vt, kNoTrans, 0.0);
1238  S.CopyFromMat(M);
1239  }
1240  // change sign of N:
1241  N.Row(Rand() % dimM).Scale(-1.0);
1242  }
1243 
1244  // add in a scaling factor too.
1245  Real tmp = 1.0 + ((Rand() % 5) * 0.01);
1246  Real logdet_factor = dimM * Log(tmp);
1247  N.Scale(tmp);
1248  S.Scale(tmp);
1249 
1250  Real logdet4, logdet5, sign4, sign5;
1251  logdet4 = N.LogDet(&sign4);
1252  logdet5 = S.LogDet(&sign5);
1253  AssertEqual(logdet4, logdet+logdet_factor, 0.01);
1254  AssertEqual(logdet5, logdet+logdet_factor, 0.01);
1255  if (num_sign_changes % 2 == 0) {
1256  KALDI_ASSERT(sign4 == 1);
1257  KALDI_ASSERT(sign5 == 1);
1258  } else {
1259  KALDI_ASSERT(sign4 == -1);
1260  KALDI_ASSERT(sign5 == -1);
1261  }
1262  }
1263 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
double Log(double x)
Definition: kaldi-math.h:100
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
static void InitRandNonsingular(SpMatrix< Real > *M)

◆ UnitTestDiagGmm()

void kaldi::UnitTestDiagGmm ( )

Definition at line 86 of file diag-gmm-test.cc.

References AssertEqual(), DiagGmm::ComponentPosteriors(), DiagGmm::ComputeGconsts(), DiagGmm::CopyFromDiagGmm(), MatrixBase< Real >::CopyFromMat(), VectorBase< Real >::CopyFromVec(), rnnlm::d, DiagGmm::Dim(), Exp(), DiagGmm::GetComponentMean(), DiagGmm::GetMeans(), DiagGmm::GetVars(), rnnlm::i, MatrixBase< Real >::InvertElements(), Log(), DiagGmm::LogLikelihood(), DiagGmm::LogLikelihoods(), DiagGmm::LogLikelihoodsPreselect(), VectorBase< Real >::LogSumExp(), M_LOG_2PI, DiagGmm::Merge(), DiagGmm::MergeKmeans(), DiagGmm::NumGauss(), RandGauss(), RandInt(), RandUniform(), DiagGmm::Read(), DiagGmm::Resize(), DiagGmm::SetInvVars(), DiagGmm::SetInvVarsAndMeans(), DiagGmm::SetMeans(), DiagGmm::SetWeights(), MatrixBase< Real >::SetZero(), DiagGmm::Split(), Input::Stream(), VectorBase< Real >::Sum(), DiagGmm::weights(), and DiagGmm::Write().

Referenced by main().

86  {
87  // random dimension of the gmm
88  size_t dim = 1 + kaldi::RandInt(0, 5);
89  // random number of mixtures
90  size_t nMix = 1 + kaldi::RandInt(0, 5);
91 
92  std::cout << "Testing NumGauss: " << nMix << ", " << "Dim: " << dim
93  << '\n';
94 
95  // generate random feature vector and
96  // random mean and variance vectors
97  Vector<BaseFloat> feat(dim), weights(nMix), loglikes(nMix);
98  Matrix<BaseFloat> means(nMix, dim), vars(nMix, dim), invvars(nMix, dim);
99 
100  float loglike = 0.0;
101  for (size_t d = 0; d < dim; d++) {
102  feat(d) = kaldi::RandGauss();
103  }
104 
105  float tot_weight = 0.0;
106  for (size_t m = 0; m < nMix; m++) {
107  weights(m) = kaldi::RandUniform();
108  for (size_t d= 0; d < dim; d++) {
109  means(m, d) = kaldi::RandGauss();
110  vars(m, d) = Exp(kaldi::RandGauss()) + 1e-5;
111  }
112  tot_weight += weights(m);
113  }
114 
115  // normalize weights
116  for (size_t m = 0; m < nMix; m++) {
117  weights(m) /= tot_weight;
118  for (size_t d= 0; d < dim; d++) {
119  loglikes(m) += -0.5 * (M_LOG_2PI + Log(vars(m, d)) + (feat(d) -
120  means(m, d)) * (feat(d) - means(m, d)) / vars(m, d));
121  }
122  loglikes(m) += Log(weights(m));
123  }
124 
125  loglike = loglikes.LogSumExp();
126 
127  // new GMM
128  DiagGmm *gmm = new DiagGmm();
129  gmm->Resize(nMix, dim);
130  invvars.CopyFromMat(vars);
131  invvars.InvertElements();
132  gmm->SetWeights(weights);
133  gmm->SetInvVarsAndMeans(invvars, means);
134  gmm->ComputeGconsts();
135 
136  Vector<BaseFloat> posterior1(nMix);
137  float loglike1 = gmm->ComponentPosteriors(feat, &posterior1);
138 
139  std::cout << "LogLike: " << loglike << '\n';
140  std::cout << "LogLike1: " << loglike1 << '\n';
141  AssertEqual(loglike, loglike1, 0.01);
142 
143  AssertEqual(1.0, posterior1.Sum(), 0.01);
144 
145  { // Test various accessors / mutators
146  Vector<BaseFloat> weights_bak(nMix);
147  Matrix<BaseFloat> means_bak(nMix, dim);
148  Matrix<BaseFloat> invvars_bak(nMix, dim);
149 
150  weights_bak.CopyFromVec(gmm->weights());
151  gmm->GetMeans(&means_bak);
152  gmm->GetVars(&invvars_bak); // get vars
153  invvars_bak.InvertElements(); // compute invvars
154 
155  // set all params one-by-one to new model
156  DiagGmm gmm2;
157  gmm2.Resize(gmm->NumGauss(), gmm->Dim());
158  gmm2.SetWeights(weights_bak);
159  gmm2.SetMeans(means_bak);
160  gmm2.SetInvVars(invvars_bak);
161  gmm2.ComputeGconsts();
162  BaseFloat loglike_gmm2 = gmm2.LogLikelihood(feat);
163  AssertEqual(loglike1, loglike_gmm2);
164  {
165  Vector<BaseFloat> loglikes;
166  gmm2.LogLikelihoods(feat, &loglikes);
167  AssertEqual(loglikes.LogSumExp(), loglike_gmm2);
168  }
169  {
170  std::vector<int32> indices;
171  for (int32 i = 0; i < gmm2.NumGauss(); i++)
172  indices.push_back(i);
173  Vector<BaseFloat> loglikes;
174  gmm2.LogLikelihoodsPreselect(feat, indices, &loglikes);
175  AssertEqual(loglikes.LogSumExp(), loglike_gmm2);
176  }
177 
178  // single component mean accessor + mutator
179  DiagGmm gmm3;
180  gmm3.Resize(gmm->NumGauss(), gmm->Dim());
181  gmm3.SetWeights(weights_bak);
182  means_bak.SetZero();
183  for (size_t i = 0; i < nMix; i++) {
184  SubVector<BaseFloat> row(means_bak, i);
185  gmm->GetComponentMean(i, &row);
186  gmm3.SetComponentMean(i, row);
187  }
188  gmm3.SetInvVars(invvars_bak);
189  gmm3.ComputeGconsts();
190  BaseFloat loglike_gmm3 = gmm3.LogLikelihood(feat);
191  AssertEqual(loglike1, loglike_gmm3, 0.01);
192  } // Test various accessors / mutators end
193 
194 
195  // First, non-binary write.
196  gmm->Write(Output("tmpf", false).Stream(), false);
197 
198  delete gmm;
199 
200  {
201  bool binary_in;
202  DiagGmm *gmm2 = new DiagGmm();
203  Input ki("tmpf", &binary_in);
204  gmm2->Read(ki.Stream(), binary_in);
205 
206  float loglike4 = gmm2->ComponentPosteriors(feat, &posterior1);
207  AssertEqual(loglike, loglike4, 0.01);
208 
209  // binary write
210  gmm2->Write(Output("tmpfb", true).Stream(), true);
211  delete gmm2;
212 
213  // binary read
214  DiagGmm *gmm3;
215  gmm3 = new DiagGmm();
216  Input ki2("tmpfb", &binary_in);
217  gmm3->Read(ki2.Stream(), binary_in);
218 
219  float loglike5 = gmm3->ComponentPosteriors(feat, &posterior1);
220  AssertEqual(loglike, loglike5, 0.01);
221  delete gmm3;
222  }
223 
224  { // split and merge test for 1 component GMM (doesn't test the merge crit.)
225  DiagGmm gmm1;
226  Vector<BaseFloat> weights1(1);
227  Matrix<BaseFloat> means1(1, dim), vars1(1, dim), invvars1(1, dim);
228  weights1(0) = 1.0;
229  means1.CopyFromMat(means.Range(0, 1, 0, dim));
230  vars1.CopyFromMat(vars.Range(0, 1, 0, dim));
231  invvars1.CopyFromMat(vars1);
232  invvars1.InvertElements();
233  gmm1.Resize(1, dim);
234  gmm1.SetWeights(weights1);
235  gmm1.SetInvVarsAndMeans(invvars1, means1);
236  gmm1.ComputeGconsts();
237  DiagGmm gmm2;
238  gmm2.CopyFromDiagGmm(gmm1);
239  gmm2.Split(2, 0.001);
240  gmm2.Merge(1);
241  float loglike1 = gmm1.LogLikelihood(feat);
242  float loglike2 = gmm2.LogLikelihood(feat);
243  AssertEqual(loglike1, loglike2, 0.01);
244  }
245 
246 
247  { // split and merge test for 1 component GMM, this time using K-means algorithm.
248  DiagGmm gmm1;
249  Vector<BaseFloat> weights1(1);
250  Matrix<BaseFloat> means1(1, dim), vars1(1, dim), invvars1(1, dim);
251  weights1(0) = 1.0;
252  means1.CopyFromMat(means.Range(0, 1, 0, dim));
253  vars1.CopyFromMat(vars.Range(0, 1, 0, dim));
254  invvars1.CopyFromMat(vars1);
255  invvars1.InvertElements();
256  gmm1.Resize(1, dim);
257  gmm1.SetWeights(weights1);
258  gmm1.SetInvVarsAndMeans(invvars1, means1);
259  gmm1.ComputeGconsts();
260  DiagGmm gmm2;
261  gmm2.CopyFromDiagGmm(gmm1);
262  gmm2.Split(2, 0.001);
263  gmm2.MergeKmeans(1);
264  float loglike1 = gmm1.LogLikelihood(feat);
265  float loglike2 = gmm2.LogLikelihood(feat);
266  AssertEqual(loglike1, loglike2, 0.01);
267  }
268 
269  { // Duplicate Gaussians using initializer that takes a vector, and
270  // check like is unchanged.
271  DiagGmm gmm1;
272  Vector<BaseFloat> weights1(1);
273  Matrix<BaseFloat> means1(1, dim), vars1(1, dim), invvars1(1, dim);
274  weights1(0) = 1.0;
275  means1.CopyFromMat(means.Range(0, 1, 0, dim));
276  vars1.CopyFromMat(vars.Range(0, 1, 0, dim));
277  invvars1.CopyFromMat(vars1);
278  invvars1.InvertElements();
279  gmm1.Resize(1, dim);
280  gmm1.SetWeights(weights1);
281  gmm1.SetInvVarsAndMeans(invvars1, means1);
282  gmm1.ComputeGconsts();
283 
284  std::vector<std::pair<BaseFloat, const DiagGmm*> > vec;
285  vec.push_back(std::make_pair(static_cast<BaseFloat>(0.4), (const DiagGmm*)(&gmm1)));
286  vec.push_back(std::make_pair(static_cast<BaseFloat>(0.6), (const DiagGmm*)(&gmm1)));
287 
288  DiagGmm gmm2(vec);
289 
290  float loglike1 = gmm1.LogLikelihood(feat);
291  float loglike2 = gmm2.LogLikelihood(feat);
292  AssertEqual(loglike1, loglike2, 0.01);
293  }
294 
295  unlink("tmpf");
296  unlink("tmpfb");
297 }
double Exp(double x)
Definition: kaldi-math.h:83
#define M_LOG_2PI
Definition: kaldi-math.h:60
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
double Log(double x)
Definition: kaldi-math.h:100
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestDiagGmmGenerate()

void kaldi::UnitTestDiagGmmGenerate ( )

Definition at line 54 of file diag-gmm-test.cc.

References AccumDiagGmm::AccumulateFromDiag(), AssertEqual(), count, DiagGmm::Dim(), DiagGmm::Generate(), rnnlm::i, InitRandomGmm(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, kGmmAll, MleDiagGmmUpdate(), and DiagGmm::NumGauss().

Referenced by main().

54  {
55  DiagGmm gmm;
56  InitRandomGmm(&gmm);
57  int32 dim = gmm.Dim();
58  int32 npoints = 100 * gmm.NumGauss();
59  Matrix<BaseFloat> rand_points(npoints, dim);
60  for (int32 i = 0; i < npoints; i++) {
61  SubVector<BaseFloat> row(rand_points, i);
62  gmm.Generate(&row);
63  }
64  int32 niters = 15;
65  BaseFloat objf_change_tot = 0.0, objf_change, count;
66  for (int32 j = 0; j < niters; j++) {
67  MleDiagGmmOptions opts;
68  AccumDiagGmm stats(gmm, kGmmAll); // all update flags.
69  for (int32 i = 0; i < npoints; i++) {
70  SubVector<BaseFloat> row(rand_points, i);
71  stats.AccumulateFromDiag(gmm, row, 1.0);
72  }
73  MleDiagGmmUpdate(opts, stats, kGmmAll, &gmm, &objf_change, &count);
74  objf_change_tot += objf_change;
75  }
76  AssertEqual(count, npoints, 1e-6);
77  int32 num_params = gmm.NumGauss() * (gmm.Dim()*2 + 1);
78  BaseFloat expected_objf_change = 0.5 * num_params;
79  KALDI_LOG << "Expected objf change is: not much more than "
80  << expected_objf_change <<", seen: " << objf_change_tot;
81  KALDI_ASSERT(objf_change_tot < 2.0 * expected_objf_change); // way too much.
82  // This test relies on statistical laws and if it fails it does not
83  // *necessarily* mean that something is wrong.
84 }
void InitRandomGmm(DiagGmm *gmm_in)
void MleDiagGmmUpdate(const MleDiagGmmOptions &config, const AccumDiagGmm &diag_gmm_acc, GmmFlagsType flags, DiagGmm *gmm, BaseFloat *obj_change_out, BaseFloat *count_out, int32 *floored_elements_out, int32 *floored_gaussians_out, int32 *removed_gaussians_out)
for computing the maximum-likelihood estimates of the parameters of a Gaussian mixture model...
kaldi::int32 int32
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestDiffSampleRate()

void kaldi::UnitTestDiffSampleRate ( )

Definition at line 528 of file pitch-functions-test.cc.

References ComputeKaldiPitch(), ConvertIntToString(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, PitchExtractionOptions::lowpass_cutoff, PitchExtractionOptions::max_f0, WaveData::Read(), and PitchExtractionOptions::samp_freq.

Referenced by UnitTestFeatWithKeele().

528  {
529  // you need to use sox to change sampling rate
530  // e.g. sox -r 10k input.wav output.wav
531  // put them in keele/(samp_rate in kHz)+"kHz" e.g. keele/10kHz
532  int sample_rate = 16000;
534  op.samp_freq = static_cast<double>(sample_rate);
535  op.lowpass_cutoff = 1000;
536  op.max_f0 = 400;
537  std::string samp_rate = ConvertIntToString(sample_rate/1000);
538  for (int32 i = 1; i < 11; i++) {
539  std::string wavefile;
540  std::string num;
541  if (i < 6) {
542  num = "f"+ConvertIntToString(i)+"nw0000";
543  wavefile = "keele/"+samp_rate+"kHz/"+num+".wav";
544  } else {
545  num = "m"+ConvertIntToString(i-5)+"nw0000";
546  wavefile = "keele/"+samp_rate+"kHz/"+num+".wav";
547  }
548  KALDI_LOG << "--- " << wavefile << " ---";
549  std::ifstream is(wavefile.c_str(), std::ios_base::binary);
550  WaveData wave;
551  wave.Read(is);
552  KALDI_ASSERT(wave.Data().NumRows() == 1);
553  SubVector<BaseFloat> waveform(wave.Data(), 0);
555  ComputeKaldiPitch(op, waveform, &m);
556  std::string outfile = "keele/tmp/+"+num+"-kaldi-samp-freq-"+samp_rate+"kHz.txt";
557  std::ofstream os(outfile.c_str());
558  m.Write(os, false);
559  }
560 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
std::string ConvertIntToString(const int &number)
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
kaldi::int32 int32
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestDivideRoundingDown()

void kaldi::UnitTestDivideRoundingDown ( )

Definition at line 60 of file kaldi-math-test.cc.

References DivideRoundingDown(), rnnlm::i, KALDI_ASSERT, and RandInt().

Referenced by main().

60  {
61  for (int32 i = 0; i < 100; i++) {
62  int32 a = RandInt(-100, 100);
63  int32 b = 0;
64  while (b == 0)
65  b = RandInt(-100, 100);
67  std::floor(static_cast<double>(a) / static_cast<double>(b)));
68  }
69 }
static int32 DivideRoundingDown(int32 a, int32 b)
Returns a / b, rounding towards negative infinity in all cases.
Definition: kaldi-math.h:287
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestDotprod()

static void kaldi::UnitTestDotprod ( )
static

Definition at line 1838 of file matrix-lib-test.cc.

References rnnlm::i, KALDI_ASSERT, Rand(), VectorBase< Real >::SetRandn(), and VecVec().

1838  {
1839  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1840  MatrixIndexT dimM = 200 + Rand()%100;
1841  Vector<Real> v(dimM), w(dimM);
1842 
1843  v.SetRandn();
1844  w.SetRandn();
1845  Vector<double> wd(w);
1846 
1847  Real f = VecVec(w, v), f2 = VecVec(wd, v), f3 = VecVec(v, wd);
1848  Real sum = 0.0;
1849  for (MatrixIndexT i = 0;i < dimM;i++) sum += v(i)*w(i);
1850  KALDI_ASSERT(std::abs(f-sum) < 0.001);
1851  KALDI_ASSERT(std::abs(f2-sum) < 0.001);
1852  KALDI_ASSERT(std::abs(f3-sum) < 0.001);
1853  }
1854 }
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ UnitTestEig()

static void kaldi::UnitTestEig ( )
static

Definition at line 1432 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), AssertEqual(), CreateEigenvalueMatrix(), MatrixBase< Real >::Eig(), rnnlm::i, InitRandNonsingular(), MatrixBase< Real >::Invert(), kNoTrans, Log(), and MatrixBase< Real >::LogDet().

1432  {
1433 
1434  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1435  MatrixIndexT dimM = 1 + iter;
1436  /* if (iter < 10)
1437  dimM = 1 + Rand() % 6;
1438  else
1439  dimM = 5 + Rand()%10; */
1440  Matrix<Real> M(dimM, dimM);
1441  InitRandNonsingular(&M);
1442  Matrix<Real> P(dimM, dimM);
1443  Vector<Real> real_eigs(dimM), imag_eigs(dimM);
1444  M.Eig(&P, &real_eigs, &imag_eigs);
1445 
1446  { // Check that the eigenvalues match up with the determinant.
1447  BaseFloat logdet_check = 0.0, logdet = M.LogDet();
1448  for (MatrixIndexT i = 0; i < dimM ; i++)
1449  logdet_check += 0.5 * Log(real_eigs(i)*real_eigs(i) + imag_eigs(i)*imag_eigs(i));
1450  AssertEqual(logdet_check, logdet);
1451  }
1452  Matrix<Real> Pinv(P);
1453  Pinv.Invert();
1454  Matrix<Real> D(dimM, dimM);
1455  CreateEigenvalueMatrix(real_eigs, imag_eigs, &D);
1456 
1457  // check that M = P D P^{-1}.
1458  Matrix<Real> tmp(dimM, dimM);
1459  tmp.AddMatMat(1.0, P, kNoTrans, D, kNoTrans, 0.0); // tmp = P * D
1460  Matrix<Real> M2(dimM, dimM);
1461  M2.AddMatMat(1.0, tmp, kNoTrans, Pinv, kNoTrans, 0.0); // M2 = tmp * Pinv = P * D * Pinv.
1462 
1463  { // print out some stuff..
1464  Matrix<Real> MP(dimM, dimM);
1465  MP.AddMatMat(1.0, M, kNoTrans, P, kNoTrans, 0.0);
1466  Matrix<Real> PD(dimM, dimM);
1467  PD.AddMatMat(1.0, P, kNoTrans, D, kNoTrans, 0.0);
1468 
1469  Matrix<Real> PinvMP(dimM, dimM);
1470  PinvMP.AddMatMat(1.0, Pinv, kNoTrans, MP, kNoTrans, 0.0);
1471  AssertEqual(MP, PD);
1472  }
1473 
1474  AssertEqual(M, M2); // check reconstruction worked.
1475  }
1476 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
double Log(double x)
Definition: kaldi-math.h:100
A class representing a vector.
Definition: kaldi-vector.h:406
void CreateEigenvalueMatrix(const VectorBase< Real > &re, const VectorBase< Real > &im, MatrixBase< Real > *D)
Creates the eigenvalue matrix D that is part of the decomposition used Matrix::Eig.
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
static void InitRandNonsingular(SpMatrix< Real > *M)

◆ UnitTestEigSp()

static void kaldi::UnitTestEigSp ( )
static

Definition at line 1479 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2Vec(), SpMatrix< Real >::AddSp(), SpMatrix< Real >::ApproxEqual(), VectorBase< Real >::Data(), SpMatrix< Real >::Eig(), rnnlm::i, InitRandNonsingular(), KALDI_ASSERT, KALDI_LOG, kNoTrans, and Rand().

1479  {
1480  // Test the Eig function with SpMatrix.
1481  // We make sure to test pathological cases, that have
1482  // either large zero eigenspaces, or two large
1483  // eigenspaces with the same absolute value but +ve
1484  // and -ve. Also zero matrix.
1485 
1486  for (MatrixIndexT iter = 0; iter < 100; iter++) {
1487  MatrixIndexT dimM = 1 + (Rand() % 10);
1488  SpMatrix<Real> S(dimM);
1489 
1490  switch (iter % 5) {
1491  case 0: // zero matrix.
1492  break;
1493  case 1: // general random symmetric matrix.
1494  InitRandNonsingular(&S);
1495  break;
1496  default:
1497  { // start with a random matrix; do decomposition; change the eigenvalues to
1498  // try to cover the problematic cases; reconstruct.
1499  InitRandNonsingular(&S);
1500  Vector<Real> s(dimM); Matrix<Real> P(dimM, dimM);
1501  S.Eig(&s, &P);
1502  // We on purpose create a problematic case where
1503  // some eigs are either zero or share a value (+ve or -ve)
1504  // with some other eigenvalue.
1505  for (MatrixIndexT i = 0; i < dimM; i++) {
1506  if (Rand() % 10 == 0) s(i) = 0; // set that eig to zero.
1507  else if (Rand() % 10 < 2) {
1508  // set that eig to some other randomly chosen eig,
1509  // times random sign.
1510  s(i) = (Rand()%2 == 0 ? 1 : -1) * s(Rand() % dimM);
1511  }
1512  }
1513  // Reconstruct s from the eigenvalues "made problematic."
1514  S.AddMat2Vec(1.0, P, kNoTrans, s, 0.0);
1515  Real *data = s.Data();
1516  std::sort(data, data+dimM);
1517  KALDI_LOG << "Real eigs are: " << s;
1518 
1519  }
1520  }
1521  Vector<Real> s(dimM); Matrix<Real> P(dimM, dimM);
1522  S.Eig(&s, &P);
1523  KALDI_LOG << "Found eigs are: " << s;
1524  SpMatrix<Real> S2(dimM);
1525  S2.AddMat2Vec(1.0, P, kNoTrans, s, 0.0);
1526  {
1527  SpMatrix<Real> diff(S);
1528  diff.AddSp(-1.0, S2);
1529  Vector<Real> s(dimM); Matrix<Real> P(dimM, dimM);
1530  diff.Eig(&s, &P);
1531  KALDI_LOG << "Eigs of difference are " << s;
1532  }
1533  KALDI_ASSERT(S.ApproxEqual(S2, 1.0e-03f));
1534  }
1535 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void InitRandNonsingular(SpMatrix< Real > *M)
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestEigSymmetric()

static void kaldi::UnitTestEigSymmetric ( )
static

Definition at line 1413 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), AssertEqual(), MatrixBase< Real >::Eig(), KALDI_ASSERT, kNoTrans, kTrans, MatrixBase< Real >::MulColsVec(), Rand(), PackedMatrix< Real >::SetRandn(), and VectorBase< Real >::Sum().

1413  {
1414 
1415  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1416  MatrixIndexT dimM = 20 + Rand()%10;
1417  SpMatrix<Real> S(dimM);
1418  S.SetRandn();
1419  Matrix<Real> M(S); // copy to regular matrix.
1420  Matrix<Real> P(dimM, dimM);
1421  Vector<Real> real_eigs(dimM), imag_eigs(dimM);
1422  M.Eig(&P, &real_eigs, &imag_eigs);
1423  KALDI_ASSERT(imag_eigs.Sum() == 0.0);
1424  // should have M = P D P^T
1425  Matrix<Real> tmp(P); tmp.MulColsVec(real_eigs); // P * eigs
1426  Matrix<Real> M2(dimM, dimM);
1427  M2.AddMatMat(1.0, tmp, kNoTrans, P, kTrans, 0.0); // M2 = tmp * Pinv = P * eigs * P^T
1428  AssertEqual(M, M2); // check reconstruction worked.
1429  }
1430 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestEnsureNonzero()

static void kaldi::UnitTestEnsureNonzero ( )
static

Definition at line 73 of file cu-math-test.cc.

References kaldi::cu::EnsureNonzero(), rnnlm::i, KALDI_ASSERT, kUndefined, Rand(), RandInt(), and CuMatrixBase< Real >::SetRandn().

73  {
74  int32 M = 100 + Rand() % 200, N = 100 + Rand() % 200;
75  Real epsilon = 0.1;
76  CuMatrix<Real> x(M, N);
77  x.SetRandn();
78  CuMatrix<Real> y(M, N, kUndefined);
79  cu::EnsureNonzero(x, epsilon, &y);
80  Matrix<Real> x_cpu(x);
81  Matrix<Real> y_cpu(y);
82  for (int32 i = 0; i < 30; i++) {
83  int32 r = RandInt(0, M-1), c = RandInt(0, N-1);
84  Real src = x_cpu(r, c), dest = y_cpu(r, c);
85  if (src <= -epsilon || src >= epsilon) {
86  KALDI_ASSERT(src == dest);
87  } else if (src >= 0) {
88  KALDI_ASSERT(dest == epsilon);
89  } else {
90  KALDI_ASSERT(dest == -epsilon);
91  }
92  }
93 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void EnsureNonzero(const CuMatrixBase< Real > &src, Real epsilon, CuMatrixBase< Real > *dest)
This function requires that src and dest have the same dimension and epsilon > 0. ...
Definition: cu-math.cc:209
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestError()

void kaldi::UnitTestError ( )

Definition at line 29 of file kaldi-error-test.cc.

References MyFunction1().

Referenced by main().

29  {
30  {
31  std::cerr << "Ignore next error:\n";
32  MyFunction1();
33  }
34 }
void MyFunction1()

◆ UnitTestEstimateMmieDiagGmm()

void kaldi::UnitTestEstimateMmieDiagGmm ( )

Definition at line 30 of file ebw-diag-gmm-test.cc.

References AccumDiagGmm::AccumulateFromDiag(), VectorBase< Real >::AddVec(), VectorBase< Real >::AddVec2(), VectorBase< Real >::ApplyPow(), DiagGmm::ComputeGconsts(), MatrixBase< Real >::CopyFromMat(), VectorBase< Real >::CopyRowFromMat(), count, rnnlm::d, DiagGmm::Dim(), Exp(), GmmFlagsToString(), rnnlm::i, MatrixBase< Real >::InvertElements(), IsmoothStatsDiagGmm(), KALDI_LOG, KALDI_WARN, kGmmMeans, kGmmVariances, kGmmWeights, DiagGmm::NumGauss(), Rand(), RandGauss(), RandInt(), DiagGmm::Resize(), AccumDiagGmm::Resize(), VectorBase< Real >::Scale(), DiagGmm::SetInvVarsAndMeans(), DiagGmm::SetWeights(), AccumDiagGmm::SetZero(), DiagGmm::Split(), UpdateEbwDiagGmm(), UpdateEbwWeightsDiagGmm(), and DiagGmm::weights().

Referenced by main().

30  {
31  size_t dim = RandInt(5, 10); // dimension of the gmm
32  size_t nMix = 2; // number of mixtures in the data
33  size_t maxiterations = RandInt(2, 5); // number of iterations for estimation
34 
35  // maximum number of densities in the GMM
36  // larger than the number of mixtures in the data
37  // so that we can test the removal of unseen components
38  int32 maxcomponents = 10;
39 
40  // generate random feature vectors
41  Matrix<BaseFloat> means_f(nMix, dim), vars_f(nMix, dim);
42  // first, generate random mean and variance vectors
43  for (size_t m = 0; m < nMix; m++) {
44  for (size_t d= 0; d < dim; d++) {
45  means_f(m, d) = kaldi::RandGauss()*100.0F;
46  vars_f(m, d) = Exp(kaldi::RandGauss())*1000.0F+ 1.0F;
47  }
48  // std::cout << "Gauss " << m << ": Mean = " << means_f.Row(m) << '\n'
49  // << "Vars = " << vars_f.Row(m) << '\n';
50  }
51 
52  // Numerator stats
53  // second, generate 1000 feature vectors for each of the mixture components
54  size_t counter_num = 0, multiple = 200;
55  Matrix<BaseFloat> feats_num(nMix*multiple, dim);
56  for (size_t m = 0; m < nMix; m++) {
57  for (size_t i = 0; i < multiple; i++) {
58  for (size_t d = 0; d < dim; d++) {
59  feats_num(counter_num, d) = means_f(m, d) + kaldi::RandGauss() *
60  std::sqrt(vars_f(m, d));
61  }
62  counter_num++;
63  }
64  }
65 
66  // Denominator stats
67  // second, generate 1000 feature vectors for each of the mixture components
68  size_t counter_den = 0;
69  Matrix<BaseFloat> feats_den(nMix*multiple, dim);
70  for (size_t m = 0; m < nMix; m++) {
71  for (size_t i = 0; i < multiple; i++) {
72  for (size_t d = 0; d < dim; d++) {
73  feats_den(counter_den, d) = means_f(m, d) + kaldi::RandGauss() *
74  std::sqrt(vars_f(m, d));
75  }
76  counter_den++;
77  }
78  }
79 
80  // Compute the global mean and variance
81  Vector<BaseFloat> mean_acc(dim);
82  Vector<BaseFloat> var_acc(dim);
83  Vector<BaseFloat> featvec(dim);
84  for (size_t i = 0; i < counter_num; i++) {
85  featvec.CopyRowFromMat(feats_num, i);
86  mean_acc.AddVec(1.0, featvec);
87  featvec.ApplyPow(2.0);
88  var_acc.AddVec(1.0, featvec);
89  }
90  mean_acc.Scale(1.0F/counter_num);
91  var_acc.Scale(1.0F/counter_num);
92  var_acc.AddVec2(-1.0, mean_acc);
93  // std::cout << "Mean acc = " << mean_acc << '\n' << "Var acc = "
94  // << var_acc << '\n';
95 
96  // write the feature vectors to a file
97  std::ofstream of("tmpfeats");
98  of.precision(10);
99  of << feats_num;
100  of.close();
101 
102  // now generate randomly initial values for the GMM
103  Vector<BaseFloat> weights(1);
104  Matrix<BaseFloat> means(1, dim), vars(1, dim), invvars(1, dim);
105  for (size_t d= 0; d < dim; d++) {
106  means(0, d) = kaldi::RandGauss()*100.0F;
107  vars(0, d) = Exp(kaldi::RandGauss()) *10.0F + 1e-5F;
108  }
109  weights(0) = 1.0F;
110  invvars.CopyFromMat(vars);
111  invvars.InvertElements();
112 
113  // new GMM
114  DiagGmm *gmm = new DiagGmm();
115  gmm->Resize(1, dim);
116  gmm->SetWeights(weights);
117  gmm->SetInvVarsAndMeans(invvars, means);
118  gmm->ComputeGconsts();
119 
120 
121  EbwOptions ebw_opts;
122  EbwWeightOptions ebw_weight_opts;
123 
124  int r = Rand() % 16;
125  GmmFlagsType flags = (r%2 == 0 ? kGmmMeans : 0)
126  + ((r/2)%2 == 0 ? kGmmVariances : 0)
127  + ((r/4)%2 == 0 ? kGmmWeights : 0);
128  double tau = (r/8)%2 == 0 ? 100 : 0.0;
129 
130  if ((flags & kGmmVariances) && !(flags & kGmmMeans)) {
131  delete gmm;
132  return; // Don't do this case: not supported in the update equations.
133  }
134 
135  AccumDiagGmm num;
136  AccumDiagGmm den;
137 
138  num.Resize(gmm->NumGauss(), gmm->Dim(), flags);
139  num.SetZero(flags);
140  den.Resize(gmm->NumGauss(), gmm->Dim(), flags);
141  den.SetZero(flags);
142 
143  size_t iteration = 0;
144  double last_log_like_diff = NAN;
145  while (iteration < maxiterations) {
146  Vector<BaseFloat> featvec_num(dim);
147  Vector<BaseFloat> featvec_den(dim);
148  num.Resize(gmm->NumGauss(), gmm->Dim(), flags);
149  num.SetZero(flags);
150  den.Resize(gmm->NumGauss(), gmm->Dim(), flags);
151  den.SetZero(flags);
152 
153  double loglike_num = 0.0;
154  double loglike_den = 0.0;
155  for (size_t i = 0; i < counter_num; i++) {
156  featvec_num.CopyRowFromMat(feats_num, i);
157  loglike_num += static_cast<double>(num.AccumulateFromDiag(*gmm,
158  featvec_num, 1.0F));
159  // std::cout << "Mean accum_num: " << num.mean_accumulator() << '\n';
160  }
161  for (size_t i = 0; i < counter_den; i++) {
162  featvec_den.CopyRowFromMat(feats_den, i);
163  loglike_den += static_cast<double>(den.AccumulateFromDiag(*gmm,
164  featvec_den, 1.0F));
165  // std::cout << "Mean accum_den: " << den.mean_accumulator() << '\n';
166  }
167 
168  std::cout << "Loglikelihood Num before iteration " << iteration << " : "
169  << std::scientific << loglike_num << " number of components: "
170  << gmm->NumGauss() << '\n';
171 
172  std::cout << "Loglikelihood Den before iteration " << iteration << " : "
173  << std::scientific << loglike_den << " number of components: "
174  << gmm->NumGauss() << '\n';
175 
176  double loglike_diff = loglike_num - loglike_den;
177  if (iteration > 0) {
178  KALDI_LOG << "Objective changed " << last_log_like_diff
179  << " to " << loglike_diff;
180  if (loglike_diff < last_log_like_diff)
181  KALDI_WARN << "Objective decreased (flags = "
182  << GmmFlagsToString(flags) << ", tau = " << tau << " )";
183  }
184  last_log_like_diff = loglike_diff;
185 
186  AccumDiagGmm num_smoothed(num);
187  IsmoothStatsDiagGmm(num, tau, &num_smoothed); // Apply I-smoothing.
188 
189  BaseFloat auxf_gauss, auxf_weight, count;
190  std::cout << "MEANX: " << gmm->weights() << '\n';
191 
192  int32 num_floored;
193  UpdateEbwDiagGmm(num_smoothed, den, flags, ebw_opts,
194  gmm, &auxf_gauss, &count, &num_floored);
195 
196  if (flags & kGmmWeights) {
197  UpdateEbwWeightsDiagGmm(num, den, ebw_weight_opts, gmm, &auxf_weight,
198  &count);
199  }
200 
201  // mean_hlp.CopyFromVec(gmm->means_invvars().Row(0));
202  // std::cout << "MEANY: " << mean_hlp << '\n';
203  std::cout << "MEANY: " << gmm->weights() << '\n';
204 
205 
206  if ((iteration % 3 == 1) && (gmm->NumGauss() * 2 <= maxcomponents)) {
207  gmm->Split(gmm->NumGauss() * 2, 0.001);
208  std::cout << "Ngauss, Ndim: " << gmm->NumGauss() << " " << gmm->Dim() << '\n';
209  }
210 
211  iteration++;
212  }
213  delete gmm;
214 
215  unlink("tmpfeats");
216 }
double Exp(double x)
Definition: kaldi-math.h:83
void UpdateEbwWeightsDiagGmm(const AccumDiagGmm &num_stats, const AccumDiagGmm &den_stats, const EbwWeightOptions &opts, DiagGmm *gmm, BaseFloat *auxf_change_out, BaseFloat *count_out)
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
uint16 GmmFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:35
void IsmoothStatsDiagGmm(const AccumDiagGmm &src_stats, double tau, AccumDiagGmm *dst_stats)
I-Smooth the stats. src_stats and dst_stats do not have to be different.
void UpdateEbwDiagGmm(const AccumDiagGmm &num_stats, const AccumDiagGmm &den_stats, GmmFlagsType flags, const EbwOptions &opts, DiagGmm *gmm, BaseFloat *auxf_change_out, BaseFloat *count_out, int32 *num_floored_out)
Definition: ebw-diag-gmm.cc:94
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string GmmFlagsToString(GmmFlagsType flags)
Convert GMM flags to string.
Definition: model-common.cc:43
#define KALDI_LOG
Definition: kaldi-error.h:153
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestExpSpeed()

void kaldi::UnitTestExpSpeed ( )

Definition at line 276 of file kaldi-math-test.cc.

References Timer::Elapsed(), Exp(), rnnlm::i, KALDI_ASSERT, and KALDI_LOG.

276  {
277  Real sum = 0.0; // compute the sum to avoid optimizing it away.
278  Real time = 0.01; // how long this should last.
279  int block_size = 10;
280  int num_ops = 0;
281  Timer tim;
282  while (tim.Elapsed() < time) {
283  for (int i = 0; i < block_size; i++) {
284  sum += Exp((Real)i);
285  }
286  num_ops += block_size;
287  }
288  KALDI_ASSERT(sum > 0.0); // make it harder for the compiler to optimize Exp
289  // away, as we have a conditional.
290  Real flops = 1.0e-06 * num_ops / tim.Elapsed();
291  KALDI_LOG << "Megaflops doing Exp("
292  << (sizeof(Real) == 4 ? "float" : "double") << ") is " << flops;
293 }
double Exp(double x)
Definition: kaldi-math.h:83
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestExtractCompressedMatrix()

static void kaldi::UnitTestExtractCompressedMatrix ( )
static

Definition at line 4435 of file matrix-lib-test.cc.

References MatrixBase< Real >::ApproxEqual(), CompressedMatrix::CopyToMat(), rnnlm::i, KALDI_ERR, KALDI_VLOG, Rand(), and MatrixBase< Real >::SetRandn().

4435  {
4436  for (int32 i = 0; i < 30; i++) {
4437  MatrixIndexT num_rows = Rand() % 20, num_cols = Rand() % 30;
4438  if (num_rows * num_cols == 0) {
4439  // this test wouldn't work for empty matrices.
4440  num_rows++;
4441  num_cols++;
4442  }
4443  Matrix<Real> mat(num_rows, num_cols);
4444  mat.SetRandn();
4445  CompressedMatrix cmat(mat);
4446 
4447  MatrixIndexT row_offset = Rand() % num_rows, col_offset = Rand() % num_cols;
4448  MatrixIndexT sub_num_rows = Rand() % (num_rows - row_offset) + 1,
4449  sub_num_cols = Rand() % (num_cols - col_offset) + 1;
4450  KALDI_VLOG(3) << "Whole matrix size: " << num_rows << "," << num_cols;
4451  KALDI_VLOG(3) << "Sub-matrix size: " << sub_num_rows << "," << sub_num_cols
4452  << " with offsets " << row_offset << "," << col_offset;
4453  CompressedMatrix cmat2(cmat, row_offset, sub_num_rows, //take a subset of
4454  col_offset, sub_num_cols); // the compressed matrix
4455  Matrix<Real> mat2(sub_num_rows, sub_num_cols);
4456  cmat2.CopyToMat(&mat2); // uncompress the subset of the compressed matrix
4457 
4458  Matrix<Real> mat3(cmat); // uncompress the whole compressed matrix
4459  SubMatrix<Real> sub_mat(mat3, row_offset, sub_num_rows, col_offset, sub_num_cols);
4460  if(!sub_mat.ApproxEqual(mat2)) {
4461  KALDI_ERR << "Matrices differ " << sub_mat << " vs. " << mat2;
4462  }
4463  }
4464 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
Sub-matrix representation.
Definition: kaldi-matrix.h:988

◆ UnitTestFactorize()

void kaldi::UnitTestFactorize ( )

Definition at line 249 of file kaldi-math-test.cc.

Referenced by main().

249  {
250  UnitTestFactorizeTpl<int>();
251  UnitTestFactorizeTpl<size_t>();
252  UnitTestFactorizeTpl<int16>();
253 }

◆ UnitTestFactorizeTpl()

void kaldi::UnitTestFactorizeTpl ( )

Definition at line 232 of file kaldi-math-test.cc.

References Factorize(), rnnlm::i, KALDI_ASSERT, and Rand().

232  {
233  for (int p= 0; p < 100; p++) {
234  I m = Rand() % 100000;
235  if (m >= 1) {
236  std::vector<I> factors;
237  Factorize(m, &factors);
238  I m2 = 1;
239  for (size_t i = 0; i < factors.size(); i++) {
240  m2 *= factors[i];
241  if (i+1 < factors.size())
242  KALDI_ASSERT(factors[i+1] >= factors[i]); // check sorted.
243  }
244  KALDI_ASSERT(m2 == m); // check correctness.
245  }
246  }
247 }
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Factorize(I m, std::vector< I > *factors)
Definition: kaldi-math.h:325

◆ UnitTestFeatNoKeele()

static void kaldi::UnitTestFeatNoKeele ( )
static

Definition at line 596 of file pitch-functions-test.cc.

References UnitTestDelay(), UnitTestPieces(), UnitTestSearch(), UnitTestSimple(), and UnitTestSnipEdges().

Referenced by main().

596  {
597  UnitTestSimple();
598  UnitTestPieces();
600  UnitTestDelay();
601  UnitTestSearch();
602 }
static void UnitTestSnipEdges()
static void UnitTestSimple()
static void UnitTestPieces()
static void UnitTestDelay()
static void UnitTestSearch()

◆ UnitTestFeatWithKeele()

static void kaldi::UnitTestFeatWithKeele ( )
static

◆ UnitTestFFTbasedBlockConvolution()

void kaldi::UnitTestFFTbasedBlockConvolution ( )

Definition at line 26 of file signal-test.cc.

References AssertEqual(), VectorBase< Real >::Dim(), FFTbasedBlockConvolveSignals(), FFTbasedConvolveSignals(), rnnlm::i, Rand(), and VectorBase< Real >::SetRandn().

Referenced by main().

26  {
27  for (int32 i = 0; i < 5; i++) {
28  int32 signal_length = 400000 + Rand() % 40000;
29  int32 filter_length = 1000 + Rand() % 100;
30  Vector<BaseFloat> signal(signal_length);
31  Vector<BaseFloat> filter(filter_length);
32  signal.SetRandn();
33  filter.SetRandn();
34  Vector<BaseFloat> signal_test(signal);
35  FFTbasedConvolveSignals(filter, &signal_test);
36  FFTbasedBlockConvolveSignals(filter, &signal);
37  AssertEqual(signal, signal_test, 0.000001 * signal.Dim());
38  }
39 }
kaldi::int32 int32
void FFTbasedConvolveSignals(const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
Definition: signal.cc:50
void FFTbasedBlockConvolveSignals(const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
Definition: signal.cc:77
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestFFTbasedConvolution()

void kaldi::UnitTestFFTbasedConvolution ( )

Definition at line 41 of file signal-test.cc.

References AssertEqual(), ConvolveSignals(), VectorBase< Real >::Dim(), FFTbasedConvolveSignals(), rnnlm::i, Rand(), and VectorBase< Real >::SetRandn().

Referenced by main().

41  {
42  for (int32 i = 0; i < 5; i++) {
43  int32 signal_length = 4000 + Rand() % 400;
44  int32 filter_length = 10 + Rand() % 10;
45  Vector<BaseFloat> signal(signal_length);
46  Vector<BaseFloat> filter(filter_length);
47  signal.SetRandn();
48  filter.SetRandn();
49  Vector<BaseFloat> signal_test(signal);
50  ConvolveSignals(filter, &signal_test);
51  FFTbasedConvolveSignals(filter, &signal);
52  AssertEqual(signal, signal_test, 0.0001 * signal.Dim());
53  }
54 }
kaldi::int32 int32
void FFTbasedConvolveSignals(const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
Definition: signal.cc:50
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
void ConvolveSignals(const Vector< BaseFloat > &filter, Vector< BaseFloat > *signal)
Definition: signal.cc:34
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestFloorCeiling()

static void kaldi::UnitTestFloorCeiling ( )
static

Definition at line 2284 of file matrix-lib-test.cc.

References VectorBase< Real >::ApplyCeiling(), VectorBase< Real >::ApplyFloor(), AssertEqual(), rnnlm::d, rnnlm::i, KALDI_ASSERT, Rand(), and VectorBase< Real >::SetRandn().

2284  {
2285  for (MatrixIndexT i = 0; i < 5; i++) {
2286  MatrixIndexT dimM = 10 + Rand() % 10;
2287  Vector<Real> v(dimM);
2288  v.SetRandn();
2289  Real pivot = v(5);
2290  Vector<Real> f(v), f2(v), c(v), c2(v);
2291  MatrixIndexT floored2;
2292  f.ApplyFloor(pivot, &floored2);
2293  MatrixIndexT ceiled2;
2294  c.ApplyCeiling(pivot, &ceiled2);
2295  MatrixIndexT floored = 0, ceiled = 0;
2296  for (MatrixIndexT d = 0; d < dimM; d++) {
2297  if (f2(d) < pivot) { f2(d) = pivot; floored++; }
2298  if (c2(d) > pivot) { c2(d) = pivot; ceiled++; }
2299  }
2300  AssertEqual(f, f2);
2301  AssertEqual(c, c2);
2302  KALDI_ASSERT(floored == floored2);
2303  KALDI_ASSERT(ceiled == ceiled2);
2304 
2305  // Check that the non-counting variants are equivalent to the counting
2306  // variants.
2307  Vector<Real> f3(v);
2308  f3.ApplyFloor(pivot);
2309  AssertEqual(f2, f3);
2310 
2311  Vector<Real> c3(v);
2312  c3.ApplyCeiling(pivot);
2313  AssertEqual(c2, c3);
2314  }
2315 }
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestFloorChol()

static void kaldi::UnitTestFloorChol ( )
static

Definition at line 2223 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), SpMatrix< Real >::ApplyFloor(), rnnlm::i, InitRandNonsingular(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, kNoTrans, Rand(), PackedMatrix< Real >::Scale(), VectorBase< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and VecSpVec().

2223  {
2224  for (MatrixIndexT i = 0;i < 10;i++) {
2225  MatrixIndexT dimM = 20 + Rand()%10;
2226 
2227 
2228  MatrixIndexT dimN = 20 + Rand()%10;
2229  Matrix<Real> X(dimM, dimN);
2230  X.SetRandn();
2231  SpMatrix<Real> B(dimM);
2232  B.AddMat2(1.0, X, kNoTrans, 0.0); // B = X*X^T -> positive semidefinite.
2233 
2234  float alpha = (Rand() % 10) + 0.5;
2235  Matrix<Real> M(dimM, dimM);
2236  M.SetRandn();
2237  SpMatrix<Real> C(dimM);
2238  C.AddMat2(1.0, M, kNoTrans, 0.0); // C:=M*M^T
2239  InitRandNonsingular(&M);
2240  C.AddMat2(1.0, M, kNoTrans, 1.0); // C+=M*M^T (after making new random M)
2241  if (i%2 == 0)
2242  C.Scale(0.001); // so it's not too much bigger than B (or it's trivial)
2243  SpMatrix<Real> BFloored(B); BFloored.ApplyFloor(C, alpha);
2244 
2245 
2246  for (MatrixIndexT j = 0;j < 10;j++) {
2247  Vector<Real> v(dimM);
2248  v.SetRandn();
2249  Real ip_b = VecSpVec(v, B, v);
2250  Real ip_a = VecSpVec(v, BFloored, v);
2251  Real ip_c = alpha * VecSpVec(v, C, v);
2252  if (i < 3) KALDI_LOG << "alpha = " << alpha << ", ip_a = " << ip_a << " ip_b = " << ip_b << " ip_c = " << ip_c <<'\n';
2253  KALDI_ASSERT(ip_a>=ip_b*0.999 && ip_a>=ip_c*0.999);
2254  }
2255  }
2256 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Real VecSpVec(const VectorBase< Real > &v1, const SpMatrix< Real > &M, const VectorBase< Real > &v2)
Computes v1^T * M * v2.
Definition: sp-matrix.cc:964
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void InitRandNonsingular(SpMatrix< Real > *M)
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestFloorUnit()

static void kaldi::UnitTestFloorUnit ( )
static

Definition at line 2261 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), SpMatrix< Real >::ApplyFloor(), rnnlm::i, KALDI_ASSERT, kNoTrans, VectorBase< Real >::Min(), Rand(), MatrixBase< Real >::SetRandn(), and SpMatrix< Real >::SymPosSemiDefEig().

2261  {
2262  for (MatrixIndexT i = 0;i < 5;i++) {
2263  MatrixIndexT dimM = 20 + Rand()%10;
2264  MatrixIndexT dimN = 20 + Rand()%10;
2265  float floor = (Rand() % 10) - 3;
2266 
2267  Matrix<Real> M(dimM, dimN);
2268  M.SetRandn();
2269  SpMatrix<Real> B(dimM);
2270  B.AddMat2(1.0, M, kNoTrans, 0.0); // B = M*M^T -> positive semidefinite.
2271 
2272  SpMatrix<Real> BFloored(B);
2273  BFloored.ApplyFloor(floor);
2274 
2275 
2276  Vector<Real> s(dimM); Matrix<Real> P(dimM, dimM); B.SymPosSemiDefEig(&s, &P);
2277  Vector<Real> s2(dimM); Matrix<Real> P2(dimM, dimM); BFloored.SymPosSemiDefEig(&s2, &P2);
2278 
2279  KALDI_ASSERT ( (s.Min() >= floor && std::abs(s2.Min()-s.Min())<0.01) || std::abs(s2.Min()-floor)<0.01);
2280  }
2281 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestFmllrDiagGmm()

void kaldi::UnitTestFmllrDiagGmm ( )

Definition at line 50 of file fmllr-diag-gmm-test.cc.

References FmllrDiagGmmAccs::AccumulateForGmm(), FmllrDiagGmmAccs::AccumulateFromPosteriors(), ApplyAffineTransform(), ApplyFeatureTransformToStats(), ApproxEqual(), DiagGmm::ComponentPosteriors(), count, DiagGmm::Dim(), DiagGmm::Generate(), rnnlm::i, InitRandomGmm(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, DiagGmm::NumGauss(), MatrixBase< Real >::SetUnit(), and FmllrDiagGmmAccs::Update().

Referenced by main().

50  {
51  using namespace kaldi;
52  DiagGmm gmm;
53  InitRandomGmm(&gmm);
54  int32 dim = gmm.Dim();
55  int32 npoints = dim*(dim+1)*5;
56  Matrix<BaseFloat> rand_points(npoints, dim);
57  for (int32 i = 0; i < npoints; i++) {
58  SubVector<BaseFloat> row(rand_points, i);
59  gmm.Generate(&row);
60  }
61  Matrix<BaseFloat> cur_xform(dim, dim+1);
62  cur_xform.SetUnit(); // set diag to unit.
63 
64  int32 niters = 5;
65  BaseFloat objf_change_tot = 0.0, objf_change, count;
66  for (int32 j = 0; j < niters; j++) {
67  FmllrOptions opts;
68  FmllrDiagGmmAccs stats(dim, j % 2 == 0 ? opts : FmllrOptions());
69  for (int32 i = 0; i < npoints; i++) {
70  SubVector<BaseFloat> row(rand_points, i);
71  if (j == 0) { // split this case off to exercise more of the code.
72  stats.AccumulateForGmm(gmm, row, 1.0);
73  } else {
74  Vector<BaseFloat> xformed_row(row);
75  ApplyAffineTransform(cur_xform, &xformed_row);
76  Vector<BaseFloat> posteriors(gmm.NumGauss());
77  gmm.ComponentPosteriors(xformed_row, &posteriors);
78  stats.AccumulateFromPosteriors(gmm, row, posteriors);
79  }
80  }
81  stats.Update(opts, &cur_xform, &objf_change, &count);
82  { // Test for ApplyFeatureTransformToStats:
83  BaseFloat objf_change_tmp, count_tmp;
84  ApplyFeatureTransformToStats(cur_xform, &stats);
85  Matrix<BaseFloat> mat(dim, dim+1);
86  mat.SetUnit();
87  stats.Update(opts, &mat, &objf_change_tmp, &count_tmp);
88  // After we apply this transform to the stats, there should
89  // be nothing to gain from further transforming the data.
90  KALDI_ASSERT(objf_change_tmp/count_tmp < 0.01);
91  }
92  KALDI_LOG << "Objf change on iter " << j << " is " << objf_change;
93  objf_change_tot += objf_change;
94  }
95  KALDI_ASSERT(ApproxEqual(count, npoints));
96  int32 num_params = dim*(dim+1);
97  BaseFloat expected_objf_change = 0.5 * num_params;
98  KALDI_LOG << "Expected objf change is: not much more than " << expected_objf_change
99  <<", seen: " << objf_change_tot;
100  KALDI_ASSERT(objf_change_tot < 2.0 * expected_objf_change); // or way too much.
101  // This test relies on statistical laws and if it fails it does not *necessarily*
102  // mean that something is wrong.
103 }
void InitRandomGmm(DiagGmm *gmm_in)
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
This does not work with multiple feature transforms.
kaldi::int32 int32
void ApplyFeatureTransformToStats(const MatrixBase< BaseFloat > &xform, AffineXformStats *stats)
This function applies a feature-level transform to stats (useful for certain techniques based on fMLL...
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void ApplyAffineTransform(const MatrixBase< BaseFloat > &xform, VectorBase< BaseFloat > *vec)
Applies the affine transform &#39;xform&#39; to the vector &#39;vec&#39; and overwrites the contents of &#39;vec&#39;...
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestFmllrDiagGmmDiagonal()

void kaldi::UnitTestFmllrDiagGmmDiagonal ( )

Definition at line 107 of file fmllr-diag-gmm-test.cc.

References FmllrDiagGmmAccs::AccumulateForGmm(), FmllrDiagGmmAccs::AccumulateFromPosteriors(), ApplyAffineTransform(), ApplyModelTransformToStats(), ApproxEqual(), DiagGmm::ComponentPosteriors(), count, DiagGmm::Dim(), DiagGmm::Generate(), rnnlm::i, InitRandomGmm(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, DiagGmm::NumGauss(), MatrixBase< Real >::SetUnit(), FmllrDiagGmmAccs::Update(), and FmllrOptions::update_type.

Referenced by main().

107  {
108  using namespace kaldi;
109  DiagGmm gmm;
110  InitRandomGmm(&gmm);
111  int32 dim = gmm.Dim();
112  int32 npoints = dim*(dim+1)*5;
113  Matrix<BaseFloat> rand_points(npoints, dim);
114  for (int32 i = 0; i < npoints; i++) {
115  SubVector<BaseFloat> row(rand_points, i);
116  gmm.Generate(&row);
117  }
118  Matrix<BaseFloat> cur_xform(dim, dim+1);
119  cur_xform.SetUnit(); // set diag to unit.
120 
121  int32 niters = 2;
122  BaseFloat objf_change_tot = 0.0, objf_change, count;
123  FmllrOptions opts;
124  opts.update_type = "diag";
125 
126  for (int32 j = 0; j < niters; j++) {
127  FmllrDiagGmmAccs stats(dim, j % 2 == 0 ? opts : FmllrOptions());
128  for (int32 i = 0; i < npoints; i++) {
129  SubVector<BaseFloat> row(rand_points, i);
130  if (j == 0) { // split this case off to exercise more of the code.
131  stats.AccumulateForGmm(gmm, row, 1.0);
132  } else {
133  Vector<BaseFloat> xformed_row(row);
134  ApplyAffineTransform(cur_xform, &xformed_row);
135  Vector<BaseFloat> posteriors(gmm.NumGauss());
136  gmm.ComponentPosteriors(xformed_row, &posteriors);
137  stats.AccumulateFromPosteriors(gmm, row, posteriors);
138  }
139  }
140 
141  stats.Update(opts, &cur_xform, &objf_change, &count);
142  { // Test for ApplyModelTransformToStats:
143  BaseFloat objf_change_tmp, count_tmp;
144  ApplyModelTransformToStats(cur_xform, &stats);
145  Matrix<BaseFloat> mat(dim, dim+1);
146  mat.SetUnit();
147  stats.Update(opts, &mat, &objf_change_tmp, &count_tmp);
148  // After we apply this transform to the stats, there should
149  // be nothing to gain from further transforming the data.
150  KALDI_ASSERT(objf_change_tmp/count_tmp < 0.01);
151  }
152  KALDI_LOG << "Objf change on iter " << j << " is " << objf_change;
153  objf_change_tot += objf_change;
154  }
155  KALDI_ASSERT(ApproxEqual(count, npoints));
156  int32 num_params = dim*2;
157  BaseFloat expected_objf_change = 0.5 * num_params;
158  KALDI_LOG << "Expected objf change is: not much more than " << expected_objf_change
159  <<", seen: " << objf_change_tot;
160  KALDI_ASSERT(objf_change_tot < 2.0 * expected_objf_change); // or way too much.
161  // This test relies on statistical laws and if it fails it does not *necessarily*
162  // mean that something is wrong.
163 }
void ApplyModelTransformToStats(const MatrixBase< BaseFloat > &xform, AffineXformStats *stats)
ApplyModelTransformToStats takes a transform "xform", which must be diagonal (i.e.
void InitRandomGmm(DiagGmm *gmm_in)
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
This does not work with multiple feature transforms.
std::string update_type
"full", "diag", "offset", "none"
kaldi::int32 int32
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void ApplyAffineTransform(const MatrixBase< BaseFloat > &xform, VectorBase< BaseFloat > *vec)
Applies the affine transform &#39;xform&#39; to the vector &#39;vec&#39; and overwrites the contents of &#39;vec&#39;...
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestFmllrDiagGmmOffset()

void kaldi::UnitTestFmllrDiagGmmOffset ( )

Definition at line 167 of file fmllr-diag-gmm-test.cc.

References FmllrDiagGmmAccs::AccumulateForGmm(), FmllrDiagGmmAccs::AccumulateFromPosteriors(), ApplyAffineTransform(), ApplyModelTransformToStats(), ApproxEqual(), DiagGmm::ComponentPosteriors(), count, DiagGmm::Dim(), DiagGmm::Generate(), rnnlm::i, InitRandomGmm(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, DiagGmm::NumGauss(), MatrixBase< Real >::SetUnit(), FmllrDiagGmmAccs::Update(), and FmllrOptions::update_type.

Referenced by main().

167  {
168  using namespace kaldi;
169  DiagGmm gmm;
170  InitRandomGmm(&gmm);
171  int32 dim = gmm.Dim();
172  int32 npoints = dim*(dim+1)*5;
173  Matrix<BaseFloat> rand_points(npoints, dim);
174  for (int32 i = 0; i < npoints; i++) {
175  SubVector<BaseFloat> row(rand_points, i);
176  gmm.Generate(&row);
177  }
178  Matrix<BaseFloat> cur_xform(dim, dim+1);
179  cur_xform.SetUnit(); // set diag to unit.
180 
181  int32 niters = 2;
182  BaseFloat objf_change_tot = 0.0, objf_change, count;
183  FmllrOptions opts;
184  opts.update_type = "offset";
185 
186  for (int32 j = 0; j < niters; j++) {
187  FmllrDiagGmmAccs stats(dim, j % 2 == 0 ? opts : FmllrOptions());
188  for (int32 i = 0; i < npoints; i++) {
189  SubVector<BaseFloat> row(rand_points, i);
190  if (j == 0) { // split this case off to exercise more of the code.
191  stats.AccumulateForGmm(gmm, row, 1.0);
192  } else {
193  Vector<BaseFloat> xformed_row(row);
194  ApplyAffineTransform(cur_xform, &xformed_row);
195  Vector<BaseFloat> posteriors(gmm.NumGauss());
196  gmm.ComponentPosteriors(xformed_row, &posteriors);
197  stats.AccumulateFromPosteriors(gmm, row, posteriors);
198  }
199  }
200 
201  stats.Update(opts, &cur_xform, &objf_change, &count);
202  { // Test for ApplyModelTransformToStats:
203  BaseFloat objf_change_tmp, count_tmp;
204  ApplyModelTransformToStats(cur_xform, &stats);
205  Matrix<BaseFloat> mat(dim, dim+1);
206  mat.SetUnit();
207  stats.Update(opts, &mat, &objf_change_tmp, &count_tmp);
208  // After we apply this transform to the stats, there should
209  // be nothing to gain from further transforming the data.
210  KALDI_ASSERT(objf_change_tmp/count_tmp < 0.01);
211  }
212  KALDI_LOG << "Objf change on iter " << j << " is " << objf_change;
213  objf_change_tot += objf_change;
214  }
215  KALDI_ASSERT(ApproxEqual(count, npoints));
216  int32 num_params = dim;
217  BaseFloat expected_objf_change = 0.5 * num_params;
218  KALDI_LOG << "Expected objf change is: not much more than " << expected_objf_change
219  <<", seen: " << objf_change_tot;
220  KALDI_ASSERT(objf_change_tot < 2.0 * expected_objf_change); // or way too much.
221  // This test relies on statistical laws and if it fails it does not *necessarily*
222  // mean that something is wrong.
223 }
void ApplyModelTransformToStats(const MatrixBase< BaseFloat > &xform, AffineXformStats *stats)
ApplyModelTransformToStats takes a transform "xform", which must be diagonal (i.e.
void InitRandomGmm(DiagGmm *gmm_in)
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
This does not work with multiple feature transforms.
std::string update_type
"full", "diag", "offset", "none"
kaldi::int32 int32
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void ApplyAffineTransform(const MatrixBase< BaseFloat > &xform, VectorBase< BaseFloat > *vec)
Applies the affine transform &#39;xform&#39; to the vector &#39;vec&#39; and overwrites the contents of &#39;vec&#39;...
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestFmllrRaw()

void kaldi::UnitTestFmllrRaw ( bool  use_offset)

Definition at line 50 of file fmllr-raw-test.cc.

References FmllrRawAccs::AccumulateForGmm(), ApplyAffineTransform(), count, DiagGmm::Dim(), rnnlm::i, InitRandomGmm(), KALDI_ASSERT, Rand(), MatrixBase< Real >::SetRandn(), MatrixBase< Real >::SetUnit(), FmllrRawAccs::SetZero(), and FmllrRawAccs::Update().

Referenced by main().

50  {
51  using namespace kaldi;
52  DiagGmm gmm;
53  InitRandomGmm(&gmm);
54  int32 model_dim = gmm.Dim();
55 
56  int32 raw_dim = 5 + Rand() % 3;
57  int32 num_splice = 1 + Rand() % 5;
58  while (num_splice * raw_dim < model_dim) {
59  num_splice++;
60  }
61 
62  int32 full_dim = num_splice * raw_dim;
63  int32 npoints = raw_dim*(raw_dim+1)*10;
64 
65  Matrix<BaseFloat> rand_points(npoints, full_dim);
66  rand_points.SetRandn();
67 
68  Matrix<BaseFloat> lda_mllt(full_dim, full_dim + (use_offset ? 1 : 0)); // This is the full LDA+MLLT
69  // matrix. TODO: test with offset.
70  lda_mllt.SetRandn();
71 
72  FmllrRawAccs accs(raw_dim, model_dim, lda_mllt);
73 
74  BaseFloat prev_objf_impr;
75  for (int32 iter = 0; iter < 4; iter++) {
76 
77  for (int32 i = 0; i < npoints; i++) {
78  SubVector<BaseFloat> sample(rand_points, i);
79  accs.AccumulateForGmm(gmm, sample, 1.0);
80  }
81 
82  Matrix<BaseFloat> fmllr_mat(raw_dim, raw_dim + 1);
83  fmllr_mat.SetUnit(); // sets diagonal elements to one.
84 
85  FmllrRawOptions opts;
86  BaseFloat objf_impr, count;
87  accs.Update(opts, &fmllr_mat, &objf_impr, &count);
88 
89  KALDI_ASSERT(objf_impr > 0.0);
90 
91  if (iter != 0) {
92  // This is not something provable, but is always true
93  // in practice.
94  KALDI_ASSERT(objf_impr < prev_objf_impr);
95  }
96  prev_objf_impr = objf_impr;
97 
98 
99  // Now transform the raw features.
100  for (int32 splice = 0; splice < num_splice; splice++) {
101  SubMatrix<BaseFloat> raw_feats(rand_points,
102  0, npoints,
103  splice * raw_dim, raw_dim);
104  for (int32 t = 0; t < npoints; t++) {
105  SubVector<BaseFloat> this_feat(raw_feats, t);
106  ApplyAffineTransform(fmllr_mat, &this_feat);
107  }
108  }
109  accs.SetZero();
110  }
111 }
void InitRandomGmm(DiagGmm *gmm_in)
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
kaldi::int32 int32
const size_t count
float BaseFloat
Definition: kaldi-types.h:29
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void ApplyAffineTransform(const MatrixBase< BaseFloat > &xform, VectorBase< BaseFloat > *vec)
Applies the affine transform &#39;xform&#39; to the vector &#39;vec&#39; and overwrites the contents of &#39;vec&#39;...
Sub-matrix representation.
Definition: kaldi-matrix.h:988
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestGcdLcm()

void kaldi::UnitTestGcdLcm ( )

Definition at line 71 of file kaldi-math-test.cc.

Referenced by main().

71  {
72  UnitTestGcdLcmTpl<int>();
73  UnitTestGcdLcmTpl<size_t>();
74  UnitTestGcdLcmTpl<int16>();
75 }

◆ UnitTestGcdLcmTpl()

void kaldi::UnitTestGcdLcmTpl ( )

Definition at line 25 of file kaldi-math-test.cc.

References Gcd(), KALDI_ASSERT, Lcm(), and Rand().

25  {
26  for (I a = 1; a < 15; a++) { // a is min gcd.
27  I b = (I)(Rand() % 10);
28  I c = (I)(Rand() % 10);
29  if (std::numeric_limits<I>::is_signed) {
30  if (Rand() % 2 == 0) b = -b;
31  if (Rand() % 2 == 0) c = -c;
32  }
33  if (b == 0 && c == 0) continue; // gcd not defined for such numbers.
34  I g = Gcd(b*a, c*a);
35  KALDI_ASSERT(g >= a);
36  KALDI_ASSERT((b*a) % g == 0);
37  KALDI_ASSERT((c*a) % g == 0);
38 
39  // test least common multiple
40  if (b <= 0 || c <= 0) continue; // lcm not defined unless both positive.
41  I h = Lcm(b*a, c*a);
42  KALDI_ASSERT(h != 0 && (h % (b*a)) == 0 &&
43  (h % (c*a)) == 0);
44  }
45 }
I Gcd(I m, I n)
Definition: kaldi-math.h:297
I Lcm(I m, I n)
Returns the least common multiple of two integers.
Definition: kaldi-math.h:318
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestGeneralMatrix()

static void kaldi::UnitTestGeneralMatrix ( )
static

Definition at line 4305 of file matrix-lib-test.cc.

References MatrixBase< Real >::Add(), MatrixBase< Real >::AddMat(), AssertEqual(), GeneralMatrix::Clear(), GeneralMatrix::Compress(), SparseMatrix< Real >::CopyToMat(), ExtractRowRangeWithPadding(), MatrixBase< Real >::FrobeniusNorm(), GeneralMatrix::GetMatrix(), InitKaldiInputStream(), InitKaldiOutputStream(), KALDI_ASSERT, KALDI_ERR, KALDI_LOG, KALDI_WARN, kNoTrans, rnnlm::n, GeneralMatrix::NumCols(), MatrixBase< Real >::NumRows(), GeneralMatrix::NumRows(), Rand(), RandGauss(), RandInt(), GeneralMatrix::Read(), MatrixBase< Real >::Row(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), GeneralMatrix::SwapSparseMatrix(), and GeneralMatrix::Write().

4305  {
4306  // This is the basic test.
4307 
4308  GeneralMatrix empty_pmat; // some tests on empty matrix
4309  KALDI_ASSERT(empty_pmat.NumRows() == 0);
4310  KALDI_ASSERT(empty_pmat.NumCols() == 0);
4311 
4312  // could set num_tot to 10000 for more thorough testing.
4313  MatrixIndexT num_failure = 0, num_tot = 1000, max_failure = 1;
4314  for (MatrixIndexT n = 0; n < num_tot; n++) {
4315  MatrixIndexT num_rows = Rand() % 20, num_cols = Rand() % 15;
4316  if (num_rows * num_cols == 0) {
4317  num_rows = 0;
4318  num_cols = 0;
4319  }
4320  if (rand() % 2 == 0 && num_cols != 0) {
4321  // smaller matrices are more likely to have problems.
4322  num_cols = 1 + Rand() % 3;
4323  }
4324  Matrix<Real> M(num_rows, num_cols);
4325  if (Rand() % 3 != 0)
4326  M.SetRandn();
4327  else {
4328  M.Add(RandGauss());
4329  }
4330  if (Rand() % 2 == 0 && num_rows != 0) { // set one row to all the same value,
4331  // which is one possible pathology.
4332  // Give it large dynamic range to increase chance that it
4333  // is the largest or smallest value in the matrix.
4334  M.Row(Rand() % num_rows).Set(RandGauss() * 4.0);
4335  }
4336  double rand_val = RandGauss() * 4.0;
4337  // set a bunch of elements to all one value: increases
4338  // chance of pathologies.
4339  MatrixIndexT modulus = 1 + Rand() % 5;
4340  for (MatrixIndexT r = 0; r < num_rows; r++)
4341  for (MatrixIndexT c = 0; c < num_cols; c++)
4342  if (Rand() % modulus != 0) M(r, c) = rand_val;
4343 
4344  GeneralMatrix pmat(M);
4345  if (RandInt(0, 1) == 0)
4346  pmat.Compress();
4347 
4348  if (RandInt(0, 1) == 0) {
4349  SparseMatrix<BaseFloat> smat(num_rows, num_cols);
4350  smat.SetRandn(0.1);
4351  pmat.Clear();
4352  smat.CopyToMat(&M, kNoTrans);
4353  pmat.SwapSparseMatrix(&smat);
4354  }
4355 
4356  KALDI_ASSERT(pmat.NumRows() == num_rows);
4357  KALDI_ASSERT(pmat.NumCols() == num_cols);
4358  GeneralMatrix pmat2(pmat);
4359 
4360  Matrix<Real> M2(pmat2.NumRows(), pmat2.NumCols());
4361  pmat2.GetMatrix(&M2);
4362 
4363  Matrix<Real> diff(M2);
4364  diff.AddMat(-1.0, M);
4365 
4366  if (pmat2.NumRows() > 0) { // Test ExtractRowRangeWithPadding.
4367  int32 row_offset = RandInt(-3, pmat.NumRows() - 1),
4368  num_rows = RandInt(1, 3 + pmat.NumRows() - row_offset);
4369  GeneralMatrix pmat3;
4370  ExtractRowRangeWithPadding(pmat2, row_offset, num_rows, &pmat3);
4371 
4372  Matrix<Real> mat_A(num_rows, pmat.NumCols()),
4373  mat_B(num_rows, pmat.NumCols());
4374  pmat3.GetMatrix(&mat_A);
4375  for (int32 row_out = 0; row_out < num_rows; row_out++) {
4376  int32 row_in = row_out + row_offset;
4377  if (row_in < 0) row_in = 0;
4378  if (row_in >= pmat2.NumRows())
4379  row_in = pmat2.NumRows() - 1;
4380  SubVector<Real> vec_out(mat_B, row_out),
4381  vec_in(M2, row_in);
4382  vec_out.CopyFromVec(vec_in);
4383  }
4384  if (mat_A.NumRows() >= 8) {
4385  // there should be exact equality.
4386  AssertEqual(mat_A, mat_B, 0.0);
4387  } else {
4388  // If it was compressed matrix and num-rows selected is < 8 and the
4389  // format was the one with per-column headers, then we would have changed
4390  // the format to save memory, which is not completely lossless.
4391  mat_A.AddMat(-1.0, mat_B);
4392  KALDI_ASSERT(mat_A.FrobeniusNorm() /
4393  (mat_A.NumRows() * mat_A.NumCols()) < 0.001);
4394  }
4395  }
4396 
4397  if (n < 5) { // test I/O.
4398  bool binary = (n % 2 == 1);
4399  {
4400  std::ofstream outs("tmpf", std::ios_base::out |std::ios_base::binary);
4401  InitKaldiOutputStream(outs, binary);
4402  pmat.Write(outs, binary);
4403  }
4404  GeneralMatrix pmat3;
4405  {
4406  bool binary_in;
4407  std::ifstream ins("tmpf", std::ios_base::in | std::ios_base::binary);
4408  InitKaldiInputStream(ins, &binary_in);
4409  pmat3.Read(ins, binary_in);
4410  }
4411 
4412  Matrix<Real> M3(pmat3.NumRows(), pmat3.NumCols());
4413  pmat3.GetMatrix(&M3);
4414  AssertEqual(M, M3);
4415  }
4416 
4417  KALDI_LOG << "M = " << M;
4418  KALDI_LOG << "M2 = " << M2;
4419  double tot = M.FrobeniusNorm(), err = diff.FrobeniusNorm();
4420  KALDI_LOG << "Compressed matrix, tot = " << tot << ", diff = "
4421  << err;
4422  if (err > 0.015 * tot) {
4423  KALDI_WARN << "Failure in possibly compressed-matrix test.";
4424  num_failure++;
4425  }
4426  }
4427  if (num_failure > max_failure)
4428  KALDI_ERR << "Too many failures in possibly compressed matrix test " << num_failure
4429  << " > " << max_failure;
4430 
4431  unlink("tmpf");
4432 }
This class is a wrapper that enables you to store a matrix in one of three forms: either as a Matrix<...
bool InitKaldiInputStream(std::istream &is, bool *binary)
Initialize an opened stream for reading by detecting the binary header and.
Definition: io-funcs-inl.h:306
void GetMatrix(Matrix< BaseFloat > *mat) const
Outputs the contents as a matrix.
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
void Read(std::istream &is, bool binary)
Note: if you write a compressed matrix in text form, it will be read as a regular full matrix...
MatrixIndexT NumCols() const
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
void ExtractRowRangeWithPadding(const GeneralMatrix &in, int32 row_offset, int32 num_rows, GeneralMatrix *out)
This function extracts a row-range of a GeneralMatrix and writes as a GeneralMatrix containing the sa...
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
MatrixIndexT NumRows() const
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void InitKaldiOutputStream(std::ostream &os, bool binary)
InitKaldiOutputStream initializes an opened stream for writing by writing an optional binary header a...
Definition: io-funcs-inl.h:291
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestHeaviside()

static void kaldi::UnitTestHeaviside ( )
static

Definition at line 1117 of file matrix-lib-test.cc.

References MatrixBase< Real >::ApplyHeaviside(), KALDI_ASSERT, and Rand().

1117  {
1118  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1119  MatrixIndexT dimM = 10 + Rand() % 10, dimN = 10 + Rand() % 10;
1120  Matrix<Real> M(dimM, dimN), N(dimM, dimN);
1121  M.SetRandn();
1122  N = M;
1123  N.ApplyHeaviside();
1124  for (MatrixIndexT r = 0; r < dimM; r++) {
1125  for (MatrixIndexT c = 0; c < dimN; c++) {
1126  Real x = M(r, c), y = N(r, c);
1127  if (x < 0.0) KALDI_ASSERT(y == 0.0);
1128  if (x > 0.0) KALDI_ASSERT(y == 1.0);
1129  if (x == 0.0) { KALDI_ASSERT(y >= 0.0 && y <= 1.0); }
1130  }
1131  }
1132  }
1133 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestHtkIo()

static void kaldi::UnitTestHtkIo ( )
static

Definition at line 2614 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, KALDI_ASSERT, HtkHeader::mNSamples, HtkHeader::mSampleKind, HtkHeader::mSamplePeriod, HtkHeader::mSampleSize, Rand(), ReadHtk(), MatrixBase< Real >::SetRandn(), and WriteHtk().

2614  {
2615 
2616  for (MatrixIndexT i = 0;i < 5;i++) {
2617  MatrixIndexT dimM = Rand()%10 + 10;
2618  MatrixIndexT dimN = Rand()%10 + 10;
2619 
2620  HtkHeader hdr;
2621  hdr.mNSamples = dimM;
2622  hdr.mSamplePeriod = 10000; // in funny HTK units-- can set it arbitrarily
2623  hdr.mSampleSize = sizeof(float)*dimN;
2624  hdr.mSampleKind = 8; // Mel spectrum.
2625 
2626  Matrix<Real> M(dimM, dimN);
2627  M.SetRandn();
2628 
2629  {
2630  std::ofstream os("tmpf", std::ios::out|std::ios::binary);
2631  WriteHtk(os, M, hdr);
2632  }
2633 
2634  Matrix<Real> N;
2635  HtkHeader hdr2;
2636  {
2637  std::ifstream is("tmpf", std::ios::in|std::ios::binary);
2638  ReadHtk(is, &N, &hdr2);
2639  }
2640 
2641  AssertEqual(M, N);
2642  KALDI_ASSERT(hdr.mNSamples == hdr2.mNSamples);
2644  KALDI_ASSERT(hdr.mSampleSize == hdr2.mSampleSize);
2645  KALDI_ASSERT(hdr.mSampleKind == hdr2.mSampleKind);
2646  }
2647 
2648  unlink("tmpf");
2649 }
int16 mSampleSize
Sample size.
Definition: kaldi-matrix.h:961
bool WriteHtk(std::ostream &os, const MatrixBase< Real > &M, HtkHeader htk_hdr)
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 mSamplePeriod
Sample period.
Definition: kaldi-matrix.h:959
int32 MatrixIndexT
Definition: matrix-common.h:98
uint16 mSampleKind
Sample kind.
Definition: kaldi-matrix.h:963
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
int32 mNSamples
Number of samples.
Definition: kaldi-matrix.h:957
bool ReadHtk(std::istream &is, Matrix< Real > *M_ptr, HtkHeader *header_ptr)
Extension of the HTK header.
A structure containing the HTK header.
Definition: kaldi-matrix.h:955

◆ UnitTestInnerProd()

static void kaldi::UnitTestInnerProd ( )
static

Definition at line 2814 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, rnnlm::j, Rand(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), and VecSpVec().

2814  {
2815 
2816  MatrixIndexT N = 1 + Rand() % 10;
2817  SpMatrix<Real> S(N);
2818  S.SetRandn();
2819  Vector<Real> v(N);
2820  v.SetRandn();
2821  Real prod = VecSpVec(v, S, v);
2822  Real f2=0.0;
2823  for (MatrixIndexT i = 0; i < N; i++)
2824  for (MatrixIndexT j = 0; j < N; j++) {
2825  f2 += v(i) * v(j) * S(i, j);
2826  }
2827  AssertEqual(prod, f2);
2828 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
Real VecSpVec(const VectorBase< Real > &v1, const SpMatrix< Real > &M, const VectorBase< Real > &v2)
Computes v1^T * M * v2.
Definition: sp-matrix.cc:964
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestInverse()

static void kaldi::UnitTestInverse ( )
static

Definition at line 1802 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), rnnlm::i, InitRandNonsingular(), rnnlm::j, KALDI_ASSERT, kNoTrans, and Rand().

1802  {
1803  for (MatrixIndexT iter = 0;iter < 10;iter++) {
1804  MatrixIndexT dimM = 20 + Rand()%10;
1805  Matrix<Real> A(dimM, dimM), B(dimM, dimM), C(dimM, dimM);
1806  InitRandNonsingular(&A);
1807  B.CopyFromMat(A);
1808  B.Invert();
1809 
1810  C.AddMatMat(1.0, A, kNoTrans, B, kNoTrans, 0.0); // C = A * B.
1811 
1812 
1813  for (MatrixIndexT i = 0;i < dimM;i++)
1814  for (MatrixIndexT j = 0;j < dimM;j++)
1815  KALDI_ASSERT(std::abs(C(i, j) - (i == j?1.0:0.0)) < 0.1);
1816  }
1817 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void InitRandNonsingular(SpMatrix< Real > *M)

◆ UnitTestInvert()

static void kaldi::UnitTestInvert ( )
static

Definition at line 185 of file cu-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddVecVec(), AssertEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), rnnlm::i, KALDI_LOG, kNoTrans, Rand(), and CuMatrixBase< Real >::SymInvertPosDef().

185  {
186  for (MatrixIndexT iter = 0; iter < 3; iter++) {
187  MatrixIndexT dim = 500 + Rand() % 400;
188 
189  KALDI_LOG << "dim is : ";
190  KALDI_LOG << dim;
191  CuMatrix<Real> A(dim,dim);
192  Matrix<Real> B(dim,dim);
193  Vector<Real> C(dim);
194  for (MatrixIndexT i = 0; i < dim; i++) {
195  B(i,i) = 1;
196  C(i) = (i/(1.0*dim)) + 1;
197  }
198  Matrix<Real> Identity(B);
199  B.AddVecVec(1.0, C, C);
200  // Now we have a positive-definite B (inversion would
201  // fail if it were not positive definite).
202 
203  A.CopyFromMat(B);
204 
205  A.SymInvertPosDef();
206  Matrix<Real> D(dim,dim);
207  A.CopyToMat(&D);
208 
209  Matrix<Real> X(dim,dim);
210  X.AddMatMat(1.0, B, kNoTrans, D, kNoTrans, 0.0);
211  // KALDI_LOG << "X is (should be identity): " << X;
212  AssertEqual(Identity, X, (sizeof(Real) == 4 ? 0.1 : 0.001));
213  }
214 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestIo() [1/2]

void kaldi::UnitTestIo ( bool  binary)

Definition at line 24 of file io-funcs-test.cc.

References AssertEqual(), ExpectToken(), rnnlm::i, InitKaldiInputStream(), InitKaldiOutputStream(), KALDI_ASSERT, Peek(), PeekToken(), Rand(), RandInt(), RandUniform(), ReadBasicType(), ReadIntegerPairVector(), ReadIntegerVector(), ReadToken(), WriteBasicType(), WriteIntegerPairVector(), WriteIntegerVector(), and WriteToken().

Referenced by main().

24  {
25  {
26  const char *filename = "tmpf";
27  std::ofstream outfile(filename, std::ios_base::out | std::ios_base::binary);
28  InitKaldiOutputStream(outfile, binary);
29  if (!binary) outfile << "\t";
30  int64 i1 = Rand() % 10000;
31  WriteBasicType(outfile, binary, i1);
32  uint16 i2 = Rand() % 10000;
33  WriteBasicType(outfile, binary, i2);
34  if (!binary) outfile << "\t";
35  char c = Rand();
36  WriteBasicType(outfile, binary, c);
37  if (!binary && Rand()%2 == 0) outfile << " \n";
38  std::vector<int32> vec1;
39  WriteIntegerVector(outfile, binary, vec1);
40  if (!binary && Rand()%2 == 0) outfile << " \n";
41  std::vector<uint16> vec2;
42  for (size_t i = 0; i < 10; i++) vec2.push_back(Rand()%100 - 10);
43  WriteIntegerVector(outfile, binary, vec2);
44  if (!binary) outfile << " \n";
45  std::vector<char> vec3;
46 
47  int32 size = RandInt(0, 10);
48  for (size_t i = 0; i < size; i++) vec3.push_back(Rand()%100);
49  WriteIntegerVector(outfile, binary, vec3);
50  std::vector<std::pair<int32, int32> > vec4;
51  WriteIntegerPairVector(outfile, binary, vec4);
52  if (!binary && Rand()%2 == 0) outfile << " \n";
53  std::vector<std::pair<uint16, uint16> > vec5;
54  for (size_t i = 0; i < size; i++) vec5.push_back(std::make_pair<uint16, uint16>(Rand()%100 - 10, Rand()%100 - 10));
55  WriteIntegerPairVector(outfile, binary, vec5);
56  if (!binary) outfile << " \n";
57  std::vector<std::pair<char, char> > vec6;
58  for (size_t i = 0; i < size; i++) vec6.push_back(std::make_pair<char, char>(Rand()%100, Rand()%100));
59  WriteIntegerPairVector(outfile, binary, vec6);
60  if (!binary && Rand()%2 == 0) outfile << " \n";
61  const char *token1 = "Hi";
62  WriteToken(outfile, binary, token1);
63  if (!binary) outfile << " \n";
64  std::string token2 = "There.";
65  WriteToken(outfile, binary, token2);
66  if (!binary && Rand()%2 == 0) outfile << " \n";
67  std::string token3 = "You.";
68  WriteToken(outfile, binary, token3);
69  if (!binary && Rand()%2 == 0) outfile << " ";
70  float f1 = RandUniform();
71  WriteBasicType(outfile, binary, f1);
72  if (!binary && Rand()%2 == 0) outfile << "\t";
73  float f2 = RandUniform();
74  WriteBasicType(outfile, binary, f2);
75  double d1 = RandUniform();
76  WriteBasicType(outfile, binary, d1);
77  if (!binary && Rand()%2 == 0) outfile << "\t";
78  double d2 = RandUniform();
79  WriteBasicType(outfile, binary, d2);
80  if (!binary && Rand()%2 == 0) outfile << "\t";
81  outfile.close();
82 
83  {
84  std::ifstream infile(filename, std::ios_base::in | std::ios_base::binary);
85  bool binary_in;
86  InitKaldiInputStream(infile, &binary_in);
87  int64 i1_in;
88  ReadBasicType(infile, binary_in, &i1_in);
89  KALDI_ASSERT(i1_in == i1);
90  uint16 i2_in;
91  ReadBasicType(infile, binary_in, &i2_in);
92  KALDI_ASSERT(i2_in == i2);
93  char c_in;
94  ReadBasicType(infile, binary_in, &c_in);
95  KALDI_ASSERT(c_in == c);
96  std::vector<int32> vec1_in;
97  ReadIntegerVector(infile, binary_in, &vec1_in);
98  KALDI_ASSERT(vec1_in == vec1);
99  std::vector<uint16> vec2_in;
100  ReadIntegerVector(infile, binary_in, &vec2_in);
101  KALDI_ASSERT(vec2_in == vec2);
102  std::vector<char> vec3_in;
103  ReadIntegerVector(infile, binary_in, &vec3_in);
104  KALDI_ASSERT(vec3_in == vec3);
105  std::vector<std::pair<int32, int32> > vec4_in;
106  ReadIntegerPairVector(infile, binary_in, &vec4_in);
107  KALDI_ASSERT(vec4_in == vec4);
108  std::vector<std::pair<uint16, uint16> > vec5_in;
109  ReadIntegerPairVector(infile, binary_in, &vec5_in);
110  KALDI_ASSERT(vec5_in == vec5);
111  std::vector<std::pair<char, char> > vec6_in;
112  ReadIntegerPairVector(infile, binary_in, &vec6_in);
113  KALDI_ASSERT(vec6_in == vec6);
114  std::string token1_in, token2_in;
115  KALDI_ASSERT(Peek(infile, binary_in) == static_cast<int>(*token1));
116  KALDI_ASSERT(PeekToken(infile, binary_in) == static_cast<int>(*token1));
117  // Note:
118  // the stuff with skipping over '<' is tested in ../util/kaldi-io-test.cc,
119  // since we need to make sure it works with pipes.
120  ReadToken(infile, binary_in, &token1_in);
121  KALDI_ASSERT(token1_in == std::string(token1));
122  ReadToken(infile, binary_in, &token2_in);
123  KALDI_ASSERT(token2_in == std::string(token2));
124  if (Rand() % 2 == 0)
125  ExpectToken(infile, binary_in, token3.c_str());
126  else
127  ExpectToken(infile, binary_in, token3);
128  float f1_in; // same type.
129  ReadBasicType(infile, binary_in, &f1_in);
130  AssertEqual(f1_in, f1);
131  double f2_in; // wrong type.
132  ReadBasicType(infile, binary_in, &f2_in);
133  AssertEqual(f2_in, f2);
134  double d1_in; // same type.
135  ReadBasicType(infile, binary_in, &d1_in);
136  AssertEqual(d1_in, d1);
137  float d2_in; // wrong type.
138  ReadBasicType(infile, binary_in, &d2_in);
139  AssertEqual(d2_in, d2);
140  KALDI_ASSERT(Peek(infile, binary_in) == -1);
141  KALDI_ASSERT(PeekToken(infile, binary_in) == -1);
142  }
143  unlink(filename);
144  }
145 }
bool InitKaldiInputStream(std::istream &is, bool *binary)
Initialize an opened stream for reading by detecting the binary header and.
Definition: io-funcs-inl.h:306
void WriteIntegerPairVector(std::ostream &os, bool binary, const std::vector< std::pair< T, T > > &v)
Function for writing STL vectors of pairs of integer types.
Definition: io-funcs-inl.h:93
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
void ReadBasicType(std::istream &is, bool binary, T *t)
ReadBasicType is the name of the read function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:55
kaldi::int32 int32
void ReadToken(std::istream &is, bool binary, std::string *str)
ReadToken gets the next token and puts it in str (exception on failure).
Definition: io-funcs.cc:154
void ReadIntegerPairVector(std::istream &is, bool binary, std::vector< std::pair< T, T > > *v)
Function for reading STL vector of pairs of integer types.
Definition: io-funcs-inl.h:131
int Peek(std::istream &is, bool binary)
Peek consumes whitespace (if binary == false) and then returns the peek() value of the stream...
Definition: io-funcs.cc:145
void ReadIntegerVector(std::istream &is, bool binary, std::vector< T > *v)
Function for reading STL vector of integer types.
Definition: io-funcs-inl.h:232
void ExpectToken(std::istream &is, bool binary, const char *token)
ExpectToken tries to read in the given token, and throws an exception on failure. ...
Definition: io-funcs.cc:191
void WriteToken(std::ostream &os, bool binary, const char *token)
The WriteToken functions are for writing nonempty sequences of non-space characters.
Definition: io-funcs.cc:134
int PeekToken(std::istream &is, bool binary)
PeekToken will return the first character of the next token, or -1 if end of file.
Definition: io-funcs.cc:170
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void WriteIntegerVector(std::ostream &os, bool binary, const std::vector< T > &v)
Function for writing STL vectors of integer types.
Definition: io-funcs-inl.h:198
void WriteBasicType(std::ostream &os, bool binary, T t)
WriteBasicType is the name of the write function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:34
void InitKaldiOutputStream(std::ostream &os, bool binary)
InitKaldiOutputStream initializes an opened stream for writing by writing an optional binary header a...
Definition: io-funcs-inl.h:291
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestIo() [2/2]

static void kaldi::UnitTestIo ( )
static

Definition at line 2486 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, InitKaldiInputStream(), InitKaldiOutputStream(), KALDI_ERR, KALDI_LOG, Rand(), PackedMatrix< Real >::Read(), Vector< Real >::Read(), Matrix< Real >::Read(), SpMatrix< Real >::Resize(), Vector< Real >::Resize(), Matrix< Real >::Resize(), PackedMatrix< Real >::Scale(), MatrixBase< Real >::Scale(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), VectorBase< Real >::Write(), and MatrixBase< Real >::Write().

2486  {
2487 
2488  for (MatrixIndexT i = 0;i < 5;i++) {
2489  MatrixIndexT dimM = Rand()%10 + 1;
2490  MatrixIndexT dimN = Rand()%10 + 1;
2491  bool binary = (i%2 == 0);
2492 
2493  if (i == 0) {
2494  dimM = 0;dimN = 0; // test case when both are zero.
2495  }
2496  Matrix<Real> M(dimM, dimN);
2497  M.SetRandn();
2498  Matrix<Real> N;
2499  Vector<Real> v1(dimM);
2500  v1.SetRandn();
2501  Vector<Real> v2(dimM);
2502 
2503  SpMatrix<Real> S(dimM);
2504  S.SetRandn();
2505  KALDI_LOG << "SpMatrix IO: " << S;
2506  SpMatrix<Real> T(dimM);
2507 
2508  {
2509  std::ofstream outs("tmpf", std::ios_base::out |std::ios_base::binary);
2510  InitKaldiOutputStream(outs, binary);
2511  M.Write(outs, binary);
2512  S.Write(outs, binary);
2513  v1.Write(outs, binary);
2514  M.Write(outs, binary);
2515  S.Write(outs, binary);
2516  v1.Write(outs, binary);
2517  }
2518 
2519  {
2520  bool binary_in;
2521  bool either_way = (i%2 == 0);
2522  std::ifstream ins("tmpf", std::ios_base::in | std::ios_base::binary);
2523  if (!InitKaldiInputStream(ins, &binary_in)) {
2524  KALDI_ERR << "Malformed input stream.";
2525  }
2526  N.Resize(0, 0);
2527  T.Resize(0);
2528  v2.Resize(0);
2529  N.Read(ins, binary_in, either_way);
2530  T.Read(ins, binary_in, either_way);
2531  v2.Read(ins, binary_in, either_way);
2532  if (i%2 == 0)
2533  ((MatrixBase<Real>&)N).Read(ins, binary_in, true); // add
2534  else
2535  N.Read(ins, binary_in, true);
2536  T.Read(ins, binary_in, true); // add
2537  if (i%2 == 0)
2538  ((VectorBase<Real>&)v2).Read(ins, binary_in, true); // add
2539  else
2540  v2.Read(ins, binary_in, true);
2541  }
2542  N.Scale(0.5);
2543  v2.Scale(0.5);
2544  T.Scale(0.5);
2545  AssertEqual(M, N);
2546  AssertEqual(v1, v2);
2547  AssertEqual(S, T);
2548  }
2549 }
Packed symetric matrix class.
Definition: matrix-common.h:62
bool InitKaldiInputStream(std::istream &is, bool *binary)
Initialize an opened stream for reading by detecting the binary header and.
Definition: io-funcs-inl.h:306
Base class which provides matrix operations not involving resizing or allocation. ...
Definition: kaldi-matrix.h:49
A class for storing matrices.
Definition: kaldi-matrix.h:823
void Read(std::istream &in, bool binary, bool add=false)
read from stream.
int32 MatrixIndexT
Definition: matrix-common.h:98
void Scale(Real alpha)
Multiply each element with a scalar value.
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
void InitKaldiOutputStream(std::ostream &os, bool binary)
InitKaldiOutputStream initializes an opened stream for writing by writing an optional binary header a...
Definition: io-funcs-inl.h:291
Provides a vector abstraction class.
Definition: kaldi-vector.h:41
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestIoCross()

static void kaldi::UnitTestIoCross ( )
static

Definition at line 2552 of file matrix-lib-test.cc.

References AssertEqual(), MatrixBase< Real >::CopyFromMat(), SpMatrix< Real >::CopyFromSp(), VectorBase< Real >::CopyFromVec(), rnnlm::i, InitKaldiInputStream(), InitKaldiOutputStream(), KALDI_ERR, Rand(), PackedMatrix< Real >::Read(), Vector< Real >::Read(), Matrix< Real >::Read(), PackedMatrix< Real >::Scale(), MatrixBase< Real >::Scale(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), PackedMatrix< Real >::Write(), VectorBase< Real >::Write(), and MatrixBase< Real >::Write().

2552  { // across types.
2553 
2554  typedef typename OtherReal<Real>::Real Other; // e.g. if Real == float, Other == double.
2555  for (MatrixIndexT i = 0;i < 5;i++) {
2556  MatrixIndexT dimM = Rand()%10 + 1;
2557  MatrixIndexT dimN = Rand()%10 + 1;
2558  bool binary = (i%2 == 0);
2559  if (i == 0) {
2560  dimM = 0;dimN = 0; // test case when both are zero.
2561  }
2562  Matrix<Real> M(dimM, dimN);
2563  Matrix<Other> MO;
2564  M.SetRandn();
2565  Matrix<Real> N(dimM, dimN);
2566  Vector<Real> v(dimM);
2567  Vector<Other> vO;
2568  v.SetRandn();
2569  Vector<Real> w(dimM);
2570 
2571  SpMatrix<Real> S(dimM);
2572  SpMatrix<Other> SO;
2573  S.SetRandn();
2574  SpMatrix<Real> T(dimM);
2575 
2576  {
2577  std::ofstream outs("tmpf", std::ios_base::out |std::ios_base::binary);
2578  InitKaldiOutputStream(outs, binary);
2579 
2580  M.Write(outs, binary);
2581  S.Write(outs, binary);
2582  v.Write(outs, binary);
2583  M.Write(outs, binary);
2584  S.Write(outs, binary);
2585  v.Write(outs, binary);
2586  }
2587  {
2588  std::ifstream ins("tmpf", std::ios_base::in | std::ios_base::binary);
2589  bool binary_in;
2590  if (!InitKaldiInputStream(ins, &binary_in)) {
2591  KALDI_ERR << "Malformed input stream";
2592  }
2593 
2594  MO.Read(ins, binary_in);
2595  SO.Read(ins, binary_in);
2596  vO.Read(ins, binary_in);
2597  MO.Read(ins, binary_in, true);
2598  SO.Read(ins, binary_in, true);
2599  vO.Read(ins, binary_in, true);
2600  N.CopyFromMat(MO);
2601  T.CopyFromSp(SO);
2602  w.CopyFromVec(vO);
2603  }
2604  N.Scale(0.5);
2605  w.Scale(0.5);
2606  T.Scale(0.5);
2607  AssertEqual(M, N);
2608  AssertEqual(v, w);
2609  AssertEqual(S, T);
2610  }
2611 }
This class provides a way for switching between double and float types.
Definition: matrix-common.h:84
Packed symetric matrix class.
Definition: matrix-common.h:62
bool InitKaldiInputStream(std::istream &is, bool *binary)
Initialize an opened stream for reading by detecting the binary header and.
Definition: io-funcs-inl.h:306
void Read(std::istream &in, bool binary, bool add=false)
A class for storing matrices.
Definition: kaldi-matrix.h:823
void SetRandn()
< Set to unit matrix.
void Read(std::istream &in, bool binary, bool add=false)
read from stream.
int32 MatrixIndexT
Definition: matrix-common.h:98
void SetRandn()
Sets to random values of a normal distribution.
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void SetRandn()
Set vector to random normally-distributed noise.
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void InitKaldiOutputStream(std::ostream &os, bool binary)
InitKaldiOutputStream initializes an opened stream for writing by writing an optional binary header a...
Definition: io-funcs-inl.h:291
void Read(std::istream &in, bool binary, bool add=false)
Read function using C++ streams.

◆ UnitTestIoNew()

void kaldi::UnitTestIoNew ( bool  binary)

Definition at line 71 of file kaldi-io-test.cc.

References AssertEqual(), Output::Close(), ExpectToken(), rnnlm::i, KALDI_ASSERT, Peek(), Rand(), RandUniform(), ReadBasicType(), ReadIntegerVector(), ReadToken(), Output::Stream(), Input::Stream(), WriteBasicType(), WriteIntegerVector(), and WriteToken().

Referenced by main().

71  {
72  {
73  const char *filename = "tmpf";
74 
75  Output ko(filename, binary);
76  std::ostream &outfile = ko.Stream();
77  if (!binary) outfile << "\t";
78  int64 i1 = Rand() % 10000;
79  WriteBasicType(outfile, binary, i1);
80  uint16 i2 = Rand() % 10000;
81  WriteBasicType(outfile, binary, i2);
82  if (!binary) outfile << "\t";
83  char c = Rand();
84  WriteBasicType(outfile, binary, c);
85  if (!binary && Rand()%2 == 0) outfile << " \n";
86  std::vector<int32> vec1;
87  WriteIntegerVector(outfile, binary, vec1);
88  if (!binary && Rand()%2 == 0) outfile << " \n";
89  std::vector<uint16> vec2;
90  for (size_t i = 0; i < 10; i++) vec2.push_back(Rand()%100 - 10);
91  WriteIntegerVector(outfile, binary, vec2);
92  if (!binary) outfile << " \n";
93  std::vector<char> vec3;
94  for (size_t i = 0; i < 10; i++) vec3.push_back(Rand()%100);
95  WriteIntegerVector(outfile, binary, vec3);
96  if (!binary && Rand()%2 == 0) outfile << " \n";
97  const char *token1 = "Hi";
98  WriteToken(outfile, binary, token1);
99  if (!binary) outfile << " \n";
100  std::string token2 = "There.";
101  WriteToken(outfile, binary, token2);
102  if (!binary && Rand()%2 == 0) outfile << " \n";
103  std::string token3 = "You.";
104  WriteToken(outfile, binary, token3);
105  if (!binary && Rand()%2 == 0) outfile << " ";
106  float f1 = RandUniform();
107  WriteBasicType(outfile, binary, f1);
108  if (!binary && Rand()%2 == 0) outfile << "\t";
109  float f2 = RandUniform();
110  WriteBasicType(outfile, binary, f2);
111  double d1 = RandUniform();
112  WriteBasicType(outfile, binary, d1);
113  if (!binary && Rand()%2 == 0) outfile << "\t";
114  double d2 = RandUniform();
115  WriteBasicType(outfile, binary, d2);
116  if (!binary && Rand()%2 == 0) outfile << "\t";
117  ko.Close();
118 
119  {
120  bool binary_in;
121  Input ki(filename, &binary_in);
122  std::istream &infile = ki.Stream();
123  int64 i1_in;
124  ReadBasicType(infile, binary_in, &i1_in);
125  KALDI_ASSERT(i1_in == i1);
126  uint16 i2_in;
127  ReadBasicType(infile, binary_in, &i2_in);
128  KALDI_ASSERT(i2_in == i2);
129  char c_in;
130  ReadBasicType(infile, binary_in, &c_in);
131  KALDI_ASSERT(c_in == c);
132  std::vector<int32> vec1_in;
133  ReadIntegerVector(infile, binary_in, &vec1_in);
134  KALDI_ASSERT(vec1_in == vec1);
135  std::vector<uint16> vec2_in;
136  ReadIntegerVector(infile, binary_in, &vec2_in);
137  KALDI_ASSERT(vec2_in == vec2);
138  std::vector<char> vec3_in;
139  ReadIntegerVector(infile, binary_in, &vec3_in);
140  KALDI_ASSERT(vec3_in == vec3);
141  std::string token1_in, token2_in;
142  KALDI_ASSERT(Peek(infile, binary_in) == static_cast<int>(*token1));
143  ReadToken(infile, binary_in, &token1_in);
144  KALDI_ASSERT(token1_in == (std::string)token1);
145  ReadToken(infile, binary_in, &token2_in);
146  KALDI_ASSERT(token2_in == token2);
147  if (Rand() % 2 == 0)
148  ExpectToken(infile, binary_in, token3.c_str());
149  else
150  ExpectToken(infile, binary_in, token3);
151  float f1_in; // same type.
152  ReadBasicType(infile, binary_in, &f1_in);
153  AssertEqual(f1_in, f1);
154  double f2_in; // wrong type.
155  ReadBasicType(infile, binary_in, &f2_in);
156  AssertEqual(f2_in, f2);
157  double d1_in; // same type.
158  ReadBasicType(infile, binary_in, &d1_in);
159  AssertEqual(d1_in, d1);
160  float d2_in; // wrong type.
161  ReadBasicType(infile, binary_in, &d2_in);
162  AssertEqual(d2_in, d2);
163  KALDI_ASSERT(Peek(infile, binary_in) == -1);
164  }
165  unlink(filename);
166  }
167 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
void ReadBasicType(std::istream &is, bool binary, T *t)
ReadBasicType is the name of the read function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:55
void ReadToken(std::istream &is, bool binary, std::string *str)
ReadToken gets the next token and puts it in str (exception on failure).
Definition: io-funcs.cc:154
int Peek(std::istream &is, bool binary)
Peek consumes whitespace (if binary == false) and then returns the peek() value of the stream...
Definition: io-funcs.cc:145
void ReadIntegerVector(std::istream &is, bool binary, std::vector< T > *v)
Function for reading STL vector of integer types.
Definition: io-funcs-inl.h:232
void ExpectToken(std::istream &is, bool binary, const char *token)
ExpectToken tries to read in the given token, and throws an exception on failure. ...
Definition: io-funcs.cc:191
void WriteToken(std::ostream &os, bool binary, const char *token)
The WriteToken functions are for writing nonempty sequences of non-space characters.
Definition: io-funcs.cc:134
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void WriteIntegerVector(std::ostream &os, bool binary, const std::vector< T > &v)
Function for writing STL vectors of integer types.
Definition: io-funcs-inl.h:198
void WriteBasicType(std::ostream &os, bool binary, T t)
WriteBasicType is the name of the write function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:34

◆ UnitTestIoPipe()

void kaldi::UnitTestIoPipe ( bool  binary)

Definition at line 169 of file kaldi-io-test.cc.

References AssertEqual(), Output::Close(), ExpectToken(), rnnlm::i, KALDI_ASSERT, Peek(), PeekToken(), Rand(), RandUniform(), ReadBasicType(), ReadIntegerVector(), ReadToken(), Sleep(), Output::Stream(), Input::Stream(), WriteBasicType(), WriteIntegerVector(), and WriteToken().

Referenced by main().

169  {
170  // This is as UnitTestIoNew except with different filenames.
171  {
172 #if defined(_MSC_VER) && !defined(KALDI_CYGWIN_COMPAT)
173  // self-invocation on Windows that emulates cat(1)
174  const char *filename_out = "|kaldi-io-test cat > tmpf.gz",
175  *filename_in = "kaldi-io-test cat tmpf.gz|";
176 #else
177  const char *filename_out = "|gzip -c > tmpf.gz",
178  *filename_in = "gunzip -c tmpf.gz |";
179 #endif
180 
181  Output ko(filename_out, binary);
182  std::ostream &outfile = ko.Stream();
183  if (!binary) outfile << "\t";
184  int64 i1 = Rand() % 10000;
185  WriteBasicType(outfile, binary, i1);
186  uint16 i2 = Rand() % 10000;
187  WriteBasicType(outfile, binary, i2);
188  if (!binary) outfile << "\t";
189  char c = Rand();
190  WriteBasicType(outfile, binary, c);
191  if (!binary && Rand()%2 == 0) outfile << " \n";
192  std::vector<int32> vec1;
193  WriteIntegerVector(outfile, binary, vec1);
194  if (!binary && Rand()%2 == 0) outfile << " \n";
195  std::vector<uint16> vec2;
196  for (size_t i = 0; i < 10; i++) vec2.push_back(Rand()%100 - 10);
197  WriteIntegerVector(outfile, binary, vec2);
198  if (!binary) outfile << " \n";
199  WriteToken(outfile, binary, "<foo>");
200  std::vector<char> vec3;
201  for (size_t i = 0; i < 10; i++) vec3.push_back(Rand()%100);
202  WriteIntegerVector(outfile, binary, vec3);
203  if (!binary && Rand()%2 == 0) outfile << " \n";
204  const char *token1 = "Hi";
205  WriteToken(outfile, binary, token1);
206  if (!binary) outfile << " \n";
207  std::string token2 = "There.";
208  WriteToken(outfile, binary, token2);
209  if (!binary && Rand()%2 == 0) outfile << " \n";
210  std::string token3 = "You.";
211  WriteToken(outfile, binary, token3);
212  if (!binary && Rand()%2 == 0) outfile << " ";
213  float f1 = RandUniform();
214  WriteBasicType(outfile, binary, f1);
215  if (!binary && Rand()%2 == 0) outfile << "\t";
216  float f2 = RandUniform();
217  WriteBasicType(outfile, binary, f2);
218  double d1 = RandUniform();
219  WriteBasicType(outfile, binary, d1);
220  if (!binary && Rand()%2 == 0) outfile << "\t";
221  double d2 = RandUniform();
222  WriteBasicType(outfile, binary, d2);
223  if (!binary && Rand()%2 == 0) outfile << "\t";
224  bool ans = ko.Close();
225  KALDI_ASSERT(ans);
226 #ifndef _MSC_VER
227  Sleep(1); // This test does not work without this sleep:
228  // seems to be some kind of file-system latency.
229 #endif
230  {
231  bool binary_in;
232  Input ki(filename_in, &binary_in);
233  std::istream &infile = ki.Stream();
234  int64 i1_in;
235  ReadBasicType(infile, binary_in, &i1_in);
236  KALDI_ASSERT(i1_in == i1);
237  uint16 i2_in;
238  ReadBasicType(infile, binary_in, &i2_in);
239  KALDI_ASSERT(i2_in == i2);
240  char c_in;
241  ReadBasicType(infile, binary_in, &c_in);
242  KALDI_ASSERT(c_in == c);
243  std::vector<int32> vec1_in;
244  ReadIntegerVector(infile, binary_in, &vec1_in);
245  KALDI_ASSERT(vec1_in == vec1);
246  std::vector<uint16> vec2_in;
247  ReadIntegerVector(infile, binary_in, &vec2_in);
248  KALDI_ASSERT(vec2_in == vec2);
249  std::vector<char> vec3_in;
250  KALDI_ASSERT(PeekToken(infile, binary_in) == static_cast<int>('f'));
251  ExpectToken(infile, binary_in, "<foo>");
252  ReadIntegerVector(infile, binary_in, &vec3_in);
253  KALDI_ASSERT(vec3_in == vec3);
254  std::string token1_in, token2_in;
255  KALDI_ASSERT(Peek(infile, binary_in) == static_cast<int>(*token1));
256  ReadToken(infile, binary_in, &token1_in);
257  KALDI_ASSERT(token1_in == (std::string)token1);
258  ReadToken(infile, binary_in, &token2_in);
259  KALDI_ASSERT(token2_in == token2);
260  if (Rand() % 2 == 0)
261  ExpectToken(infile, binary_in, token3.c_str());
262  else
263  ExpectToken(infile, binary_in, token3);
264  float f1_in; // same type.
265  ReadBasicType(infile, binary_in, &f1_in);
266  AssertEqual(f1_in, f1);
267  double f2_in; // wrong type.
268  ReadBasicType(infile, binary_in, &f2_in);
269  AssertEqual(f2_in, f2);
270  double d1_in; // same type.
271  ReadBasicType(infile, binary_in, &d1_in);
272  AssertEqual(d1_in, d1);
273  float d2_in; // wrong type.
274  ReadBasicType(infile, binary_in, &d2_in);
275  AssertEqual(d2_in, d2);
276  KALDI_ASSERT(Peek(infile, binary_in) == -1);
277  }
278  }
279  unlink("tmpf.txt");
280  unlink("tmpf.gz");
281 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
void ReadBasicType(std::istream &is, bool binary, T *t)
ReadBasicType is the name of the read function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:55
void Sleep(float seconds)
Definition: kaldi-utils.cc:45
void ReadToken(std::istream &is, bool binary, std::string *str)
ReadToken gets the next token and puts it in str (exception on failure).
Definition: io-funcs.cc:154
int Peek(std::istream &is, bool binary)
Peek consumes whitespace (if binary == false) and then returns the peek() value of the stream...
Definition: io-funcs.cc:145
void ReadIntegerVector(std::istream &is, bool binary, std::vector< T > *v)
Function for reading STL vector of integer types.
Definition: io-funcs-inl.h:232
void ExpectToken(std::istream &is, bool binary, const char *token)
ExpectToken tries to read in the given token, and throws an exception on failure. ...
Definition: io-funcs.cc:191
void WriteToken(std::ostream &os, bool binary, const char *token)
The WriteToken functions are for writing nonempty sequences of non-space characters.
Definition: io-funcs.cc:134
int PeekToken(std::istream &is, bool binary)
PeekToken will return the first character of the next token, or -1 if end of file.
Definition: io-funcs.cc:170
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void WriteIntegerVector(std::ostream &os, bool binary, const std::vector< T > &v)
Function for writing STL vectors of integer types.
Definition: io-funcs-inl.h:198
void WriteBasicType(std::ostream &os, bool binary, T t)
WriteBasicType is the name of the write function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:34

◆ UnitTestIoStandard()

void kaldi::UnitTestIoStandard ( )

Definition at line 283 of file kaldi-io-test.cc.

References Output::Stream().

Referenced by main().

283  {
284  /*
285  Don't do the the following part because it requires
286  to pipe from an empty file, for it to not hang.
287  {
288  Input inp("", NULL); // standard input.
289  KALDI_ASSERT(inp.Stream().get() == -1);
290  }
291  {
292  Input inp("-", NULL); // standard input.
293  KALDI_ASSERT(inp.Stream().get() == -1);
294  }*/
295 
296  {
297  std::cout << "Should see: foo\n";
298  Output out("", false);
299  out.Stream() << "foo\n";
300  }
301  {
302  std::cout << "Should see: bar\n";
303  Output out("-", false);
304  out.Stream() << "bar\n";
305  }
306 }

◆ UnitTestIvectorExtractor()

void kaldi::UnitTestIvectorExtractor ( )

Definition at line 145 of file ivector-extractor-test.cc.

References IvectorExtractorStats::AccStatsForUtterance(), IvectorExtractorStats::AuxfPerFrame(), IvectorExtractorEstimationOptions::gaussian_min_count, kaldi::unittest::InitRandFullGmm(), IvectorExtractorOptions::ivector_dim, KALDI_ASSERT, KALDI_LOG, IvectorExtractorStatsOptions::num_samples_for_weights, Rand(), FullGmmNormal::Rand(), Matrix< Real >::Swap(), TestIvectorExtraction(), TestIvectorExtractorIO(), TestIvectorExtractorStatsIO(), IvectorExtractorStats::Update(), IvectorExtractorStatsOptions::update_variances, and IvectorExtractorOptions::use_weights.

Referenced by main().

145  {
146  FullGmm fgmm;
147  int32 dim = 5 + Rand() % 5, num_comp = 1 + Rand() % 5;
148  KALDI_LOG << "Num Gauss = " << num_comp;
149  unittest::InitRandFullGmm(dim, num_comp, &fgmm);
150  FullGmmNormal fgmm_normal(fgmm);
151 
152  IvectorExtractorOptions ivector_opts;
153  ivector_opts.ivector_dim = dim + 5;
154  ivector_opts.use_weights = (Rand() % 2 == 0);
155  KALDI_LOG << "Feature dim is " << dim
156  << ", ivector dim is " << ivector_opts.ivector_dim;
157  IvectorExtractor extractor(ivector_opts, fgmm);
158  TestIvectorExtractorIO(extractor);
159 
160  IvectorExtractorStatsOptions stats_opts;
161  if (Rand() % 2 == 0) stats_opts.update_variances = false;
162  stats_opts.num_samples_for_weights = 100; // Improve accuracy
163  // of estimation, since we do it with relatively few utterances,
164  // and we're testing the convergence.
165 
166  int32 num_utts = 1 + Rand() % 5;
167  std::vector<Matrix<BaseFloat> > all_feats(num_utts);
168  for (int32 utt = 0; utt < num_utts; utt++) {
169  int32 num_frames = 100 + Rand() % 200;
170  if (Rand() % 2 == 0) num_frames *= 10;
171  if (Rand() % 2 == 0) num_frames /= 1.0;
172  Matrix<BaseFloat> feats(num_frames, dim);
173  fgmm_normal.Rand(&feats);
174  feats.Swap(&all_feats[utt]);
175  }
176 
177  int32 num_iters = 4;
178  double last_auxf_impr = 0.0, last_auxf = 0.0;
179  for (int32 iter = 0; iter < num_iters; iter++) {
180  IvectorExtractorStats stats(extractor, stats_opts);
181 
182  for (int32 utt = 0; utt < num_utts; utt++) {
183  Matrix<BaseFloat> &feats = all_feats[utt];
184  stats.AccStatsForUtterance(extractor, feats, fgmm);
185  TestIvectorExtraction(extractor, feats, fgmm);
186  }
188 
189  IvectorExtractorEstimationOptions estimation_opts;
190  estimation_opts.gaussian_min_count = dim + 5;
191  double auxf = stats.AuxfPerFrame(),
192  auxf_impr = stats.Update(estimation_opts, &extractor);
193 
194  KALDI_LOG << "Iter " << iter << ", auxf per frame was " << auxf
195  << ", improvement in this update "
196  << "phase was " << auxf_impr;
197  if (iter > 0) {
198  double auxf_change = auxf - last_auxf;
199  KALDI_LOG << "Predicted auxf change from last update phase was "
200  << last_auxf_impr << " versus observed change "
201  << auxf_change;
202  double wiggle_room = (ivector_opts.use_weights ? 5.0e-05 : 1.0e-08);
203  // The weight update is (a) not exact, and (b) relies on sampling, [two
204  // separate issues], so it might not always improve. But with
205  // a large number of "weight samples", it's OK.
206  KALDI_ASSERT(auxf_change >= last_auxf_impr - wiggle_room);
207  }
208  last_auxf_impr = auxf_impr;
209  last_auxf = auxf;
210  }
211  std::cout << "********************************************************************************************\n";
212 }
void TestIvectorExtractorIO(const IvectorExtractor &extractor)
Definition for Gaussian Mixture Model with full covariances in normal mode: where the parameters are ...
Definition for Gaussian Mixture Model with full covariances.
Definition: full-gmm.h:40
IvectorExtractorStats is a class used to update the parameters of the ivector extractor.
kaldi::int32 int32
Options for IvectorExtractorStats, which is used to update the parameters of IvectorExtractor.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void InitRandFullGmm(int32 dim, int32 num_comp, FullGmm *gmm)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Options for training the IvectorExtractor, e.g. variance flooring.
#define KALDI_LOG
Definition: kaldi-error.h:153
void TestIvectorExtractorStatsIO(IvectorExtractorStats &stats)
void TestIvectorExtraction(const IvectorExtractor &extractor, const MatrixBase< BaseFloat > &feats, const FullGmm &fgmm)

◆ UnitTestKeele()

static void kaldi::UnitTestKeele ( )
static

Definition at line 366 of file pitch-functions-test.cc.

References ComputeKaldiPitch(), ConvertIntToString(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, PitchExtractionOptions::nccf_ballast, WaveData::Read(), and MatrixBase< Real >::Write().

Referenced by UnitTestFeatWithKeele().

366  {
367  KALDI_LOG << "=== UnitTestKeele() ===";
368  for (int32 i = 1; i < 11; i++) {
369  std::string wavefile;
370  std::string num;
371  if (i < 6) {
372  num = "f" + ConvertIntToString(i) + "nw0000";
373  wavefile = "keele/16kHz/"+num+".wav";
374  } else {
375  num = "m" + ConvertIntToString(i-5) + "nw0000";
376  wavefile = "keele/16kHz/"+num+".wav";
377  }
378  KALDI_LOG << "--- " << wavefile << " ---";
379  std::ifstream is(wavefile.c_str(), std::ios_base::binary);
380  WaveData wave;
381  wave.Read(is);
382  KALDI_ASSERT(wave.Data().NumRows() == 1);
383  SubVector<BaseFloat> waveform(wave.Data(), 0);
384  // use pitch code with default configuration..
386  op.nccf_ballast = 1;
387  op.penalty_factor = 5;
388  // compute pitch.
390  ComputeKaldiPitch(op, waveform, &m);
391  std::string outfile = "keele/tmp/+"+num+"-kaldi.txt";
392  std::ofstream os(outfile.c_str());
393  m.Write(os, false);
394  }
395 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
void Write(std::ostream &out, bool binary) const
write to stream.
std::string ConvertIntToString(const int &number)
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
kaldi::int32 int32
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestKeeleNccfBallast()

static void kaldi::UnitTestKeeleNccfBallast ( )
static

Definition at line 430 of file pitch-functions-test.cc.

References ComputeKaldiPitch(), ConvertIntToString(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, PitchExtractionOptions::nccf_ballast, WaveData::Read(), and MatrixBase< Real >::Write().

Referenced by UnitTestFeatWithKeele().

430  {
431  KALDI_LOG << "=== UnitTestKeeleNccfBallast() ===";
432  for (int32 k = 1; k < 10; k++) {
433  for (int32 i = 1; i < 2; i++) {
434  std::string wavefile;
435  std::string num;
436  if (i < 6) {
437  num = "f"+ConvertIntToString(i)+"nw0000";
438  wavefile = "keele/16kHz/"+num+".wav";
439  } else {
440  num = "m"+ConvertIntToString(i-5)+"nw0000";
441  wavefile = "keele/16kHz/"+num+".wav";
442  }
443  KALDI_LOG << "--- " << wavefile << " ---";
444  std::ifstream is(wavefile.c_str(), std::ios_base::binary);
445  WaveData wave;
446  wave.Read(is);
447  KALDI_ASSERT(wave.Data().NumRows() == 1);
448  SubVector<BaseFloat> waveform(wave.Data(), 0);
449  // use pitch code with default configuration..
451  op.nccf_ballast = 0.05 * k;
452  KALDI_LOG << " nccf_ballast " << op.nccf_ballast;
453  // compute pitch.
455  ComputeKaldiPitch(op, waveform, &m);
456  std::string nccfballast = ConvertIntToString(op.nccf_ballast);
457  std::string outfile = "keele/tmp/+"+num
458  +"-kaldi-nccf-ballast-"+nccfballast+".txt";
459  std::ofstream os(outfile.c_str());
460  m.Write(os, false);
461  }
462  }
463 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
void Write(std::ostream &out, bool binary) const
write to stream.
std::string ConvertIntToString(const int &number)
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
kaldi::int32 int32
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestLbfgs()

static void kaldi::UnitTestLbfgs ( )
static

Definition at line 3170 of file matrix-lib-test.cc.

References VectorBase< Real >::AddSpVec(), VectorBase< Real >::AddVec(), OptimizeLbfgs< Real >::DoStep(), Exp(), g_kaldi_verbose_level, OptimizeLbfgs< Real >::GetProposedValue(), OptimizeLbfgs< Real >::GetValue(), SpMatrix< Real >::Invert(), KALDI_VLOG, LbfgsOptions::minimize, VectorBase< Real >::Norm(), Rand(), RandPosdefSpMatrix(), OptimizeLbfgs< Real >::RecentStepLength(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), VecSpVec(), and VecVec().

3170  {
3173  for (MatrixIndexT iter = 0; iter < 3; iter++) {
3174  bool minimize = (iter % 2 == 0);
3175  MatrixIndexT dim = 1 + Rand() % 30;
3176  SpMatrix<Real> S(dim);
3177  RandPosdefSpMatrix(dim, &S);
3178  Vector<Real> v(dim);
3179  v.SetRandn();
3180  // Function will be f = exp(0.1 * [ x' v -0.5 x' S x ])
3181  // This is to maximize; we negate it when minimizing.
3182 
3183  //Vector<Real> hessian(dim);
3184  //hessian.CopyDiagFromSp(S);
3185 
3186  SpMatrix<Real> Sinv(S);
3187  Sinv.Invert();
3188  Vector<Real> x_opt(dim);
3189  x_opt.AddSpVec(1.0, Sinv, v, 0.0); // S^{-1} v-- the optimum.
3190 
3191  Vector<Real> init_x(dim);
3192  init_x.SetRandn();
3193 
3194  LbfgsOptions opts;
3195  opts.minimize = minimize; // This objf has a maximum, not a minimum.
3196  OptimizeLbfgs<Real> opt_lbfgs(init_x, opts);
3197  MatrixIndexT num_iters = 0;
3198  Real c = 0.01;
3199  Real sign = (minimize ? -1.0 : 1.0); // function has a maximum not minimum..
3200  while (opt_lbfgs.RecentStepLength() > 1.0e-04) {
3201  KALDI_VLOG(2) << "Last step length is " << opt_lbfgs.RecentStepLength();
3202  const VectorBase<Real> &x = opt_lbfgs.GetProposedValue();
3203  Real logf = VecVec(x, v) - 0.5 * VecSpVec(x, S, x);
3204  Vector<Real> dlogf_dx(v); // derivative of log(f) w.r.t. x.
3205  dlogf_dx.AddSpVec(-1.0, S, x, 1.0);
3206  KALDI_VLOG(2) << "Gradient magnitude is " << dlogf_dx.Norm(2.0);
3207  Real f = Exp(c * logf);
3208  Vector<Real> df_dx(dlogf_dx);
3209  df_dx.Scale(f * c); // comes from derivative of the exponential function.
3210  f *= sign;
3211  df_dx.Scale(sign);
3212  opt_lbfgs.DoStep(f, df_dx);
3213  num_iters++;
3214  }
3215  Vector<Real> x (opt_lbfgs.GetValue());
3216  Vector<Real> diff(x);
3217  diff.AddVec(-1.0, x_opt);
3218  KALDI_VLOG(2) << "L-BFGS finished after " << num_iters << " function evaluations.";
3219  /*
3220  if (sizeof(Real) == 8) {
3221  KALDI_ASSERT(diff.Norm(2.0) < 0.5);
3222  } else {
3223  KALDI_ASSERT(diff.Norm(2.0) < 2.0);
3224  } */
3225  }
3226  g_kaldi_verbose_level = temp;
3227 }
double Exp(double x)
Definition: kaldi-math.h:83
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
Real VecSpVec(const VectorBase< Real > &v1, const SpMatrix< Real > &M, const VectorBase< Real > &v2)
Computes v1^T * M * v2.
Definition: sp-matrix.cc:964
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
int32 g_kaldi_verbose_level
This is set by util/parse-options.
Definition: kaldi-error.cc:46
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
This is an implementation of L-BFGS.
Definition: optimization.h:84
Provides a vector abstraction class.
Definition: kaldi-vector.h:41
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37
void RandPosdefSpMatrix(size_t dim, SpMatrix< BaseFloat > *matrix, TpMatrix< BaseFloat > *matrix_sqrt=NULL, BaseFloat *logdet=NULL)

◆ UnitTestLimitCond()

static void kaldi::UnitTestLimitCond ( )
static

Definition at line 2345 of file matrix-lib-test.cc.

References rnnlm::i, KALDI_ASSERT, SpMatrix< Real >::LimitCond(), and Rand().

2345  {
2346  for (MatrixIndexT i = 0;i < 5;i++) {
2347  MatrixIndexT dimM = 20 + Rand()%10;
2348  SpMatrix<Real> B(dimM);
2349  B(1, 1) = 10000;
2350  KALDI_ASSERT(B.LimitCond(1000) == (dimM-1));
2351  KALDI_ASSERT(std::abs(B(2, 2) - 10.0) < 0.01);
2352  KALDI_ASSERT(std::abs(B(3, 0)) < 0.001);
2353  }
2354 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestLimitCondInvert()

static void kaldi::UnitTestLimitCondInvert ( )
static

Definition at line 2202 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::AddMatMat(), rnnlm::i, MatrixBase< Real >::IsUnit(), KALDI_ASSERT, kNoTrans, SpMatrix< Real >::LimitCond(), Rand(), and MatrixBase< Real >::SetRandn().

2202  {
2203  for (MatrixIndexT i = 0;i < 10;i++) {
2204  MatrixIndexT dimM = 20 + Rand()%10;
2205  MatrixIndexT dimN = dimM + 1 + Rand()%10;
2206 
2207  SpMatrix<Real> B(dimM);
2208  Matrix<Real> X(dimM, dimN);
2209  X.SetRandn();
2210  B.AddMat2(1.0, X, kNoTrans, 0.0); // B = X*X^T -> positive definite (almost certainly), since N > M.
2211 
2212 
2213  SpMatrix<Real> B2(B);
2214  B2.LimitCond(1.0e+10, true); // Will invert.
2215 
2216  Matrix<Real> Bf(B), B2f(B2);
2217  Matrix<Real> I(dimM, dimM); I.AddMatMat(1.0, Bf, kNoTrans, B2f, kNoTrans, 0.0);
2218  KALDI_ASSERT(I.IsUnit(0.1));
2219  }
2220 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestLinearCgd()

static void kaldi::UnitTestLinearCgd ( )
static

Definition at line 3230 of file matrix-lib-test.cc.

References VectorBase< Real >::AddSpVec(), VectorBase< Real >::AddVec(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, LinearCgd(), LinearCgdOptions::max_error, LinearCgdOptions::max_iters, SpMatrix< Real >::MaxAbsEig(), VectorBase< Real >::Norm(), Rand(), RandPosdefSpMatrix(), and VectorBase< Real >::SetRandn().

3230  {
3231  for (int i = 0; i < 20 ; i++) {
3232  MatrixIndexT M = 1 + Rand() % 20;
3233 
3234  SpMatrix<Real> A(M);
3235  RandPosdefSpMatrix(M, &A);
3236  Vector<Real> x(M), b(M), b2(M);
3237 
3238  LinearCgdOptions opts;
3239  if (Rand() % 2 == 0)
3240  opts.max_iters = 1 + Rand() % 10;
3241  if (Rand() % 2 == 0)
3242  opts.max_error = 1.0; // note: an absolute, not relative, error.
3243 
3244  x.SetRandn();
3245 
3246  b.AddSpVec(1.0, A, x, 0.0);
3247  Vector<Real> x_e(M); // x_e means x_estimated.
3248  x_e.SetRandn();
3249 
3250  int32 iters = LinearCgd(opts, A, b, &x_e);
3251 
3252  b2.AddSpVec(1.0, A, x_e, 0.0);
3253 
3254  Vector<Real> residual_error(b);
3255  residual_error.AddVec(-1.0, b2);
3256 
3257  BaseFloat error = residual_error.Norm(2.0);
3258 
3259  if (iters >= M) {
3260  // should have converged fully.
3261  Real max_abs = A.MaxAbsEig();
3262  KALDI_LOG << "error = " << error << ", b norm is " << b.Norm(2.0)
3263  << ", A max-abs-eig is " << max_abs;
3264  KALDI_ASSERT(error < 1.0e-04 * b.Norm(2.0) * max_abs);
3265  } else {
3266  BaseFloat wiggle_room = 1.1;
3267  if (opts.max_iters >= 0) {
3268  KALDI_ASSERT(iters <= opts.max_iters);
3269  if (iters < opts.max_iters) {
3270  KALDI_ASSERT(error <= wiggle_room * opts.max_error);
3271  }
3272  } else {
3273  KALDI_ASSERT(error <= wiggle_room * opts.max_error);
3274  }
3275  }
3276  }
3277 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 LinearCgd(const LinearCgdOptions &opts, const SpMatrix< Real > &A, const VectorBase< Real > &b, VectorBase< Real > *x)
#define KALDI_LOG
Definition: kaldi-error.h:153
void RandPosdefSpMatrix(size_t dim, SpMatrix< BaseFloat > *matrix, TpMatrix< BaseFloat > *matrix_sqrt=NULL, BaseFloat *logdet=NULL)

◆ UnitTestLogAddSub()

void kaldi::UnitTestLogAddSub ( )

Definition at line 171 of file kaldi-math-test.cc.

References Exp(), rnnlm::i, KALDI_ASSERT, Log(), LogAdd(), LogSub(), and Rand().

Referenced by main().

171  {
172  for (int i = 0; i < 100; i++) {
173  double f1 = Rand() % 10000, f2 = Rand() % 20;
174  double add1 = Exp(LogAdd(Log(f1), Log(f2)));
175  double add2 = Exp(LogAdd(Log(f2), Log(f1)));
176  double add = f1 + f2, thresh = add*0.00001;
177  KALDI_ASSERT(std::abs(add-add1) < thresh && std::abs(add-add2) < thresh);
178 
179 
180  try {
181  double f2_check = Exp(LogSub(Log(add), Log(f1))),
182  thresh = (f2*0.01)+0.001;
183  KALDI_ASSERT(std::abs(f2_check-f2) < thresh);
184  } catch(...) {
185  KALDI_ASSERT(f2 == 0); // It will probably crash for f2=0.
186  }
187  }
188 }
double Exp(double x)
Definition: kaldi-math.h:83
double Log(double x)
Definition: kaldi-math.h:100
double LogSub(double x, double y)
Definition: kaldi-math.h:228
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
double LogAdd(double x, double y)
Definition: kaldi-math.h:184
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestLogSpeed()

void kaldi::UnitTestLogSpeed ( )

Definition at line 297 of file kaldi-math-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, and Log().

297  {
298  Real sum = 0.0; // compute the sum to avoid optimizing it away.
299  Real time = 0.01; // how long this should last.
300  int block_size = 10;
301  int num_ops = 0;
302  Timer tim;
303  while (tim.Elapsed() < time) {
304  for (int i = 0; i < block_size; i++) {
305  sum += Log(static_cast<float>(i + 1));
306  }
307  num_ops += block_size;
308  }
309  KALDI_ASSERT(sum > 0.0); // make it harder for the compiler to optimize Log
310  // away, as we have a conditional.
311  Real flops = 1.0e-06 * num_ops / tim.Elapsed();
312  KALDI_LOG << "Megaflops doing Log("
313  << (sizeof(Real) == 4 ? "float" : "double") << ") is " << flops;
314 }
double Log(double x)
Definition: kaldi-math.h:100
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestLstmNonlinearity()

void kaldi::UnitTestLstmNonlinearity ( )

Definition at line 213 of file cu-math-test.cc.

References CuMatrixBase< Real >::AddMat(), ApproxEqual(), kaldi::cu::BackpropLstmNonlinearity(), CuMatrixBase< Real >::ColRange(), kaldi::cu::ComputeLstmNonlinearity(), rnnlm::i, KALDI_ERR, KALDI_LOG, kTrans, RandInt(), CuMatrixBase< Real >::Row(), CuMatrixBase< Real >::Scale(), and TraceMatMat().

Referenced by CudaMathUnitTest().

213  {
214  for (int32 loop = 0; loop < 10; loop++) {
215 
216  // problem dimensions.
217  int32 num_rows = RandInt(5, 20),
218  cell_dim = RandInt(2, 200),
219  dropout_dim = (RandInt(0, 1) == 0 ? 0 : 3);
220 
221  // Pick the (input or params block), and output block, for which we'll
222  // spot-check the derivative values. This will give us test failures
223  // that are fine-grained enough to assist debugging.
224  int32 test_input = RandInt(0, 4),
225  test_params = RandInt(0, 2),
226  test_output = RandInt(0, 1);
227 
228  // set one of test_input or test_params to -1, meaning we're not testing that
229  // thing. only test one at a time.
230  if (RandInt(0, 1) == 0)
231  test_input = -1;
232  else
233  test_params = -1;
234 
235 
236  CuMatrix<BaseFloat> input(num_rows, cell_dim * 5 + dropout_dim),
237  params(3, cell_dim),
238  output_deriv(num_rows, cell_dim * 2);
239  input.SetRandn();
240  params.SetRandn();
241  // set just one block of the output deriv to a random value.
242  output_deriv.ColRange(test_output * cell_dim, cell_dim).SetRandn();
243 
244 
245 
246  CuMatrix<BaseFloat> output(num_rows, cell_dim * 2);
247 
248  cu::ComputeLstmNonlinearity(input, params, &output);
249 
250  BaseFloat baseline_objf = TraceMatMat(output, output_deriv, kTrans);
251 
252  // not really testing self repair here... will debug it when we actually run
253  // it, by looking at the diagnostics.
254  CuMatrix<double> deriv_sum(5, cell_dim),
255  value_sum(5, cell_dim);
256  CuVector<BaseFloat> self_repair_config(10.0); // leave at zero... we don't really test this here.
258  self_repair_sum(5, cell_dim),
259  input_deriv(num_rows, 5 * cell_dim + dropout_dim),
260  params_deriv(3, cell_dim);
261 
262  double count_in = 0.0;
263 
264  // get derivative w.r.t. input and params, which we are testing.
265  cu::BackpropLstmNonlinearity(input, params, output_deriv, deriv_sum,
266  self_repair_config, count_in,
267  &input_deriv, &params_deriv,
268  &value_sum, &deriv_sum, &self_repair_sum);
269 
270 
271  int32 test_dim = 5; // number of separate offsets we add while testing the
272  // derivatives... reduces randomness in test.
273  BaseFloat delta = 1.0e-03;
274  Vector<BaseFloat> predicted_objf_change(test_dim),
275  measured_objf_change(test_dim);
276 
277  for (int32 i = 0; i < test_dim; i++) {
278  CuMatrix<BaseFloat> delta_input(num_rows, 5 * cell_dim + dropout_dim),
279  delta_params(3, cell_dim);
280  if (test_input >= 0) {
281  delta_input.ColRange(test_input * cell_dim, cell_dim).SetRandn();
282  delta_input.Scale(delta);
283  }
284  if (test_params >= 0) {
285  delta_params.Row(test_params).SetRandn();
286  delta_params.Scale(delta);
287  }
288 
289  predicted_objf_change(i) = TraceMatMat(delta_input, input_deriv, kTrans) +
290  TraceMatMat(delta_params, params_deriv, kTrans);
291 
292  CuMatrix<BaseFloat> perturbed_input(input);
293  perturbed_input.AddMat(1.0, delta_input);
294 
295  CuMatrix<BaseFloat> perturbed_params(params);
296  perturbed_params.AddMat(1.0, delta_params);
297 
298  CuMatrix<BaseFloat> perturbed_output(num_rows, 2 * cell_dim);
299  cu::ComputeLstmNonlinearity(perturbed_input, perturbed_params,
300  &perturbed_output);
301  BaseFloat new_objf = TraceMatMat(perturbed_output, output_deriv, kTrans),
302  objf_change = new_objf - baseline_objf;
303  measured_objf_change(i) = objf_change;
304  }
305  KALDI_LOG << "LSTM nonlinearity test: num_rows=" << num_rows
306  << ", cell_dim=" << cell_dim
307  << ", dropout_dim=" << dropout_dim
308  << ", test_input=" << test_input
309  << ", test_params=" << test_params
310  << ", test_output=" << test_output
311  << ", predicted_objf_change=" << predicted_objf_change
312  << ", measured_objf_change=" << measured_objf_change;
313 
314  if (!ApproxEqual(predicted_objf_change, measured_objf_change, BaseFloat(0.1F))) {
315  KALDI_ERR << "LSTM nonlinearity test failed.";
316  }
317  }
318 }
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
void BackpropLstmNonlinearity(const CuMatrixBase< Real > &input, const CuMatrixBase< Real > &params, const CuMatrixBase< Real > &output_deriv, const CuMatrixBase< double > &deriv_sum_in, const CuVectorBase< Real > &self_repair_config, double count_in, CuMatrixBase< Real > *input_deriv, CuMatrixBase< Real > *params_deriv, CuMatrixBase< double > *value_sum_out, CuMatrixBase< double > *deriv_sum_out, CuMatrixBase< Real > *self_repair_sum_out)
This function does the &#39;backward&#39; pass corresponding to the function ComputeLstmNonlinearity.
Definition: cu-math.cc:768
float BaseFloat
Definition: kaldi-types.h:29
#define KALDI_ERR
Definition: kaldi-error.h:147
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95
void ComputeLstmNonlinearity(const CuMatrixBase< Real > &input, const CuMatrixBase< Real > &params, CuMatrixBase< Real > *output)
this is a special-purpose function used by class LstmNonlinearityComponent, to do its forward propaga...
Definition: cu-math.cc:489

◆ UnitTestMat2Vec()

static void kaldi::UnitTestMat2Vec ( )
static

Definition at line 2317 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), SpMatrix< Real >::AddMat2Vec(), AssertEqual(), SpMatrix< Real >::CopyFromSp(), rnnlm::i, kNoTrans, kTrans, Rand(), PackedMatrix< Real >::Scale(), MatrixBase< Real >::SetRandn(), and SpMatrix< Real >::SymPosSemiDefEig().

2317  {
2318  for (MatrixIndexT i = 0; i < 5; i++) {
2319  MatrixIndexT dimM = 10 + Rand() % 10;
2320 
2321  Matrix<Real> M(dimM, dimM);
2322  M.SetRandn();
2323  SpMatrix<Real> B(dimM);
2324  B.AddMat2(1.0, M, kNoTrans, 0.0); // B = M*M^T -> positive definite (since M nonsingular).
2325 
2326  Matrix<Real> P(dimM, dimM);
2327  Vector<Real> s(dimM);
2328 
2329  B.SymPosSemiDefEig(&s, &P);
2330  SpMatrix<Real> B2(dimM);
2331  B2.CopyFromSp(B);
2332  B2.Scale(0.25);
2333 
2334  // B2 <-- 2.0*B2 + 0.5 * P * diag(v) * P^T
2335  B2.AddMat2Vec(0.5, P, kNoTrans, s, 2.0); // 2.0 * 0.25 + 0.5 = 1.
2336  AssertEqual(B, B2);
2337 
2338  SpMatrix<Real> B3(dimM);
2339  Matrix<Real> PT(P, kTrans);
2340  B3.AddMat2Vec(1.0, PT, kTrans, s, 0.0);
2341  AssertEqual(B, B3);
2342  }
2343 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestMatrix()

static void kaldi::UnitTestMatrix ( )
static

Definition at line 338 of file cu-test.cc.

References CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, Rand(), MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetRandn().

338  {
339  //operator()
340  for (MatrixIndexT iter = 0; iter < 2; iter++) {
341  int32 dim1 = 6 + Rand() % 10;
342  int32 dim2 = 8 + Rand() % 10;
343  Matrix<Real> A(dim1,dim2);
344  A.SetRandn();
345  CuMatrix<Real> B(A);
346  KALDI_ASSERT(A(3, 4) == B(3, 4));
347  B(3, 4) = 2.0;
348  A(3, 4) = B(3, 4);
349  KALDI_ASSERT(A(3, 4) == B(3, 4));
350 
351  SpMatrix<Real> As(dim1);
352  CuSpMatrix<Real> Bs(As);
353  KALDI_ASSERT(As(3, 4) == Bs(3, 4));
354  Bs(3, 4) = 2.0;
355  if (Rand() % 2 == 0)
356  As(3, 4) = Bs(3, 4);
357  else
358  As(3, 4) = (const_cast<const CuSpMatrix<Real>&>(Bs))(3, 4);
359 
360  KALDI_ASSERT(As(3, 4) == Bs(3, 4));
361 
362  Vector<Real> v(dim1);
363  CuVector<Real> w(v);
364  KALDI_ASSERT(w(2) == v(2));
365  w(2) = 3.0;
366  v(2) = w(2);
367  KALDI_ASSERT(w(2) == v(2));
368  }
369 
370  //SetRandn
371  for (MatrixIndexT iter = 0; iter < 10; iter++) {
372  int32 dim1 = 15 + Rand() % 10;
373  int32 dim2 = dim1;//10 + Rand() % 14;
374  //KALDI_LOG << "dimension is " << dim1
375  // << " " << dim2 << '\n';
376  CuMatrix<Real> A(dim1,dim2);
377  A.SetRandn();
378  Matrix<Real> A1(dim1,dim2);
379  A.CopyToMat(&A1);
380  //KALDI_LOG << "gpu sum is: " << A.Sum();
381  //KALDI_LOG << "cpu sum is: " << A1.Sum();
382  }
383 }
Packed symetric matrix class.
Definition: matrix-common.h:62
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestMatrixAddMatSmat()

void kaldi::UnitTestMatrixAddMatSmat ( )

Definition at line 229 of file sparse-matrix-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddMatSmat(), AssertEqual(), KALDI_ASSERT, kNoTrans, kTrans, rnnlm::n, RandInt(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), TraceMatMat(), and TraceMatSmat().

229  {
230 
231  for (int32 t = 0; t < 4; t++) {
232  MatrixIndexT m = RandInt(10, 20), n = RandInt(10, 20), o = RandInt(10, 20);
233  MatrixTransposeType Btrans = (RandInt(0, 1) == 0 ? kTrans : kNoTrans);
234 
235  // we are effectively comparing trace(A B C) computed as
236  // trace((A B) C) vs. trace ((C A) B)
237 
238  BaseFloat alpha = 0.333, beta = 1.764;
239 
240 
241  Matrix<Real> A(m, n);
242  A.SetRandn();
243  SparseMatrix<Real> B(Btrans == kNoTrans ? n : o,
244  Btrans == kNoTrans ? o : n);
245  B.SetRandn(0.5);
246 
247  Matrix<Real> AB(m, o);
248  AB.SetRandn(); // this random extra part is used in testing the 'beta'.
249 
250  Matrix<Real> C(o, m);
251  C.SetRandn();
252 
253  Matrix<Real> CA(o, n);
254  CA.AddMatMat(1.0, C, kNoTrans, A, kNoTrans, 0.0);
255  Real trace_abc_alpha = TraceMatSmat(CA, B, Btrans);
256 
257  Real trace_abc_beta = TraceMatMat(AB, C, kNoTrans);
258 
259  AB.AddMatSmat(alpha, A, B, Btrans, beta);
260 
261  // next line is in case I made certain mistakes like setting matrix to
262  // random.
263  KALDI_ASSERT(trace_abc_alpha != 0.0 && trace_abc_beta != 0.0);
264  Real result1 = TraceMatMat(AB, C, kNoTrans),
265  result2 = alpha * trace_abc_alpha + beta * trace_abc_beta;
266  AssertEqual(result1, result2, 0.01);
267  }
268 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Real TraceMatSmat(const MatrixBase< Real > &A, const SparseMatrix< Real > &B, MatrixTransposeType trans)
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestMatrixAddSmatMat()

void kaldi::UnitTestMatrixAddSmatMat ( )

Definition at line 272 of file sparse-matrix-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddSmatMat(), AssertEqual(), KALDI_ASSERT, kNoTrans, kTrans, rnnlm::n, RandInt(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), TraceMatMat(), and TraceMatSmat().

272  {
273 
274  for (int32 t = 0; t < 4; t++) {
275  MatrixIndexT m = RandInt(10, 20), n = RandInt(10, 20), o = RandInt(10, 20);
276  MatrixTransposeType Btrans = (RandInt(0, 1) == 0 ? kTrans : kNoTrans);
277 
278  // we are effectively comparing trace(A B C) computed as
279  // trace((A B) C) vs. trace ((C A) B)
280 
281  BaseFloat alpha = 0.333, beta = 1.764;
282 
283  Matrix<Real> A(m, n);
284  A.SetRandn();
285  SparseMatrix<Real> B(Btrans == kNoTrans ? n : o,
286  Btrans == kNoTrans ? o : n);
287  B.SetRandn(0.5);
288 
289  Matrix<Real> C(o, m);
290  C.SetRandn();
291 
292  Matrix<Real> BC(n, m);
293  BC.SetRandn(); // this random extra part is used in testing the 'beta'.
294 
295  Matrix<Real> CA(o, n);
296  CA.AddMatMat(1.0, C, kNoTrans, A, kNoTrans, 0.0);
297  Real trace_abc_alpha = TraceMatSmat(CA, B, Btrans);
298 
299  Real trace_abc_beta = TraceMatMat(A, BC, kNoTrans);
300 
301  BC.AddSmatMat(alpha, B, Btrans, C, beta);
302 
303  // next line is in case I made certain mistakes like setting matrix to
304  // random.
305  KALDI_ASSERT(trace_abc_alpha != 0.0 && trace_abc_beta != 0.0);
306  Real result1 = TraceMatMat(A, BC, kNoTrans),
307  result2 = alpha * trace_abc_alpha + beta * trace_abc_beta;
308  AssertEqual(result1, result2, 0.01);
309  }
310 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Real TraceMatSmat(const MatrixBase< Real > &A, const SparseMatrix< Real > &B, MatrixTransposeType trans)
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestMax2()

static void kaldi::UnitTestMax2 ( )
static

Definition at line 3143 of file matrix-lib-test.cc.

References AssertEqual(), MatrixBase< Real >::CopyFromMat(), rnnlm::i, MatrixBase< Real >::Max(), and Rand().

3143  {
3144  for (MatrixIndexT i = 0; i < 2; i++) {
3145  MatrixIndexT M = 1 + Rand() % 10, N = 1 + Rand() % 10;
3146  Matrix<Real> A(M, N), B(M, N), C(M, N), D(M, N);
3147  A.SetRandn();
3148  B.SetRandn();
3149  for (MatrixIndexT r = 0; r < M; r++)
3150  for (MatrixIndexT c = 0; c < N; c++)
3151  C(r, c) = std::max(A(r, c), B(r, c));
3152  D.CopyFromMat(A);
3153  D.Max(B);
3154  AssertEqual(C, D);
3155  }
3156 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestMaxAbsEig()

static void kaldi::UnitTestMaxAbsEig ( )
static

Definition at line 3158 of file matrix-lib-test.cc.

References AssertEqual(), SpMatrix< Real >::Eig(), rnnlm::i, VectorBase< Real >::Max(), SpMatrix< Real >::MaxAbsEig(), VectorBase< Real >::Min(), and PackedMatrix< Real >::SetRandn().

3158  {
3159  for (MatrixIndexT i = 0; i < 1; i++) {
3160  SpMatrix<Real> M(10);
3161  M.SetRandn();
3162  Matrix<Real> P(10, 10);
3163  Vector<Real> s(10);
3164  M.Eig(&s, (i == 0 ? static_cast<Matrix<Real>*>(NULL) : &P));
3165  Real max_eig = std::max(-s.Min(), s.Max());
3166  AssertEqual(max_eig, M.MaxAbsEig());
3167  }
3168 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestMaxMin()

static void kaldi::UnitTestMaxMin ( )
static

Definition at line 3280 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, rnnlm::j, PackedMatrix< Real >::Max(), MatrixBase< Real >::Max(), VectorBase< Real >::Max(), PackedMatrix< Real >::Min(), MatrixBase< Real >::Min(), VectorBase< Real >::Min(), Rand(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

3280  {
3281 
3282  MatrixIndexT M = 1 + Rand() % 10, N = 1 + Rand() % 10;
3283  {
3284  Vector<Real> v(N);
3285  v.SetRandn();
3286  Real min = 1.0e+10, max = -1.0e+10;
3287  for (MatrixIndexT i = 0; i< N; i++) {
3288  min = std::min(min, v(i));
3289  max = std::max(max, v(i));
3290  }
3291  AssertEqual(min, v.Min());
3292  AssertEqual(max, v.Max());
3293  }
3294  {
3295  SpMatrix<Real> S(N);
3296  S.SetRandn();
3297  Real min = 1.0e+10, max = -1.0e+10;
3298  for (MatrixIndexT i = 0; i< N; i++) {
3299  for (MatrixIndexT j = 0; j <= i; j++) {
3300  min = std::min(min, S(i, j));
3301  max = std::max(max, S(i, j));
3302  }
3303  }
3304  AssertEqual(min, S.Min());
3305  AssertEqual(max, S.Max());
3306  }
3307  {
3308  Matrix<Real> mat(M, N);
3309  mat.SetRandn();
3310  Real min = 1.0e+10, max = -1.0e+10;
3311  for (MatrixIndexT i = 0; i< M; i++) {
3312  for (MatrixIndexT j = 0; j < N; j++) {
3313  min = std::min(min, mat(i, j));
3314  max = std::max(max, mat(i, j));
3315  }
3316  }
3317  AssertEqual(min, mat.Min());
3318  AssertEqual(max, mat.Max());
3319  }
3320 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestMmul()

static void kaldi::UnitTestMmul ( )
static

Definition at line 1693 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), rnnlm::i, rnnlm::j, KALDI_ASSERT, kNoTrans, and Rand().

1693  {
1694  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1695  MatrixIndexT dimM = 20 + Rand()%10, dimN = 20 + Rand()%10, dimO = 20 + Rand()%10; // dims between 10 and 20.
1696  // MatrixIndexT dimM = 2, dimN = 3, dimO = 4;
1697  Matrix<Real> A(dimM, dimN), B(dimN, dimO), C(dimM, dimO);
1698  A.SetRandn();
1699  B.SetRandn();
1700  //
1701  // KALDI_LOG <<"a = " << A;
1702  // KALDI_LOG<<"B = " << B;
1703  C.AddMatMat(1.0, A, kNoTrans, B, kNoTrans, 0.0); // C = A * B.
1704  // KALDI_LOG << "c = " << C;
1705  for (MatrixIndexT i = 0;i < dimM;i++) {
1706  for (MatrixIndexT j = 0;j < dimO;j++) {
1707  double sum = 0.0;
1708  for (MatrixIndexT k = 0;k < dimN;k++) {
1709  sum += A(i, k) * B(k, j);
1710  }
1711  KALDI_ASSERT(std::abs(sum - C(i, j)) < 0.0001);
1712  }
1713  }
1714  }
1715 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestMmulSym()

static void kaldi::UnitTestMmulSym ( )
static

Definition at line 1718 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddSpSp(), AssertEqual(), kNoTrans, kTrans, and Rand().

1718  {
1719 
1720  // Test matrix multiplication on symmetric matrices.
1721  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1722  MatrixIndexT dimM = 20 + Rand()%10;
1723 
1724  Matrix<Real> A(dimM, dimM), B(dimM, dimM), C(dimM, dimM), tmp(dimM, dimM), tmp2(dimM, dimM);
1725  SpMatrix<Real> sA(dimM), sB(dimM), sC(dimM), stmp(dimM);
1726 
1727  A.SetRandn();
1728  B.SetRandn();
1729  C.SetRandn();
1730  // Make A, B, C symmetric.
1731  tmp.CopyFromMat(A); A.AddMat(1.0, tmp, kTrans);
1732  tmp.CopyFromMat(B); B.AddMat(1.0, tmp, kTrans);
1733  tmp.CopyFromMat(C); C.AddMat(1.0, tmp, kTrans);
1734 
1735  sA.CopyFromMat(A);
1736  sB.CopyFromMat(B);
1737  sC.CopyFromMat(C);
1738 
1739 
1740  tmp.AddMatMat(1.0, A, kNoTrans, B, kNoTrans, 0.0); // tmp = A * B.
1741  tmp2.AddSpSp(1.0, sA, sB, 0.0); // tmp = sA*sB.
1742  AssertEqual(tmp, tmp2);
1743  tmp2.AddSpSp(1.0, sA, sB, 0.0); // tmp = sA*sB.
1744  AssertEqual(tmp, tmp2);
1745  }
1746 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestMul()

static void kaldi::UnitTestMul ( )
static

Definition at line 2750 of file matrix-lib-test.cc.

References VectorBase< Real >::AddMatVec(), VectorBase< Real >::AddSpVec(), VectorBase< Real >::AddTpVec(), AssertEqual(), MatrixBase< Real >::CopyFromTp(), rnnlm::i, kNoTrans, kTrans, Rand(), VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

2750  {
2751  for (MatrixIndexT x = 0; x<=1; x++) {
2752  MatrixTransposeType trans = (x == 1 ? kTrans: kNoTrans);
2753  for (MatrixIndexT i = 0;i < 5;i++) {
2754  float alpha = 1.0, beta =0;
2755  if (i%3 == 0) beta = 0.5;
2756  if (i%5 == 0) alpha = 0.7;
2757  MatrixIndexT dimM = (Rand()%10) + 10;
2758  Vector<Real> v(dimM);
2759  v.SetRandn();
2760  TpMatrix<Real> T(dimM);
2761  T.SetRandn();
2762  Matrix<Real> M(dimM, dimM);
2763  if (i%2 == 1)
2764  M.CopyFromTp(T, trans);
2765  else
2766  M.CopyFromTp(T, kNoTrans);
2767  Vector<Real> v2(v);
2768  Vector<Real> v3(v);
2769  v2.AddTpVec(alpha, T, trans, v, beta);
2770  if (i%2 == 1)
2771  v3.AddMatVec(alpha, M, kNoTrans, v, beta);
2772  else
2773  v3.AddMatVec(alpha, M, trans, v, beta);
2774 
2775  v.AddTpVec(alpha, T, trans, v, beta);
2776  AssertEqual(v2, v3);
2777  AssertEqual(v, v2);
2778  }
2779 
2780  for (MatrixIndexT i = 0;i < 5;i++) {
2781  float alpha = 1.0, beta =0;
2782  if (i%3 == 0) beta = 0.5;
2783  if (i%5 == 0) alpha = 0.7;
2784 
2785  MatrixIndexT dimM = (Rand()%10) + 10;
2786  Vector<Real> v(dimM);
2787  v.SetRandn();
2788  SpMatrix<Real> T(dimM);
2789  T.SetRandn();
2790  Matrix<Real> M(T);
2791  Vector<Real> v2(dimM);
2792  Vector<Real> v3(dimM);
2793  v2.AddSpVec(alpha, T, v, beta);
2794  v3.AddMatVec(alpha, M, i%2 ? kNoTrans : kTrans, v, beta);
2795  AssertEqual(v2, v3);
2796  }
2797  }
2798 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestMulElements()

static void kaldi::UnitTestMulElements ( )
static

Definition at line 1822 of file matrix-lib-test.cc.

References MatrixBase< Real >::CopyFromMat(), rnnlm::i, rnnlm::j, KALDI_ASSERT, MatrixBase< Real >::MulElements(), and Rand().

1822  {
1823  for (MatrixIndexT iter = 0; iter < 5; iter++) {
1824  MatrixIndexT dimM = 20 + Rand()%10, dimN = 20 + Rand()%10;
1825  Matrix<Real> A(dimM, dimN), B(dimM, dimN), C(dimM, dimN);
1826  A.SetRandn();
1827  B.SetRandn();
1828 
1829  C.CopyFromMat(A);
1830  C.MulElements(B); // C = A .* B (in Matlab, for example).
1831 
1832  for (MatrixIndexT i = 0;i < dimM;i++)
1833  for (MatrixIndexT j = 0;j < dimN;j++)
1834  KALDI_ASSERT(std::abs(C(i, j) - (A(i, j)*B(i, j))) < 0.0001);
1835  }
1836 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestMulTp()

static void kaldi::UnitTestMulTp ( )
static

Definition at line 385 of file cu-test.cc.

References AssertEqual(), CuVectorBase< Real >::CopyToVec(), kNoTrans, kTrans, CuVectorBase< Real >::MulTp(), VectorBase< Real >::MulTp(), Rand(), VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

385  {
386  for (MatrixIndexT iter = 0; iter < 10; iter++) {
387  int32 dim = 1 + Rand() % 30;
388  Vector<Real> v(dim);
389  v.SetRandn();
390  TpMatrix<Real> M(dim);
391  M.SetRandn();
392  CuVector<Real> cv(v);
393  CuTpMatrix<Real> cM(M);
394 
395  Vector<Real> v2(dim);
396  cv.CopyToVec(&v2);
397  AssertEqual(v, v2);
398  v.MulTp(M, iter % 2 == 0 ? kTrans:kNoTrans);
399  cv.MulTp(cM, iter % 2 == 0 ? kTrans:kNoTrans);
400  cv.CopyToVec(&v2);
401  // KALDI_LOG << "v is " << v << ", v2 is " << v2;
402  AssertEqual(v, v2);
403  }
404 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestNativeFilename()

void kaldi::UnitTestNativeFilename ( )

Definition at line 309 of file kaldi-io-test.cc.

References KALDI_ASSERT, and MapCygwinPath().

Referenced by main().

309  {
310 #ifdef KALDI_CYGWIN_COMPAT
311  extern std::string MapCygwinPath(const std::string &filename);
312 
313  KALDI_ASSERT(MapCygwinPath("") == "");
314  KALDI_ASSERT(MapCygwinPath(".") == ".");
315  KALDI_ASSERT(MapCygwinPath("..") == "..");
316  KALDI_ASSERT(MapCygwinPath("/dev/null")[0] != '/');
317  KALDI_ASSERT(MapCygwinPath("/tmp")[1] == ':');
318  KALDI_ASSERT(MapCygwinPath("/tmp/")[1] == ':');
319  KALDI_ASSERT(MapCygwinPath("/tmp/foo")[1] == ':');
320  KALDI_ASSERT(MapCygwinPath("/cygdrive/c") == "c:/");
321  KALDI_ASSERT(MapCygwinPath("/cygdrive/c/") == "c:/");
322  KALDI_ASSERT(MapCygwinPath("/cygdrive/c/foo") == "c:/foo");
323 #endif
324 }
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
std::string MapCygwinPath(const std::string &filename)

◆ UnitTestNonsymmetricPower()

void kaldi::UnitTestNonsymmetricPower ( )

Definition at line 3754 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), AssertEqual(), InitRandNonsingular(), MatrixBase< Real >::Invert(), KALDI_ASSERT, KALDI_ERR, KALDI_LOG, kNoTrans, MatrixBase< Real >::Power(), Rand(), and MatrixBase< Real >::SetRandn().

3754  {
3755 
3756  for (MatrixIndexT iter = 0; iter < 30; iter++) {
3757  MatrixIndexT dimM = 1 + Rand() % 20;
3758  Matrix<Real> M(dimM, dimM);
3759  M.SetRandn();
3760 
3761  Matrix<Real> MM(dimM, dimM);
3762  MM.AddMatMat(1.0, M, kNoTrans, M, kNoTrans, 0.0); // MM = M M.
3763  Matrix<Real> MMMM(dimM, dimM);
3764  MMMM.AddMatMat(1.0, MM, kNoTrans, MM, kNoTrans, 0.0);
3765 
3766  Matrix<Real> MM2(MM);
3767  bool b = MM2.Power(1.0);
3768  KALDI_ASSERT(b);
3769  AssertEqual(MM2, MM);
3770  Matrix<Real> MMMM2(MM);
3771  b = MMMM2.Power(2.0);
3772  KALDI_ASSERT(b);
3773  AssertEqual(MMMM2, MMMM);
3774  }
3775  for (MatrixIndexT iter = 0; iter < 30; iter++) {
3776  MatrixIndexT dimM = 1 + Rand() % 20;
3777  Matrix<Real> M(dimM, dimM);
3778  InitRandNonsingular(&M);
3779 
3780  Matrix<Real> MM(dimM, dimM);
3781  MM.AddMatMat(1.0, M, kNoTrans, M, kNoTrans, 0.0); // MM = M M.
3782  // This ensures there are no real, negative eigenvalues.
3783 
3784  Matrix<Real> MMMM(dimM, dimM);
3785  MMMM.AddMatMat(1.0, MM, kNoTrans, MM, kNoTrans, 0.0);
3786 
3787  Matrix<Real> MM2(M);
3788  if (!MM2.Power(2.0)) { // possibly had negative eigenvalues
3789  KALDI_LOG << "Could not take matrix to power (not an error)";
3790  } else {
3791  AssertEqual(MM2, MM);
3792  }
3793  Matrix<Real> MMMM2(M);
3794  if (!MMMM2.Power(4.0)) { // possibly had negative eigenvalues
3795  KALDI_LOG << "Could not take matrix to power (not an error)";
3796  } else {
3797  AssertEqual(MMMM2, MMMM);
3798  }
3799  Matrix<Real> MMMM3(MM);
3800  if (!MMMM3.Power(2.0)) {
3801  KALDI_ERR << "Could not take matrix to power (should have been able to)";
3802  } else {
3803  AssertEqual(MMMM3, MMMM);
3804  }
3805 
3806  Matrix<Real> MM4(MM);
3807  if (!MM4.Power(-1.0))
3808  KALDI_ERR << "Could not take matrix to power (should have been able to)";
3809  MM4.Invert();
3810  AssertEqual(MM4, MM);
3811  }
3812 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
static void InitRandNonsingular(SpMatrix< Real > *M)
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestNorm()

static void kaldi::UnitTestNorm ( )
static

Definition at line 674 of file matrix-lib-test.cc.

References VectorBase< Real >::ApproxEqual(), ApproxEqual(), SpMatrix< Real >::ApproxEqual(), MatrixBase< Real >::ApproxEqual(), SpMatrix< Real >::FrobeniusNorm(), MatrixBase< Real >::FrobeniusNorm(), KALDI_ASSERT, VectorBase< Real >::Norm(), Rand(), RandGauss(), PackedMatrix< Real >::Scale(), MatrixBase< Real >::Scale(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

674  { // test some simple norm properties: scaling. also ApproxEqual test.
675 
676  for (MatrixIndexT p = 0; p < 10; p++) {
677  Real scalar = RandGauss();
678  if (scalar == 0.0) continue;
679  if (scalar < 0) scalar *= -1.0;
680  MatrixIndexT dimM = 10 + Rand() % 10, dimN = 10 + Rand() % 10;
681  Matrix<Real> M(dimM, dimN);
682  M.SetRandn();
683  SpMatrix<Real> S(dimM);
684  S.SetRandn();
685  Vector<Real> V(dimN);
686  V.SetRandn();
687 
688  Real Mnorm = M.FrobeniusNorm(),
689  Snorm = S.FrobeniusNorm(),
690  Vnorm1 = V.Norm(1.0),
691  Vnorm2 = V.Norm(2.0),
692  Vnorm3 = V.Norm(3.0);
693  M.Scale(scalar);
694  S.Scale(scalar);
695  V.Scale(scalar);
696  KALDI_ASSERT(ApproxEqual(M.FrobeniusNorm(), Mnorm*scalar));
697  KALDI_ASSERT(ApproxEqual(S.FrobeniusNorm(), Snorm*scalar));
698  KALDI_ASSERT(ApproxEqual(V.Norm(1.0), Vnorm1 * scalar));
699  KALDI_ASSERT(ApproxEqual(V.Norm(2.0), Vnorm2 * scalar));
700  KALDI_ASSERT(ApproxEqual(V.Norm(3.0), Vnorm3 * scalar));
701 
702  KALDI_ASSERT(V.ApproxEqual(V));
703  KALDI_ASSERT(M.ApproxEqual(M));
704  KALDI_ASSERT(S.ApproxEqual(S));
705  SpMatrix<Real> S2(S); S2.Scale(1.1); KALDI_ASSERT(!S.ApproxEqual(S2)); KALDI_ASSERT(S.ApproxEqual(S2, 0.15));
706  Matrix<Real> M2(M); M2.Scale(1.1); KALDI_ASSERT(!M.ApproxEqual(M2)); KALDI_ASSERT(M.ApproxEqual(M2, 0.15));
707  Vector<Real> V2(V); V2.Scale(1.1); KALDI_ASSERT(!V.ApproxEqual(V2)); KALDI_ASSERT(V.ApproxEqual(V2, 0.15));
708  }
709 }
Packed symetric matrix class.
Definition: matrix-common.h:62
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestOnlineCmvn()

void kaldi::UnitTestOnlineCmvn ( )

Definition at line 32 of file feature-functions-test.cc.

References SlidingWindowCmnOptions::center, SlidingWindowCmnOptions::cmn_window, rnnlm::d, rnnlm::i, KALDI_ERR, SlidingWindowCmnOptions::min_window, SlidingWindowCmnOptions::normalize_variance, Rand(), and SlidingWindowCmn().

Referenced by main().

32  {
33  for (int32 i = 0; i < 1000; i++) {
34  int32 num_frames = 1 + (Rand() % 10 * 10);
35  int32 dim = 1 + Rand() % 10;
37  opts.center = (Rand() % 2 == 0);
38  opts.normalize_variance = (Rand() % 2 == 0);
39  opts.cmn_window = 5 + Rand() % 50;
40  opts.min_window = 1 + Rand() % 100;
41  if (opts.min_window > opts.cmn_window)
42  opts.min_window = opts.cmn_window;
43 
44  Matrix<BaseFloat> feats(num_frames, dim),
45  output_feats(num_frames, dim),
46  output_feats2(num_frames, dim);
47  feats.SetRandn();
48  SlidingWindowCmn(opts, feats, &output_feats);
49 
50  for (int32 t = 0; t < num_frames; t++) {
51  int32 window_begin, window_end;
52  if (opts.center) {
53  window_begin = t - (opts.cmn_window / 2),
54  window_end = window_begin + opts.cmn_window;
55  int32 shift = 0;
56  if (window_begin < 0)
57  shift = -window_begin;
58  else if (window_end > num_frames)
59  shift = num_frames - window_end;
60  window_end += shift;
61  window_begin += shift;
62  } else {
63  window_begin = t - opts.cmn_window;
64  window_end = t + 1;
65  if (window_end < opts.min_window)
66  window_end = opts.min_window;
67  }
68  if (window_begin < 0) window_begin = 0;
69  if (window_end > num_frames) window_end = num_frames;
70  int32 window_size = window_end - window_begin;
71  for (int32 d = 0; d < dim; d++) {
72  double sum = 0.0, sumsq = 0.0;
73  for (int32 t2 = window_begin; t2 < window_end; t2++) {
74  sum += feats(t2, d);
75  sumsq += feats(t2, d) * feats(t2, d);
76  }
77  double mean = sum / window_size, uncentered_covar = sumsq / window_size,
78  covar = uncentered_covar - mean * mean;
79  covar = std::max(covar, 1.0e-20);
80  double data = feats(t, d),
81  norm_data = data - mean;
82  if (opts.normalize_variance) {
83  if (window_size == 1) norm_data = 0.0;
84  else norm_data /= sqrt(covar);
85  }
86  output_feats2(t, d) = norm_data;
87  }
88  }
89  if (! output_feats.ApproxEqual(output_feats2, 0.0001)) {
90  KALDI_ERR << "Features differ " << output_feats << " vs. " << output_feats2;
91  }
92  }
93 }
kaldi::int32 int32
#define KALDI_ERR
Definition: kaldi-error.h:147
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void SlidingWindowCmn(const SlidingWindowCmnOptions &opts, const MatrixBase< BaseFloat > &input, MatrixBase< BaseFloat > *output)
Applies sliding-window cepstral mean and/or variance normalization.

◆ UnitTestOrthogonalizeRows()

static void kaldi::UnitTestOrthogonalizeRows ( )
static

Definition at line 2052 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), rnnlm::i, MatrixBase< Real >::IsUnit(), KALDI_ASSERT, kNoTrans, kTrans, Rand(), and MatrixBase< Real >::SetRandn().

2052  {
2053  for (MatrixIndexT iter = 0; iter < 100; iter++) {
2054  MatrixIndexT dimM = 4 + Rand() % 5, dimN = dimM + (Rand() % 2);
2055  Matrix<Real> M(dimM, dimN);
2056  for (MatrixIndexT i = 0; i < dimM; i++) {
2057  if (Rand() % 5 != 0) M.Row(i).SetRandn();
2058  }
2059  if (Rand() % 2 != 0) { // Multiply by a random square matrix;
2060  // keeps it low rank but will be correlated. Harder
2061  // test case.
2062  Matrix<Real> N(dimM, dimM);
2063  N.SetRandn();
2064  Matrix<Real> tmp(dimM, dimN);
2065  tmp.AddMatMat(1.0, N, kNoTrans, M, kNoTrans, 0.0);
2066  M.CopyFromMat(tmp);
2067  }
2068  M.OrthogonalizeRows();
2069  Matrix<Real> I(dimM, dimM);
2070  I.AddMatMat(1.0, M, kNoTrans, M, kTrans, 0.0);
2071  KALDI_ASSERT(I.IsUnit(1.0e-05));
2072  }
2073 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestParseOptions()

void kaldi::UnitTestParseOptions ( )

Definition at line 46 of file parse-options-test.cc.

References ParseOptions::GetArg(), KALDI_ASSERT, KALDI_LOG, DummyOptions::my_bool, DummyOptions::my_string, ParseOptions::NumArgs(), ParseOptions::PrintUsage(), ParseOptions::Read(), DummyOptions::Register(), and ParseOptions::Register().

Referenced by main().

46  {
47  int argc = 7;
48  std::string str="default_for_str";
49  int32 num = 1;
50  uint32 unum = 2;
51  const char *argv[7] = { "program_name", "--unum=5", "--num=3", "--i=boo",
52  "a", "b", "c" };
53  ParseOptions po("my usage msg");
54  po.Register("i", &str, "My variable");
55  po.Register("num", &num, "My int32 variable");
56  po.Register("unum", &unum, "My uint32 variable");
57  po.Read(argc, argv);
58  KALDI_ASSERT(po.NumArgs() == 3);
59  KALDI_ASSERT(po.GetArg(1) == "a");
60  KALDI_ASSERT(po.GetArg(2) == "b");
61  KALDI_ASSERT(po.GetArg(3) == "c");
62  KALDI_ASSERT(unum == 5);
63  KALDI_ASSERT(num == 3);
64  KALDI_ASSERT(str == "boo");
65 
66  ParseOptions po2("my another msg");
67  int argc2 = 4;
68  const char *argv2[4] = { "program_name", "--i=foo",
69  "--to-be-NORMALIZED=test", "c" };
70  std::string str2 = "default_for_str2";
71  po2.Register("To_Be_Normalized", &str2,
72  "My variable (name has to be normalized)");
73  po2.Register("i", &str, "My variable");
74  po2.Read(argc2, argv2);
75  KALDI_ASSERT(po2.NumArgs() == 1);
76  KALDI_ASSERT(po2.GetArg(1) == "c");
77  KALDI_ASSERT(str2 == "test");
78  KALDI_ASSERT(str == "foo");
79 
80  ParseOptions po3("now checking options with prefix");
81  ParseOptions ro3("prefix", &po3); // to register with prefix
82  ParseOptions so3("prefix2", &ro3); // to register with prefix, recursively.
83  DummyOptions dummy_opts;
84  po3.Register("str", &str, "My string variable");
85  po3.Register("num", &num, "My int32 variable");
86  // Now register with prefix
87  ro3.Register("unum", &unum, "My uint32 variable");
88  ro3.Register("str", &str2, "My other string variable");
89  uint32 unum2 = 0;
90  so3.Register("unum", &unum2, "Another uint32 variable");
91 
92  int argc3 = 10;
93  const char *argv3[10] = {
94  "program_name", "--prefix.unum=5", "--num=3",
95  "--prefix.str=foo", "--str=bar", "--prefix.my-bool=false",
96  "--prefix.my-str=baz", "--prefix.prefix2.unum=42", "a", "b" };
97 
98  dummy_opts.Register(&ro3);
99  po3.PrintUsage(false);
100 
101  po3.Read(argc3, argv3);
102  KALDI_ASSERT(po3.NumArgs() == 2);
103  KALDI_ASSERT(po3.GetArg(1) == "a");
104  KALDI_ASSERT(po3.GetArg(2) == "b");
105  KALDI_ASSERT(unum == 5);
106  KALDI_ASSERT(unum2 == 42);
107  KALDI_ASSERT(num == 3);
108  KALDI_ASSERT(str2 == "foo");
109  KALDI_ASSERT(str == "bar");
110  KALDI_ASSERT(dummy_opts.my_bool == false);
111  KALDI_ASSERT(dummy_opts.my_string == "baz");
112 
113 
114  try { // test error with --option=, which is not a valid way to set
115  // boolean options.
116  int argc4 = 2;
117  const char *argv4[2] = { "program_name", "--option="};
118  ParseOptions po4("my usage msg");
119  bool val = false;
120  po4.Register("option", &val, "My boolean");
121  po4.Read(argc4, argv4);
122  assert(false); // Should not reach this part of code.
123  } catch(std::exception e) {
124  KALDI_LOG << "Failed to read option (this is expected).";
125  }
126 
127  { // test that --option sets "option" to true, if bool.
128  int argc4 = 2;
129  const char *argv4[2] = { "program_name", "--option"};
130  ParseOptions po4("my usage msg");
131  bool val = false;
132  po4.Register("option", &val, "My boolean");
133  po4.Read(argc4, argv4);
134  KALDI_ASSERT(val == true);
135  }
136 
137 
138  try { // test error with --option, which is not a valid way to set
139  // string-valued options.
140  int argc4 = 2;
141  const char *argv4[2] = { "program_name", "--option"};
142  ParseOptions po4("my usage msg");
143  std::string val;
144  po4.Register("option", &val, "My string");
145  po4.Read(argc4, argv4);
146  assert(false); // Should not reach this part of code.
147  } catch(std::exception e) {
148  KALDI_LOG << "Failed to read option (this is expected).";
149  }
150 
151  { // test that --option= sets "option" to empty, if string.
152  int argc4 = 2;
153  const char *argv4[2] = { "program_name", "--option="};
154  ParseOptions po4("my usage msg");
155  std::string val = "foo";
156  po4.Register("option", &val, "My boolean");
157  po4.Read(argc4, argv4);
158  KALDI_ASSERT(val.empty());
159  }
160 
161  { // integer options test
162  int argc4 = 2;
163  const char *argv4[2] = { "program_name", "--option=8"};
164  ParseOptions po4("my usage msg");
165  int32 val = 32;
166  po4.Register("option", &val, "My int");
167  po4.Read(argc4, argv4);
168  KALDI_ASSERT(val == 8);
169  }
170 
171  { // float
172  int argc4 = 2;
173  const char *argv4[2] = { "program_name", "--option=8.5"};
174  ParseOptions po4("my usage msg");
175  BaseFloat val = 32.0;
176  po4.Register("option", &val, "My float");
177  po4.Read(argc4, argv4);
178  KALDI_ASSERT(val == 8.5);
179  }
180  { // string options test
181  int argc4 = 2;
182  const char *argv4[2] = { "program_name", "--option=bar"};
183  ParseOptions po4("my usage msg");
184  std::string val = "foo";
185  po4.Register("option", &val, "My string");
186  po4.Read(argc4, argv4);
187  KALDI_ASSERT(val == "bar");
188  }
189 
190  try { // test error with --float=string
191  int argc4 = 2;
192  const char *argv4[2] = { "program_name", "--option=foo"};
193  ParseOptions po4("my usage msg");
194  BaseFloat val = 32.0;
195  po4.Register("option", &val, "My float");
196  po4.Read(argc4, argv4);
197  assert(false); // Should not reach this part of code.
198  } catch(std::exception e) {
199  KALDI_LOG << "Failed to read option (this is expected).";
200  }
201 
202 
203  try { // test error with --int=string
204  int argc4 = 2;
205  const char *argv4[2] = { "program_name", "--option=foo"};
206  ParseOptions po4("my usage msg");
207  int32 val = 32;
208  po4.Register("option", &val, "My int");
209  po4.Read(argc4, argv4);
210  assert(false); // Should not reach this part of code.
211  } catch(std::exception e) {
212  KALDI_LOG << "Failed to read option (this is expected).";
213  }
214 
215  try { // test error with --int=int+garbage
216  int argc4 = 2;
217  const char *argv4[2] = { "program_name", "--option=12xyz"};
218  ParseOptions po4("my usage msg");
219  int32 val = 32;
220  po4.Register("option", &val, "My int");
221  po4.Read(argc4, argv4);
222  assert(false); // Should not reach this part of code.
223  } catch(std::exception e) {
224  KALDI_LOG << "Failed to read option (this is expected).";
225  }
226 
227  try { // test error with --unsigned-int=negative-number.
228  int argc4 = 2;
229  const char *argv4[2] = { "program_name", "--option=-13"};
230  ParseOptions po4("my usage msg");
231  uint32 val = 32;
232  po4.Register("option", &val, "My int");
233  po4.Read(argc4, argv4);
234  assert(false); // Should not reach this part of code.
235  } catch(std::exception e) {
236  KALDI_LOG << "Failed to read option (this is expected)xxx.";
237  }
238 
239  try { // test error with --bool=string
240  int argc4 = 2;
241  const char *argv4[2] = { "program_name", "--option=foo"};
242  ParseOptions po4("my usage msg");
243  bool val = false;
244  po4.Register("option", &val, "My bool");
245  po4.Read(argc4, argv4);
246  assert(false); // Should not reach this part of code.
247  } catch(std::exception e) {
248  KALDI_LOG << "Failed to read option (this is expected).";
249  }
250 
251 
252  // test error with --=
253  try {
254  int argc4 = 2;
255  const char *argv4[2] = { "program_name", "--=8"};
256  int32 num = 0;
257  ParseOptions po4("my usage msg");
258  po4.Register("num", &num, "My int32 variable");
259  po4.Read(argc4, argv4);
260  KALDI_ASSERT(num == 0);
261  } catch(std::exception e) {
262  KALDI_LOG << "Failed to read option (this is expected).";
263  }
264 
265  // test "--" (no more options)
266  int argc4 = 5;
267  unum = 2;
268  const char *argv4[5] = { "program_name", "--unum=6", "--", "a", "b" };
269  ParseOptions po4("my usage msg");
270  po4.Register("unum", &unum, "My uint32 variable");
271  po4.Read(argc4, argv4);
272  KALDI_ASSERT(po4.NumArgs() == 2);
273  KALDI_ASSERT(po4.GetArg(1) == "a");
274  KALDI_ASSERT(po4.GetArg(2) == "b");
275  KALDI_ASSERT(unum == 6);
276 
277  // test obsolete "--" (no more options)
278  int argc5 = 3;
279  unum = 2;
280  const char *argv5[3] = { "program_name", "--unum=7", "--" };
281  ParseOptions po5("my usage msg");
282  po5.Register("unum", &unum, "My uint32 variable");
283  po5.Read(argc5, argv5);
284  KALDI_ASSERT(po5.NumArgs() == 0);
285  KALDI_ASSERT(unum == 7);
286 
287  // test that "--foo=bar" after "--" is interpreted as argument
288  int argc6 = 4;
289  unum = 2;
290  const char *argv6[5] = { "program_name", "--unum=8", "--", "--foo=8" };
291  ParseOptions po6("my usage msg");
292  po6.Register("unum", &unum, "My uint32 variable");
293  po6.Read(argc6, argv6);
294  KALDI_ASSERT(po6.NumArgs() == 1);
295  KALDI_ASSERT(po6.GetArg(1) == "--foo=8");
296 }
kaldi::int32 int32
float BaseFloat
Definition: kaldi-types.h:29
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void Register(ParseOptions *po)
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestPca()

static void kaldi::UnitTestPca ( bool  full_test)
static

Definition at line 3854 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::AddMatMat(), AssertEqual(), ComputePca(), rnnlm::i, SpMatrix< Real >::IsUnit(), MatrixBase< Real >::IsUnit(), KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, NonUnitness(), Rand(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::Sum().

3854  {
3855  // We'll test that we can exactly reconstruct the vectors, if
3856  // the PCA dim is <= the "real" dim that the vectors live in.
3857  for (MatrixIndexT i = 0; i < 10; i++) {
3858  bool exact = i % 2 == 0;
3859  MatrixIndexT true_dim = (full_test ? 200 : 50) + Rand() % 5, //dim of subspace points live in
3860  feat_dim = true_dim + Rand() % 5, // dim of feature space
3861  num_points = true_dim + Rand() % 5, // number of training points.
3862  G = std::min(feat_dim,
3863  std::min(num_points,
3864  static_cast<MatrixIndexT>(true_dim + Rand() % 5)));
3865 
3866  Matrix<Real> Proj(feat_dim, true_dim);
3867  Proj.SetRandn();
3868  Matrix<Real> true_X(num_points, true_dim);
3869  true_X.SetRandn();
3870  Matrix<Real> X(num_points, feat_dim);
3871  X.AddMatMat(1.0, true_X, kNoTrans, Proj, kTrans, 0.0);
3872 
3873  Matrix<Real> U(G, feat_dim); // the basis
3874  Matrix<Real> A(num_points, G); // projection of points into the basis..
3875  ComputePca(X, &U, &A, true, exact);
3876  {
3877  SpMatrix<Real> I(G);
3878  I.AddMat2(1.0, U, kNoTrans, 0.0);
3879  KALDI_LOG << "Non-unit-ness of U is " << NonUnitness(I);
3880  KALDI_ASSERT(I.IsUnit(0.001));
3881  }
3882  Matrix<Real> X2(num_points, feat_dim);
3883  X2.AddMatMat(1.0, A, kNoTrans, U, kNoTrans, 0.0);
3884  // Check reproduction.
3885  KALDI_LOG << "A.Sum() " << A.Sum() << ", U.Sum() " << U.Sum();
3886  AssertEqual(X, X2, 0.01);
3887  // Check basis is orthogonal.
3888  Matrix<Real> tmp(G, G);
3889  tmp.AddMatMat(1.0, U, kNoTrans, U, kTrans, 0.0);
3890  KALDI_ASSERT(tmp.IsUnit(0.01));
3891  }
3892 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
void ComputePca(const MatrixBase< Real > &X, MatrixBase< Real > *U, MatrixBase< Real > *A, bool print_eigs, bool exact)
ComputePCA does a PCA computation, using either outer products or inner products, whichever is more e...
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static Real NonUnitness(const SpMatrix< Real > &S)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestPca2()

static void kaldi::UnitTestPca2 ( bool  full_test)
static

Definition at line 3901 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), SpMatrix< Real >::AddMat2Sp(), AssertEqual(), ComputePca(), MatrixBase< Real >::CopyFromMat(), SpMatrix< Real >::Eig(), rnnlm::i, SpMatrix< Real >::IsDiagonal(), KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, NonDiagonalness(), NonOrthogonality(), MatrixBase< Real >::SetRandn(), SortSvd(), and SpMatrix< Real >::Trace().

3901  {
3902  for (MatrixIndexT i = 0; i < 5; i++) {
3903  // MatrixIndexT feat_dim = 600, num_points = 300;
3904  MatrixIndexT feat_dim = (full_test ? 600 : 100),
3905  num_points = (i%2 == 0 ? feat_dim * 2 : feat_dim / 2); // test
3906  // both branches of PCA code, inner + outer.
3907 
3908  Matrix<Real> X(num_points, feat_dim);
3909  X.SetRandn();
3910 
3911  MatrixIndexT pca_dim = 30;
3912 
3913  Matrix<Real> U(pca_dim, feat_dim); // rows PCA directions.
3914  bool print_eigs = true, exact = false;
3915  ComputePca(X, &U, static_cast<Matrix<Real>*>(NULL), print_eigs, exact);
3916 
3917  Real non_orth = NonOrthogonality(U, kNoTrans);
3918  KALDI_ASSERT(non_orth < 0.001);
3919  KALDI_LOG << "Non-orthogonality of U is " << non_orth;
3920  Matrix<Real> U2(pca_dim, feat_dim);
3921 
3922  {
3923  SpMatrix<Real> Scatter(feat_dim);
3924  Scatter.AddMat2(1.0, X, kTrans, 0.0);
3925  Matrix<Real> V(feat_dim, feat_dim);
3926  Vector<Real> l(feat_dim);
3927  Scatter.Eig(&l, &V); // cols of V are eigenvectors.
3928  SortSvd(&l, &V); // Get top dims.
3929  U2.CopyFromMat(SubMatrix<Real>(V, 0, feat_dim, 0, pca_dim), kTrans);
3930  Real non_orth = NonOrthogonality(U2, kNoTrans);
3931  KALDI_ASSERT(non_orth < 0.001);
3932  KALDI_LOG << "Non-orthogonality of U2 is " << non_orth;
3933 
3934  SpMatrix<Real> ScatterProjU(pca_dim), ScatterProjU2(pca_dim);
3935  ScatterProjU.AddMat2Sp(1.0, U, kNoTrans, Scatter, 0.0);
3936  ScatterProjU2.AddMat2Sp(1.0, U2, kNoTrans, Scatter, 0.0);
3937  KALDI_LOG << "Non-diagonality of proj with U is "
3938  << NonDiagonalness(ScatterProjU);
3939  KALDI_LOG << "Non-diagonality of proj with U2 is "
3940  << NonDiagonalness(ScatterProjU2);
3941  KALDI_ASSERT(ScatterProjU.IsDiagonal(0.01)); // Algorithm is statistical,
3942  // so it ends up being less accurate.
3943  KALDI_ASSERT(ScatterProjU2.IsDiagonal());
3944  KALDI_LOG << "Trace proj with U is " << ScatterProjU.Trace()
3945  << " with U2 is " << ScatterProjU2.Trace();
3946  AssertEqual(ScatterProjU.Trace(), ScatterProjU2.Trace(), 0.1);// Algorithm is
3947  // statistical so give it some leeway.
3948  }
3949  }
3950 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
void ComputePca(const MatrixBase< Real > &X, MatrixBase< Real > *U, MatrixBase< Real > *A, bool print_eigs, bool exact)
ComputePCA does a PCA computation, using either outer products or inner products, whichever is more e...
static Real NonOrthogonality(const MatrixBase< Real > &M, MatrixTransposeType transM)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
Sub-matrix representation.
Definition: kaldi-matrix.h:988
static Real NonDiagonalness(const SpMatrix< Real > &S)
void SortSvd(VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt, bool sort_on_absolute_value)
Function to ensure that SVD is sorted.

◆ UnitTestPenaltyFactor()

static void kaldi::UnitTestPenaltyFactor ( )
static

Definition at line 397 of file pitch-functions-test.cc.

References ComputeKaldiPitch(), ConvertIntToString(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, PitchExtractionOptions::penalty_factor, WaveData::Read(), and MatrixBase< Real >::Write().

Referenced by UnitTestFeatWithKeele().

397  {
398  KALDI_LOG << "=== UnitTestPenaltyFactor() ===";
399  for (int32 k = 1; k < 5; k++) {
400  for (int32 i = 1; i < 4; i++) {
401  std::string wavefile;
402  std::string num;
403  if (i < 6) {
404  num = "f"+ConvertIntToString(i)+"nw0000";
405  wavefile = "keele/16kHz/"+num+".wav";
406  } else {
407  num = "m"+ConvertIntToString(i-5)+"nw0000";
408  wavefile = "keele/16kHz/"+num+".wav";
409  }
410  KALDI_LOG << "--- " << wavefile << " ---";
411  std::ifstream is(wavefile.c_str(), std::ios_base::binary);
412  WaveData wave;
413  wave.Read(is);
414  KALDI_ASSERT(wave.Data().NumRows() == 1);
415  SubVector<BaseFloat> waveform(wave.Data(), 0);
416  // use pitch code with default configuration..
418  op.penalty_factor = k * 0.05;
419  op.nccf_ballast = 0.1;
420  // compute pitch.
422  ComputeKaldiPitch(op, waveform, &m);
423  std::string penaltyfactor = ConvertIntToString(k);
424  std::string outfile = "keele/tmp/+"+num+"-kaldi-penalty-"+penaltyfactor+".txt";
425  std::ofstream os(outfile.c_str());
426  m.Write(os, false);
427  }
428  }
429 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
void Write(std::ostream &out, bool binary) const
write to stream.
std::string ConvertIntToString(const int &number)
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
kaldi::int32 int32
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestPieces()

static void kaldi::UnitTestPieces ( )
static

Definition at line 154 of file pitch-functions-test.cc.

References OnlinePitchFeature::AcceptWaveform(), ApproxEqual(), AssertEqual(), ComputeKaldiPitch(), ProcessPitchOptions::delta_pitch_noise_stddev, VectorBase< Real >::Dim(), OnlineProcessPitch::Dim(), OnlinePitchFeature::GetFrame(), OnlineProcessPitch::GetFrame(), rnnlm::i, OnlinePitchFeature::InputFinished(), KALDI_ERR, KALDI_LOG, M_2PI, rnnlm::n, PitchExtractionOptions::nccf_ballast_online, OnlinePitchFeature::NumFramesReady(), ProcessPitch(), RandGauss(), Matrix< Real >::Resize(), and PitchExtractionOptions::samp_freq.

Referenced by UnitTestFeatNoKeele().

154  {
155  KALDI_LOG << "=== UnitTestPieces() ===\n";
156  for (int32 n = 0; n < 10; n++) {
157  // the parametrization object
160  op2.delta_pitch_noise_stddev = 0.0; // to avoid mismatch of delta_log_pitch
161  // brought by rand noise.
162  op1.nccf_ballast_online = true; // this is necessary for the computation
163  // to be identical regardless how many pieces we break the signal into.
164 
165  int32 size = 10000 + rand() % 50000;
166 
167  Vector<BaseFloat> v(size);
168  // init with noise plus a sine-wave whose frequency is changing randomly.
169 
170  double cur_freq = 200.0, normalized_time = 0.0;
171 
172  for (int32 i = 0; i < size; i++) {
173  v(i) = RandGauss() + cos(normalized_time * M_2PI);
174  cur_freq += RandGauss(); // let the frequency wander a little.
175  if (cur_freq < 100.0) cur_freq = 100.0;
176  if (cur_freq > 300.0) cur_freq = 300.0;
177  normalized_time += cur_freq / op1.samp_freq;
178  }
179 
180  Matrix<BaseFloat> m1, m1p;
181 
182  // trying to have same opts as baseline.
183  ComputeKaldiPitch(op1, v, &m1);
184  ProcessPitch(op2, m1, &m1p);
185 
186  Matrix<BaseFloat> m2, m2p;
187 
188  { // compute it online with multiple pieces.
189  OnlinePitchFeature pitch_extractor(op1);
190  OnlineProcessPitch process_pitch(op2, &pitch_extractor);
191  int32 start_samp = 0;
192  while (start_samp < v.Dim()) {
193  int32 num_samp = rand() % (v.Dim() + 1 - start_samp);
194  SubVector<BaseFloat> v_part(v, start_samp, num_samp);
195  pitch_extractor.AcceptWaveform(op1.samp_freq, v_part);
196  start_samp += num_samp;
197  }
198  pitch_extractor.InputFinished();
199  int32 num_frames = pitch_extractor.NumFramesReady();
200  m2.Resize(num_frames, 2);
201  m2p.Resize(num_frames, process_pitch.Dim());
202  for (int32 frame = 0; frame < num_frames; frame++) {
203  SubVector<BaseFloat> row(m2, frame);
204  pitch_extractor.GetFrame(frame, &row);
205  SubVector<BaseFloat> rowp(m2p, frame);
206  process_pitch.GetFrame(frame, &rowp);
207  }
208  }
209  AssertEqual(m1, m2);
210  if (!ApproxEqual(m1p, m2p)) {
211  KALDI_ERR << "Post-processed pitch differs: " << m1p << " vs. " << m2p;
212  }
213  KALDI_LOG << "Test passed :)\n";
214  }
215 }
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
This online-feature class implements post processing of pitch features.
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
struct rnnlm::@11::@12 n
#define KALDI_ERR
Definition: kaldi-error.h:147
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define M_2PI
Definition: kaldi-math.h:52
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
void ProcessPitch(const ProcessPitchOptions &opts, const MatrixBase< BaseFloat > &input, Matrix< BaseFloat > *output)
This function processes the raw (NCCF, pitch) quantities computed by ComputeKaldiPitch, and processes them into features.
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestPitchExtractionSpeed()

static void kaldi::UnitTestPitchExtractionSpeed ( )
static

Definition at line 465 of file pitch-functions-test.cc.

References ComputeKaldiPitch(), ConvertIntToString(), Timer::Elapsed(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, PitchExtractionOptions::lowpass_cutoff, PitchExtractionOptions::nccf_ballast, and WaveData::Read().

Referenced by UnitTestFeatWithKeele().

465  {
466  KALDI_LOG << "=== UnitTestPitchExtractionSpeed() ===";
467  // use pitch code with default configuration..
469  op.nccf_ballast = 0.1;
470  op.lowpass_cutoff = 1000;
471  for (int32 i = 1; i < 2; i++) {
472  std::string wavefile;
473  std::string num;
474  if (i < 6) {
475  num = "f"+ConvertIntToString(i)+"nw0000";
476  wavefile = "keele/16kHz/"+num+".wav";
477  } else {
478  num = "m"+ConvertIntToString(i-5)+"nw0000";
479  wavefile = "keele/16kHz/"+num+".wav";
480  }
481  KALDI_LOG << "--- " << wavefile << " ---";
482  std::ifstream is(wavefile.c_str(), std::ios_base::binary);
483  WaveData wave;
484  wave.Read(is);
485  KALDI_ASSERT(wave.Data().NumRows() == 1);
486  SubVector<BaseFloat> waveform(wave.Data(), 0);
487  // compute pitch.
488  int test_num = 10;
490  Timer timer;
491  for (int32 t = 0; t < test_num; t++)
492  ComputeKaldiPitch(op, waveform, &m);
493  double tot_time = timer.Elapsed(),
494  speech_time = test_num * waveform.Dim() / wave.SampFreq();
495  KALDI_LOG << " Pitch extraction time per second of speech is "
496  << (tot_time / speech_time) << " seconds.";
497  }
498 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
std::string ConvertIntToString(const int &number)
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
kaldi::int32 int32
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestPitchExtractorCompareKeele()

static void kaldi::UnitTestPitchExtractorCompareKeele ( )
static

Definition at line 499 of file pitch-functions-test.cc.

References ComputeKaldiPitch(), ConvertIntToString(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, PitchExtractionOptions::nccf_ballast, and WaveData::Read().

Referenced by UnitTestFeatWithKeele().

499  {
500  KALDI_LOG << "=== UnitTestPitchExtractorCompareKeele() ===";
501  // use pitch code with default configuration..
503  op.nccf_ballast = 0.1;
504  for (int32 i = 1; i < 11; i++) {
505  std::string wavefile;
506  std::string num;
507  if (i < 6) {
508  num = "f"+ConvertIntToString(i)+"nw0000";
509  wavefile = "keele/16kHz/"+num+".wav";
510  } else {
511  num = "m"+ConvertIntToString(i-5)+"nw0000";
512  wavefile = "keele/16kHz/"+num+".wav";
513  }
514  KALDI_LOG << "--- " << wavefile << " ---";
515  std::ifstream is(wavefile.c_str(), std::ios_base::binary);
516  WaveData wave;
517  wave.Read(is);
518  KALDI_ASSERT(wave.Data().NumRows() == 1);
519  SubVector<BaseFloat> waveform(wave.Data(), 0);
520  // compute pitch.
522  ComputeKaldiPitch(op, waveform, &m);
523  std::string outfile = "keele/tmp/+"+num+"-speedup-kaldi1.txt";
524  std::ofstream os(outfile.c_str());
525  m.Write(os, false);
526  }
527 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
std::string ConvertIntToString(const int &number)
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
kaldi::int32 int32
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestPldaEstimation()

void kaldi::UnitTestPldaEstimation ( int32  dim)

Definition at line 25 of file plda-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::AddMatMat(), VectorBase< Real >::AddMatVec(), PldaStats::AddSamples(), SpMatrix< Real >::AddTp2Sp(), MatrixBase< Real >::AddVecToRows(), TpMatrix< Real >::Cholesky(), MatrixBase< Real >::Cond(), VectorBase< Real >::Data(), VectorBase< Real >::Dim(), SpMatrix< Real >::Eig(), PldaEstimator::Estimate(), TpMatrix< Real >::Invert(), KALDI_LOG, kNoTrans, kTrans, rnnlm::n, Rand(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), PldaStats::Sort(), and SpMatrix< Real >::Trace().

Referenced by main().

25  {
26  int32 num_classes = 1000 + Rand() % 10;
27  Matrix<double> between_proj(dim, dim);
28  while (between_proj.Cond() > 100)
29  between_proj.SetRandn();
30  Matrix<double> within_proj(dim, dim);
31  while (within_proj.Cond() > 100)
32  within_proj.SetRandn();
33 
34 
35  Vector<double> global_mean(dim);
36  global_mean.SetRandn();
37  global_mean.Scale(10.0);
38 
39  PldaStats stats;
40 
41  for (int32 n = 0; n < num_classes; n++) {
42  int32 num_egs = 1 + Rand() % 30;
43  Vector<double> rand_vec(dim);
44  rand_vec.SetRandn();
45  Vector<double> class_mean(global_mean);
46  class_mean.AddMatVec(1.0, between_proj, kNoTrans, rand_vec, 1.0);
47 
48  Matrix<double> rand_mat(num_egs, dim);
49  rand_mat.SetRandn();
50  Matrix<double> offset_mat(num_egs, dim);
51  offset_mat.AddMatMat(1.0, rand_mat, kNoTrans, within_proj,
52  kTrans, 0.0);
53  offset_mat.AddVecToRows(1.0, class_mean);
54 
55  double weight = 1.0 + (0.1 * (Rand() % 30));
56  stats.AddSamples(weight,
57  offset_mat);
58  }
59 
60 
61 
62  SpMatrix<double> between_var(dim), within_var(dim);
63  between_var.AddMat2(1.0, between_proj, kNoTrans, 0.0);
64  within_var.AddMat2(1.0, within_proj, kNoTrans, 0.0);
65 
66  stats.Sort();
67  PldaEstimator estimator(stats);
68  Plda plda;
69  PldaEstimationConfig config;
70  estimator.Estimate(config, &plda);
71 
72  KALDI_LOG << "Trace of true within-var is " << within_var.Trace();
73  KALDI_LOG << "Trace of true between-var is " << between_var.Trace();
74 
75  {
76  TpMatrix<double> C(dim);
77  C.Cholesky(within_var);
78  C.Invert();
79  SpMatrix<double> between_var_proj(dim);
80  between_var_proj.AddTp2Sp(1.0, C, kNoTrans, between_var, 0.0);
81  Vector<double> s(dim);
82  between_var_proj.Eig(&s);
83  s.Scale(-1.0);
84  std::sort(s.Data(), s.Data() + s.Dim());
85  s.Scale(-1.0);
86  KALDI_LOG << "Diagonal of between-class variance in normalized space "
87  << "should be: " << s;
88  }
89 
90 }
kaldi::int32 int32
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
void AddSamples(double weight, const Matrix< double > &group)
The dimension is set up the first time you add samples.
Definition: plda.cc:286
#define KALDI_LOG
Definition: kaldi-error.h:153
void Sort()
Definition: plda.h:188

◆ UnitTestPosteriors()

void kaldi::UnitTestPosteriors ( )

Definition at line 25 of file logistic-regression-test.cc.

References VectorBase< Real >::ApplyExp(), ApproxEqual(), MatrixBase< Real >::ApproxEqual(), VectorBase< Real >::CopyRowFromMat(), LogisticRegression::GetLogPosteriors(), rnnlm::i, KALDI_ASSERT, LogisticRegressionConfig::max_steps, LogisticRegressionConfig::normalizer, MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::Row(), MatrixBase< Real >::SetRandn(), LogisticRegression::SetWeights(), and VectorBase< Real >::Sum().

Referenced by main().

25  {
26  int32 n_features = Rand() % 600 + 10,
27  n_xs = Rand() % 200 + 100,
28  n_labels = Rand() % 20 + 10;
29 
31  conf.max_steps = 20;
32  conf.normalizer = 0.001;
33 
34  Matrix<BaseFloat> xs(n_xs, n_features);
35  xs.SetRandn();
36  Matrix<BaseFloat> weights(n_labels, n_features + 1);
37  weights.SetRandn();
39  std::vector<int32> classes;
40  for (int32 i = 0; i < weights.NumRows(); i++) {
41  classes.push_back(i);
42  }
43  classifier.SetWeights(weights, classes);
44 
45  // Get posteriors for the xs using batch and serial methods.
46  Matrix<BaseFloat> batch_log_posteriors;
47  classifier.GetLogPosteriors(xs, &batch_log_posteriors);
48  Matrix<BaseFloat> log_posteriors(n_xs, n_labels);
49  for (int32 i = 0; i < n_xs; i++) {
50  Vector<BaseFloat> x(n_features);
51  x.CopyRowFromMat(xs, i);
52  Vector<BaseFloat> log_post;
53  classifier.GetLogPosteriors(x, &log_post);
54 
55  // Verify that sum_y p(y|x) = 1.0.
56  Vector<BaseFloat> post(log_post);
57  post.ApplyExp();
58  KALDI_ASSERT(ApproxEqual(post.Sum(), 1.0));
59  log_posteriors.Row(i).CopyFromVec(log_post);
60  }
61 
62  // Verify equivalence of batch and serial methods.
63  float tolerance = 0.01;
64  KALDI_ASSERT(log_posteriors.ApproxEqual(batch_log_posteriors, tolerance));
65 }
kaldi::int32 int32
void GetLogPosteriors(const Matrix< BaseFloat > &xs, Matrix< BaseFloat > *log_posteriors)
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
void SetWeights(const Matrix< BaseFloat > &weights, const std::vector< int32 > classes)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestPower()

static void kaldi::UnitTestPower ( )
static

Definition at line 1074 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), SpMatrix< Real >::ApplyPow(), VectorBase< Real >::ApplyPow(), AssertEqual(), SpMatrix< Real >::CopyFromMat(), VectorBase< Real >::CopyFromVec(), kNoTrans, kTrans, and Rand().

1074  {
1075  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1076  // this is for matrix-pow
1077  MatrixIndexT dimM = 10 + Rand() % 10;
1078  Matrix<Real> M(dimM, dimM), N(dimM, dimM);
1079  M.SetRandn();
1080  N.AddMatMat(1.0, M, kNoTrans, M, kTrans, 0.0); // N:=M*M^T.
1081  SpMatrix<Real> S(dimM);
1082  S.CopyFromMat(N); // symmetric so should not crash.
1083  S.ApplyPow(0.5);
1084  S.ApplyPow(2.0);
1085  M.CopyFromSp(S);
1086  AssertEqual(M, N);
1087 
1088  // this is for vector-pow
1089  MatrixIndexT dimV = 10 + Rand() % 10;
1090  Vector<Real> V(dimV), V1(dimV), V2(dimV);
1091  V.SetRandn();
1092  V1.AddVecVec(1.0, V, V, 0.0); // V1:=V.*V.
1093  V2.CopyFromVec(V1);
1094  V2.ApplyPow(0.5);
1095  V2.ApplyPow(2.0);
1096  AssertEqual(V1, V2);
1097  }
1098 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestPowerAbs()

static void kaldi::UnitTestPowerAbs ( )
static

Definition at line 1100 of file matrix-lib-test.cc.

References VectorBase< Real >::ApplyPowAbs(), AssertEqual(), VectorBase< Real >::CopyFromVec(), KALDI_LOG, and Rand().

1100  {
1101  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1102  MatrixIndexT dimV = 10 + Rand() % 10;
1103  Vector<Real> V(dimV), V1(dimV), V2(dimV);
1104  V.SetRandn();
1105  V1.AddVecVec(1.0, V, V, 0.0); // V1:=V.*V.
1106  V2.CopyFromVec(V1);
1107  KALDI_LOG << V1;
1108  V2.ApplyPowAbs(0.5);
1109  KALDI_LOG << V2;
1110  V2.ApplyPowAbs(2.0);
1111  KALDI_LOG << V2;
1112  AssertEqual(V1, V2);
1113  }
1114 }
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestProcess()

void kaldi::UnitTestProcess ( )

Definition at line 561 of file pitch-functions-test.cc.

References ComputeKaldiPitch(), ConvertIntToString(), ProcessPitchOptions::delta_pitch_noise_stddev, rnnlm::i, KALDI_ASSERT, KALDI_LOG, PitchExtractionOptions::lowpass_cutoff, ProcessPitch(), WaveData::Read(), and MatrixBase< Real >::Write().

Referenced by UnitTestFeatWithKeele().

561  {
562  for (int32 i = 1; i < 11; i++) {
563  std::string wavefile;
564  std::string num;
565  if (i < 6) {
566  num = "f"+ConvertIntToString(i)+"nw0000";
567  wavefile = "keele/16kHz/"+num+".wav";
568  } else {
569  num = "m"+ConvertIntToString(i-5)+"nw0000";
570  wavefile = "keele/16kHz/"+num+".wav";
571  }
572  KALDI_LOG << "--- " << wavefile << " ---";
573  std::ifstream is(wavefile.c_str(), std::ios_base::binary);
574  WaveData wave;
575  wave.Read(is);
576  KALDI_ASSERT(wave.Data().NumRows() == 1);
577  SubVector<BaseFloat> waveform(wave.Data(), 0);
579  op.lowpass_cutoff = 1000;
580  op.nccf_ballast = 0.1;
581  op.max_f0 = 400;
582  Matrix<BaseFloat> m, m2;
583  ComputeKaldiPitch(op, waveform, &m);
584  ProcessPitchOptions postprop_op;
585  // postprop_op.pov_nonlinearity = 2;
586  // Use zero noise, or the features won't be identical.
587  postprop_op.delta_pitch_noise_stddev = 0.0;
588  ProcessPitch(postprop_op, m, &m2);
589 
590  std::string outfile = "keele/tmp/+"+num+"-processed-kaldi.txt";
591  std::ofstream os(outfile.c_str());
592  m2.Write(os, false);
593  }
594 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
void Write(std::ostream &out, bool binary) const
write to stream.
std::string ConvertIntToString(const int &number)
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
kaldi::int32 int32
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void ProcessPitch(const ProcessPitchOptions &opts, const MatrixBase< BaseFloat > &input, Matrix< BaseFloat > *output)
This function processes the raw (NCCF, pitch) quantities computed by ComputeKaldiPitch, and processes them into features.
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestRand()

void kaldi::UnitTestRand ( )

Definition at line 77 of file kaldi-math-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, rnnlm::n, Rand(), RandGauss(), RandGauss2(), RandInt(), RandPoisson(), RandPrune(), RandUniform(), and WithProb().

Referenced by main().

77  {
78  // Testing random-number generation.
79  std::cout << "Testing random-number generation. "
80  << "If there is an error this may not terminate.\n";
81  std::cout << "If this does not terminate, look more closely. "
82  << "There might be a problem [but might not be]\n";
83  for (int i = 1; i < 10; i++) {
84  { // test RandUniform.
85  std::cout << "Test RandUniform\n";
86  KALDI_ASSERT(RandUniform() >= 0 && RandUniform() <= 1);
87  float sum = RandUniform()-0.5;
88  for (int j = 0; ; j++) {
89  sum += RandUniform()-0.5;
90  if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
91  }
92  }
93  { // test RandGauss.
94  float sum = RandGauss();
95  for (int j = 0; ; j++) {
96  sum += RandGauss();
97  if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
98  }
99  }
100  { // test RandGauss.
101  float sum = RandGauss();
102  for (int j = 0; ; j++) {
103  float a, b;
104  RandGauss2(&a, &b);
105  if (i % 2 == 0) sum += a;
106  else
107  sum += b;
108  if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
109  }
110  }
111  { // test poisson_Rand().
112  KALDI_ASSERT(RandPoisson(3.0) >= 0);
113  KALDI_ASSERT(RandPoisson(0.0) == 0);
114  std::cout << "Test RandPoisson\n";
115  float lambda = RandUniform() * 3.0; // between 0 and 3.
116  double sum = RandPoisson(lambda) - lambda; // expected value is zero.
117  for (int j = 0; ; j++) {
118  sum += RandPoisson(lambda) - lambda;
119  if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
120  }
121  }
122 
123  { // test WithProb().
124  for (int32 i = 0; i < 10; i++) {
125  KALDI_ASSERT((WithProb(0.0) == false) && (WithProb(1.0) == true));
126  }
127  {
128  int32 tot = 0, n = 10000;
129  BaseFloat p = 0.5;
130  for (int32 i = 0; i < n; i++)
131  tot += WithProb(p);
132  KALDI_ASSERT(tot > (n * p * 0.8) && tot < (n * p * 1.2));
133  }
134  {
135  int32 tot = 0, n = 10000;
136  BaseFloat p = 0.25;
137  for (int32 i = 0; i < n; i++)
138  tot += WithProb(p);
139  KALDI_ASSERT(tot > (n * p * 0.8) && tot < (n * p * 1.2));
140  }
141  }
142  { // test RandInt().
143  KALDI_ASSERT(RandInt(0, 3) >= 0 && RandInt(0, 3) <= 3);
144 
145  std::cout << "Test RandInt\n";
146  int minint = Rand() % 200;
147  int maxint = minint + 1 + Rand() % 20;
148 
149  float sum = RandInt(minint, maxint) + 0.5*(minint+maxint);
150  for (int j = 0; ; j++) {
151  sum += RandInt(minint, maxint) - 0.5*(minint+maxint);
152  if (std::abs(static_cast<float>(sum)) <
153  0.5*sqrt(static_cast<double>(j))*(maxint-minint)) break;
154  }
155  }
156  { // test RandPrune in basic way.
157  KALDI_ASSERT(RandPrune(1.1, 1.0) == 1.1);
158  KALDI_ASSERT(RandPrune(0.0, 0.0) == 0.0);
159  KALDI_ASSERT(RandPrune(-1.1, 1.0) == -1.1);
160  KALDI_ASSERT(RandPrune(0.0, 1.0) == 0.0);
161  KALDI_ASSERT(RandPrune(0.5, 1.0) >= 0.0);
162  KALDI_ASSERT(RandPrune(-0.5, 1.0) <= 0.0);
163  BaseFloat f = RandPrune(-0.5, 1.0);
164  KALDI_ASSERT(f == 0.0 || f == -1.0);
165  f = RandPrune(0.5, 1.0);
166  KALDI_ASSERT(f == 0.0 || f == 1.0);
167  }
168  }
169 }
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
bool WithProb(BaseFloat prob, struct RandomState *state)
Definition: kaldi-math.cc:72
Float RandPrune(Float post, BaseFloat prune_thresh, struct RandomState *state=NULL)
Definition: kaldi-math.h:174
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
int32 RandPoisson(float lambda, struct RandomState *state)
Definition: kaldi-math.cc:126
float BaseFloat
Definition: kaldi-types.h:29
void RandGauss2(float *a, float *b, RandomState *state)
Definition: kaldi-math.cc:139
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestRandCategorical()

static void kaldi::UnitTestRandCategorical ( )
static

Definition at line 4481 of file matrix-lib-test.cc.

References rnnlm::i, KALDI_ASSERT, KALDI_LOG, rnnlm::n, Rand(), VectorBase< Real >::RandCategorical(), and VectorBase< Real >::Sum().

4481  {
4482  int32 N = 1 + Rand() % 10;
4483  Vector<Real> vec(N);
4484  for (int32 n = 0; n < N; n++)
4485  vec(n) = Rand() % 3;
4486  if (vec.Sum() == 0)
4487  vec(0) = 2.0;
4488  Real sum = vec.Sum();
4489  int32 num_samples = 100000;
4490  std::vector<int32> counts(N, 0);
4491  for (int32 i = 0; i < num_samples; i++)
4492  counts[vec.RandCategorical()]++;
4493  for (int32 n = 0; n < N; n++) {
4494  Real a = counts[n] / (1.0 * num_samples),
4495  b = vec(n) / sum;
4496  KALDI_LOG << "a = " << a << ", b = " << b;
4497  KALDI_ASSERT(fabs(a - b) <= 0.1); // pretty arbitrary. Will increase #samp if fails.
4498  }
4499 }
kaldi::int32 int32
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestRange()

static void kaldi::UnitTestRange ( )
static

Definition at line 2653 of file matrix-lib-test.cc.

References ApproxEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), VectorBase< Real >::Range(), MatrixBase< Real >::Range(), VectorBase< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), MatrixBase< Real >::Sum(), and VectorBase< Real >::Sum().

2653  { // Testing SubMatrix class.
2654 
2655  // this is for matrix-range
2656  for (MatrixIndexT i = 0;i < 5;i++) {
2657  MatrixIndexT dimM = (Rand()%10) + 10;
2658  MatrixIndexT dimN = (Rand()%10) + 10;
2659 
2660  Matrix<Real> M(dimM, dimN);
2661  M.SetRandn();
2662  MatrixIndexT dimMStart = Rand() % 5;
2663  MatrixIndexT dimNStart = Rand() % 5;
2664 
2665  MatrixIndexT dimMEnd = dimMStart + 1 + (Rand()%10); if (dimMEnd > dimM) dimMEnd = dimM;
2666  MatrixIndexT dimNEnd = dimNStart + 1 + (Rand()%10); if (dimNEnd > dimN) dimNEnd = dimN;
2667 
2668 
2669  SubMatrix<Real> sub(M, dimMStart, dimMEnd-dimMStart, dimNStart, dimNEnd-dimNStart);
2670 
2671  KALDI_ASSERT(sub.Sum() == M.Range(dimMStart, dimMEnd-dimMStart, dimNStart, dimNEnd-dimNStart).Sum());
2672 
2673  for (MatrixIndexT i = dimMStart;i < dimMEnd;i++)
2674  for (MatrixIndexT j = dimNStart;j < dimNEnd;j++)
2675  KALDI_ASSERT(M(i, j) == sub(i-dimMStart, j-dimNStart));
2676 
2677  sub.SetRandn();
2678 
2679  KALDI_ASSERT(sub.Sum() == M.Range(dimMStart, dimMEnd-dimMStart, dimNStart, dimNEnd-dimNStart).Sum());
2680 
2681  for (MatrixIndexT i = dimMStart;i < dimMEnd;i++)
2682  for (MatrixIndexT j = dimNStart;j < dimNEnd;j++)
2683  KALDI_ASSERT(M(i, j) == sub(i-dimMStart, j-dimNStart));
2684  }
2685 
2686  // this if for vector-range
2687  for (MatrixIndexT i = 0;i < 5;i++) {
2688  MatrixIndexT length = (Rand()%10) + 10;
2689 
2690  Vector<Real> V(length);
2691  V.SetRandn();
2692  MatrixIndexT lenStart = Rand() % 5;
2693 
2694  MatrixIndexT lenEnd = lenStart + 1 + (Rand()%10); if (lenEnd > length) lenEnd = length;
2695 
2696  SubVector<Real> sub(V, lenStart, lenEnd-lenStart);
2697 
2698  KALDI_ASSERT(ApproxEqual(sub.Sum(), V.Range(lenStart, lenEnd-lenStart).Sum()));
2699 
2700  for (MatrixIndexT i = lenStart;i < lenEnd;i++)
2701  KALDI_ASSERT(V(i) == sub(i-lenStart));
2702 
2703  sub.SetRandn();
2704 
2705  KALDI_ASSERT(ApproxEqual(sub.Sum(), V.Range(lenStart, lenEnd-lenStart).Sum()));
2706 
2707  for (MatrixIndexT i = lenStart;i < lenEnd;i++)
2708  KALDI_ASSERT(V(i) == sub(i-lenStart));
2709  }
2710 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Sub-matrix representation.
Definition: kaldi-matrix.h:988
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestRangesMatrix()

void kaldi::UnitTestRangesMatrix ( bool  binary)

Definition at line 842 of file kaldi-table-test.cc.

References SequentialTableReader< Holder >::Done(), RandomAccessTableReader< Holder >::HasKey(), rnnlm::i, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), rnnlm::n, SequentialTableReader< Holder >::Next(), MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), RandInt(), Output::Stream(), Input::Stream(), Trim(), RandomAccessTableReader< Holder >::Value(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

842  {
843  int32 archive_size = RandInt(1, 10);
844  std::vector<std::pair<std::string, Matrix<BaseFloat> > > archive_contents(
845  archive_size);
846  for (int32 i = 0; i < archive_size; i++) {
847  char key_buf[2];
848  key_buf[0] = 'A' + i;
849  key_buf[1] = '\0';
850  std::string key(key_buf);
851  archive_contents[i].first = key;
852  archive_contents[i].second.Resize(RandInt(1, 5), RandInt(1, 5));
853  archive_contents[i].second.SetRandn();
854  }
855  if (RandInt(0, 1) == 0)
856  std::random_shuffle(archive_contents.begin(), archive_contents.end());
857 
858  std::ostringstream writer_name;
859  writer_name << "ark,scp";
860  if (binary) writer_name << ",b";
861  else writer_name << ",t";
862  writer_name << ":tmpf,tmpf.scp";
863 
864  {
865  BaseFloatMatrixWriter writer(writer_name.str());
866  for (int32 i = 0; i < archive_size; i++)
867  writer.Write(archive_contents[i].first, archive_contents[i].second);
868  }
869 
870  std::vector<std::string> scp_lines;
871  {
872  bool binary;
873  Input scp_input("tmpf.scp", &binary);
874  KALDI_ASSERT(!binary);
875  std::string line;
876  while (getline(scp_input.Stream(), line)) {
877  Trim(&line); // remove trailing and beginning whitespace.
878  scp_lines.push_back(line);
879  }
880  KALDI_ASSERT(scp_lines.size() == archive_contents.size());
881  }
882 
883  int32 scp_length = RandInt(0, 10);
884  std::vector<std::pair<std::string, Matrix<BaseFloat> > >
885  scp_intended_contents(scp_length);
886 
887  {
888  Output output("tmpf_ranges.scp", false);
889 
890  for (int32 i = 0; i < scp_length; i++) {
891  int32 src_i = RandInt(0, archive_size - 1);
892  std::string scp_line_str = scp_lines[src_i]; // a line like "A tmpf:1043", without newline.
893  scp_line_str[0] = 'a' + i; // now scp_line_str looks like "a tmpf:1043".
894  std::string key("x");
895  key[0] = 'a' + i;
896  scp_intended_contents[i].first = key;
897  output.Stream() << scp_line_str;
898  const Matrix<BaseFloat> &src_mat = archive_contents[src_i].second;
899  if (RandInt(0, 1) == 0) { // Use a range.
900  int32 tot_rows = src_mat.NumRows(), tot_cols = src_mat.NumCols();
901  int32 row_offset = RandInt(0, tot_rows - 1),
902  num_rows = RandInt(1, tot_rows - row_offset),
903  col_offset = RandInt(0, tot_cols - 1),
904  num_cols = RandInt(1, tot_cols - col_offset);
905  SubMatrix<BaseFloat> sub_mat(src_mat, row_offset, num_rows,
906  col_offset, num_cols);
907  scp_intended_contents[i].second = sub_mat;
908  output.Stream() << "[";
909  if (row_offset != 0 || num_rows != tot_rows)
910  output.Stream() << row_offset << ":"
911  << (row_offset + num_rows - 1);
912  else
913  output.Stream() << ":";
914  if (col_offset != 0 || num_cols != tot_cols) {
915  output.Stream() << "," << col_offset
916  << ":" << (col_offset + num_cols - 1);
917  } else {
918  if (RandInt(0, 1) == 0) {
919  output.Stream() << ",:";
920  }
921  }
922  output.Stream() << "]";
923  } else { // no range.
924  scp_intended_contents[i].second = src_mat;
925  }
926  output.Stream() << "\n";
927  }
928  }
929 
930  { // test random-access reading.
931  bool permissive = (RandInt(0, 1) == 0);
932  RandomAccessDoubleMatrixReader reader(permissive ?
933  "scp,p:tmpf_ranges.scp" :
934  "scp:tmpf_ranges.scp");
935 
936  int32 num_queries = RandInt(0, 10);
937  for (int32 n = 0; n < num_queries; n++) {
938  int32 i = RandInt(0, scp_length);
939  if (i == scp_length) { // fake "bad" query.
940  KALDI_ASSERT(!reader.HasKey("foobar"));
941  } else {
942  std::string key = scp_intended_contents[i].first;
943  if (RandInt(0, 1) == 0)
944  KALDI_ASSERT(reader.HasKey(key));
945  Matrix<BaseFloat> value (reader.Value(key));
946  KALDI_ASSERT(value.ApproxEqual(scp_intended_contents[i].second));
947  }
948  }
949  }
950 
951 
952  { // test sequential reading.
953  bool permissive = (RandInt(0, 1) == 0);
954  SequentialBaseFloatMatrixReader reader(permissive ?
955  "scp,p:tmpf_ranges.scp" :
956  "scp:tmpf_ranges.scp");
957 
958  int32 i = 0;
959  for (; !reader.Done(); reader.Next(), i++) {
960  KALDI_ASSERT(reader.Key() == scp_intended_contents[i].first);
961  KALDI_ASSERT(reader.Value().ApproxEqual(scp_intended_contents[i].second));
962  }
963  KALDI_ASSERT(i == scp_length);
964  }
965 
966 
967  unlink("tmpf");
968  unlink("tmpf.scp");
969  unlink("tmpf_ranges.scp");
970 }
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
void Write(const std::string &key, const T &value) const
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
struct rnnlm::@11::@12 n
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
void Trim(std::string *str)
Removes the beginning and trailing whitespaces from a string.
Definition: text-utils.cc:92
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
Sub-matrix representation.
Definition: kaldi-matrix.h:988
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestRankNUpdate()

static void kaldi::UnitTestRankNUpdate ( )
static

Definition at line 2140 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::AddMatMat(), AssertEqual(), kNoTrans, kTrans, Rand(), and MatrixBase< Real >::SetRandn().

2140  {
2141  for (MatrixIndexT iter = 0;iter < 10;iter++) {
2142  MatrixIndexT dimA = 10 + Rand()%3;
2143  MatrixIndexT dimO = 10 + Rand()%3;
2144  Matrix<Real> Af(dimA, dimA);
2145  SpMatrix<Real> Ap(dimA);
2146  SpMatrix<Real> Ap2(dimA);
2147  Matrix<Real> M(dimO, dimA);
2148  M.SetRandn();
2149  Matrix<Real> N(M, kTrans);
2150  Af.AddMatMat(1.0, M, kTrans, M, kNoTrans, 0.0);
2151  Ap.AddMat2(1.0, M, kTrans, 0.0);
2152  Ap2.AddMat2(1.0, N, kNoTrans, 0.0);
2153  Matrix<Real> Ap_f(Ap);
2154  Matrix<Real> Ap2_f(Ap2);
2155  AssertEqual(Ap_f, Af);
2156  AssertEqual(Ap2_f, Af);
2157  }
2158 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestReadConfig()

void kaldi::UnitTestReadConfig ( )

Definition at line 479 of file text-utils-test.cc.

References ApproxEqual(), rnnlm::i, KALDI_ASSERT, and ReadConfigLines().

Referenced by main().

479  {
480  std::string str = "a-b alpha=aa beta=\"b b\"# String test\n"
481  "a-b beta2='b c' beta3=bd # \n"
482  "a-b gamma=1:2:3:4 # Int Vector test\n"
483  " a-b de1ta=f # Bool + Integer in key Comment test delta=t \n"
484  "a-b _epsilon=-1 # Int Vector test _epsilon=1 \n"
485  "a-b zet-_a=0.15 theta=1.1# Float, -, _ test\n"
486  "a-b quoted='a b c' # quoted string\n"
487  "a-b quoted2=\"d e 'a b=c' f\" # string quoted with double quotes";
488 
489  std::istringstream is(str);
490  std::vector<std::string> lines;
491  ReadConfigLines(is, &lines);
492  KALDI_ASSERT(lines.size() == 8);
493 
494  ConfigLine cfl;
495  for (size_t i = 0; i < lines.size(); i++) {
496  KALDI_ASSERT(cfl.ParseLine(lines[i]) && cfl.FirstToken() == "a-b");
497  if (i == 1) {
498  KALDI_ASSERT(cfl.GetValue("beta2", &str) && str == "b c");
499  }
500  if (i == 4) {
501  KALDI_ASSERT(cfl.GetValue("_epsilon", &str) && str == "-1");
502  }
503  if (i == 5) {
504  BaseFloat float_val = 0;
505  KALDI_ASSERT(cfl.GetValue("zet-_a", &float_val) && ApproxEqual(float_val, 0.15));
506  }
507  if (i == 6) {
508  KALDI_ASSERT(cfl.GetValue("quoted", &str) && str == "a b c");
509  }
510  if (i == 7) {
511  KALDI_ASSERT(cfl.GetValue("quoted2", &str) && str == "d e 'a b=c' f");
512  }
513  }
514 }
float BaseFloat
Definition: kaldi-types.h:29
void ReadConfigLines(std::istream &is, std::vector< std::string > *lines)
This function reads in a config file and *appends* its contents to a vector of lines; it is responsib...
Definition: text-utils.cc:564
This class is responsible for parsing input like hi-there xx=yyy a=b c empty= f-oo=Append(bar, sss) ba_z=123 bing=&#39;a b c&#39; baz="a b c d=&#39;a b&#39; e" and giving you access to the fields, in this case.
Definition: text-utils.h:205
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestReadScriptFile()

void kaldi::UnitTestReadScriptFile ( )

Definition at line 28 of file kaldi-table-test.cc.

References Output::Close(), KALDI_ASSERT, ReadScriptFile(), Sleep(), and Output::Stream().

Referenced by main().

28  {
29  typedef std::pair<std::string, std::string> pr;
30  {
31  std::stringstream ss;
32  ss << " a b\n";
33  ss << "c d \n";
34  ss << "c d e \n";
35  std::vector<pr> script;
36  bool ans = ReadScriptFile(ss, true, &script);
37  KALDI_ASSERT(ans);
38  std::vector<pr> script2;
39  script2.push_back(std::pair<std::string, std::string>("a", "b"));
40  script2.push_back(std::pair<std::string, std::string>("c", "d"));
41  script2.push_back(std::pair<std::string, std::string>("c", "d e"));
42  KALDI_ASSERT(script == script2);
43  }
44  {
45  typedef std::pair<std::string, std::string> pr;
46  std::stringstream ss;
47  ss << " a \n";
48  std::vector<pr> script;
49  // suppress the warning since I already checked it's OK.
50  KALDI_ASSERT(!ReadScriptFile(ss, false, &script));
51  }
52  {
53  typedef std::pair<std::string, std::string> pr;
54  std::stringstream ss;
55  ss << "\n";
56  std::vector<pr> script;
57  // suppress the warning since I already checked it's OK.
58  KALDI_ASSERT(!ReadScriptFile(ss, false, &script));
59  }
60 #if !defined(_MSC_VER) || defined(KALDI_CYGWIN_COMPAT)
61  {
62  Output ko("| gzip -c > tmpf.gz", false); // text mode.
63  ko.Stream() << "a b\n";
64  ko.Close();
65  std::vector<pr> script;
66  Sleep(1); // This test does not work without this sleep:
67  bool ans = ReadScriptFile("gunzip -c tmpf.gz |", true, &script);
68  KALDI_ASSERT(ans);
69  std::vector<pr> script2;
70  script2.push_back(std::pair<std::string, std::string>("a", "b"));
71  KALDI_ASSERT(script == script2);
72  }
73 
74  {
75  Output ko("| gzip -c > tmpf.gz", true); // binary mode w/ header:
76  // should fail, because script files should not have binary header.
77  ko.Stream() << "a b\n";
78  bool ans = ko.Close();
79  KALDI_ASSERT(ans);
80  Sleep(1); // This test does not work without this sleep:
81  // seems to be some kind of file-system latency.
82  std::vector<pr> script;
83  ans = ReadScriptFile("gunzip -c tmpf.gz |", false, &script);
84  KALDI_ASSERT(!ans);
85  }
86  unlink("tmpf.gz");
87 #endif
88 }
void Sleep(float seconds)
Definition: kaldi-utils.cc:45
bool ReadScriptFile(const std::string &rxfilename, bool warn, std::vector< std::pair< std::string, std::string > > *script_out)
Definition: kaldi-table.cc:26
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestRealFft()

static void kaldi::UnitTestRealFft ( )
static

Definition at line 3611 of file matrix-lib-test.cc.

References AssertEqual(), VectorBase< Real >::CopyFromVec(), Rand(), RealFft(), RealFftInefficient(), and VectorBase< Real >::Scale().

3611  {
3612 
3613  // First, test RealFftInefficient.
3614  for (MatrixIndexT N_ = 2; N_ < 100; N_ += 6) {
3615  MatrixIndexT N = N_;
3616  if (N >90) N *= Rand() % 60;
3617  Vector<Real> v(N), w(N), x(N), y(N);
3618  v.SetRandn();
3619  w.CopyFromVec(v);
3620  RealFftInefficient(&w, true);
3621  y.CopyFromVec(v);
3622  RealFft(&y, true); // test efficient one.
3623  // KALDI_LOG <<"v = "<<v;
3624  // KALDI_LOG << "Inefficient real fft of v is: "<< w;
3625  // KALDI_LOG << "Efficient real fft of v is: "<< y;
3626  AssertEqual(w, y, 0.01*N);
3627  x.CopyFromVec(w);
3628  RealFftInefficient(&x, false);
3629  RealFft(&y, false);
3630  // KALDI_LOG << "Inefficient real fft of v twice is: "<< x;
3631  if (N != 0) x.Scale(1.0/N);
3632  if (N != 0) y.Scale(1.0/N);
3633  AssertEqual(v, x, 0.001*N);
3634  AssertEqual(v, y, 0.001*N); // ?
3635  }
3636 }
void RealFftInefficient(VectorBase< Real > *v, bool forward)
Inefficient version of Fourier transform, for testing purposes.
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void RealFft(VectorBase< Real > *v, bool forward)
RealFft is a fourier transform of real inputs.

◆ UnitTestRealFftSpeed() [1/2]

static void kaldi::UnitTestRealFftSpeed ( )
static

Definition at line 38 of file matrix-lib-speed-test.cc.

References Timer::Elapsed(), rnnlm::i, KALDI_LOG, and RealFft().

38  {
39  // First, test RealFftInefficient.
40  Timer t;
41  MatrixIndexT sz = 512; // fairly typical size.
42  for (MatrixIndexT i = 0; i < 3000; i++) {
43  if (i % 1000 == 0) KALDI_LOG << "done 1000 [ == ten seconds of speech]";
44  Vector<Real> v(sz);
45  RealFft(&v, true);
46  }
47  CsvResult<Real>(__func__, 512, t.Elapsed(), "seconds");
48 }
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
void RealFft(VectorBase< Real > *v, bool forward)
RealFft is a fourier transform of real inputs.

◆ UnitTestRealFftSpeed() [2/2]

static void kaldi::UnitTestRealFftSpeed ( )
static

Definition at line 3676 of file matrix-lib-test.cc.

References rnnlm::i, KALDI_LOG, and RealFft().

3676  {
3677 
3678  // First, test RealFftInefficient.
3679  KALDI_LOG << "starting. ";
3680  MatrixIndexT sz = 512; // fairly typical size.
3681  for (MatrixIndexT i = 0; i < 3000; i++) {
3682  if (i % 1000 == 0) KALDI_LOG << "done 1000 [ == ten seconds of speech]";
3683  Vector<Real> v(sz);
3684  RealFft(&v, true);
3685  }
3686 }
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153
void RealFft(VectorBase< Real > *v, bool forward)
RealFft is a fourier transform of real inputs.

◆ UnitTestRegtreeFmllrDiagGmm()

void kaldi::UnitTestRegtreeFmllrDiagGmm ( cova_type  feature_type,
size_t  max_bclass 
)

Definition at line 140 of file regtree-fmllr-diag-gmm-test.cc.

References AccumAmDiagGmm::AccumulateForGmm(), RegtreeFmllrDiagGmmAccs::AccumulateForGmm(), AmDiagGmm::AddPdf(), RegressionTree::BuildTree(), DiagGmm::ComputeGconsts(), MatrixBase< Real >::Cond(), MatrixBase< Real >::CopyFromMat(), VectorBase< Real >::CopyFromVec(), rnnlm::d, DeletePointers(), generate_features(), RegtreeFmllrDiagGmm::GetLogDets(), rnnlm::i, AccumAmDiagGmm::Init(), RegtreeFmllrDiagGmmAccs::Init(), MatrixBase< Real >::InvertElements(), rnnlm::j, kGmmAll, RegtreeFmllrOptions::min_count, MleAmDiagGmmUpdate(), rnnlm::n, RegressionTree::NumBaseclasses(), RegtreeFmllrDiagGmm::NumBaseClasses(), AmDiagGmm::NumGaussInPdf(), RegtreeFmllrDiagGmm::NumRegClasses(), Rand(), RandUniform(), RegtreeFmllrDiagGmm::Read(), DiagGmm::Resize(), Vector< Real >::Resize(), DiagGmm::SetInvVarsAndMeans(), MatrixBase< Real >::SetRandn(), DiagGmm::SetWeights(), RegtreeFmllrDiagGmmAccs::SetZero(), AmDiagGmm::SplitPdf(), Input::Stream(), RegtreeFmllrDiagGmm::TransformFeature(), RegtreeFmllrDiagGmmAccs::Update(), RegtreeFmllrOptions::use_regtree, RegtreeFmllrDiagGmm::Validate(), and RegtreeFmllrDiagGmm::Write().

Referenced by main().

140  {
141  // dimension of the feature space
142  size_t dim = 5 + Rand() % 3;
143 
144  // number of components in the data
145  size_t n_gaussians = 8;
146 
147  // number of data points to generate for every gaussian
148  size_t frames_per_gaussian = 100;
149 
150  // generate random transformation matrix trans_mat
151  Matrix<BaseFloat> trans_mat(dim, dim);
152  int i = 0;
153  while (i < 10000) {
154  trans_mat.SetRandn();
155  if (trans_mat.Cond() < 100) break;
156  i++;
157  }
158  std::cout << "Condition of original Trans_Mat: " << trans_mat.Cond() << '\n';
159 
160  // generate many feature vectors for each of the mixture components
161  std::vector<Vector<BaseFloat>*>
162  train_feats(n_gaussians * frames_per_gaussian);
163  std::vector<Vector<BaseFloat>*>
164  adapt_feats(n_gaussians * frames_per_gaussian);
165 
166  generate_features(feature_type,
167  n_gaussians,
168  dim,
169  trans_mat,
170  frames_per_gaussian,
171  train_feats,
172  adapt_feats);
173 
174  // initial values for a GMM
175  Vector<BaseFloat> weights(1);
176  Matrix<BaseFloat> means(1, dim), vars(1, dim), invvars(1, dim);
177  for (size_t d= 0; d < dim; d++) {
178  means(0, d) = 0.0F;
179  vars(0, d) = 1.0F;
180  }
181  weights(0) = 1.0F;
182  invvars.CopyFromMat(vars);
183  invvars.InvertElements();
184 
185  // new HMM with 1 state
186  DiagGmm *gmm = new DiagGmm();
187  gmm->Resize(1, dim);
188  gmm->SetWeights(weights);
189  gmm->SetInvVarsAndMeans(invvars, means);
190  gmm->ComputeGconsts();
191  GmmFlagsType flags = kGmmAll;
192  MleDiagGmmOptions opts;
193 
194  AmDiagGmm *am = new AmDiagGmm();
195  am->AddPdf(*gmm);
196  AccumAmDiagGmm *est_am = new AccumAmDiagGmm();
197 
198  // train HMM
199  size_t iteration = 0;
200  size_t maxiterations = 10;
201  int32 maxcomponents = n_gaussians;
202  BaseFloat loglike = 0;
203  while (iteration < maxiterations) {
204  est_am->Init(*am, flags);
205 
206  loglike = 0;
207  for (size_t j = 0; j < train_feats.size(); j++) {
208  loglike += est_am->AccumulateForGmm(*am, *train_feats[j], 0, 1.0);
209  }
210  MleAmDiagGmmUpdate(opts, *est_am, flags, am, NULL, NULL);
211 
212  std::cout << "Loglikelihood before iteration " << iteration << " : "
213  << std::scientific << loglike << " number of components: "
214  << am->NumGaussInPdf(0) << '\n';
215 
216  if ((iteration % 3 == 1) &&
217  (am->NumGaussInPdf(0) * 2 <= maxcomponents)) {
218  size_t n = am->NumGaussInPdf(0)*2;
219  am->SplitPdf(0, n, 0.001);
220  }
221  iteration++;
222  }
223 
224  // adapt HMM to the transformed feature vectors
225  iteration = 0;
226  RegtreeFmllrDiagGmmAccs * fmllr_accs = new RegtreeFmllrDiagGmmAccs();
227  RegressionTree regtree;
228 
229  RegtreeFmllrOptions xform_opts;
230  xform_opts.min_count = 100 * (1 + Rand() % 10);
231  xform_opts.use_regtree = (RandUniform() < 0.5)? false : true;
232 
233  size_t num_pdfs = 1;
234  Vector<BaseFloat> occs(num_pdfs);
235  for (int32 i = 0; i < static_cast<int32>(num_pdfs); i++) {
236  occs(i) = 1.0/static_cast<BaseFloat>(num_pdfs);
237  }
238  std::vector<int32> silphones;
239  regtree.BuildTree(occs, silphones, *am, max_bclass);
240  maxiterations = 10;
241  std::vector<Vector<BaseFloat>*> logdet(adapt_feats.size());
242  for (size_t j = 0; j < adapt_feats.size(); j++) {
243  logdet[j] = new Vector<BaseFloat>(1);
244  logdet[j]->operator()(0) = 0.0;
245  }
246  while (iteration < maxiterations) {
247  fmllr_accs->Init(regtree.NumBaseclasses(), dim);
248  fmllr_accs->SetZero();
249  RegtreeFmllrDiagGmm *new_fmllr = new RegtreeFmllrDiagGmm();
250  loglike = 0;
251  for (size_t j = 0; j < adapt_feats.size(); j++) {
252  loglike += fmllr_accs->AccumulateForGmm(regtree, *am, *adapt_feats[j], 0, 1.0);
253  loglike += logdet[j]->operator()(0);
254  }
255  std::cout << "FMLLR: Loglikelihood before iteration " << iteration << " : "
256  << std::scientific << loglike << '\n';
257 
258  fmllr_accs->Update(regtree, xform_opts, new_fmllr, NULL, NULL);
259  std::cout << "Got " << new_fmllr->NumBaseClasses() << " baseclasses\n";
260  bool binary = (RandUniform() < 0.5)? true : false;
261  std::cout << "Writing the transform to disk.\n";
262  new_fmllr->Write(Output("tmpf", binary).Stream(), binary);
263  RegtreeFmllrDiagGmm *fmllr_read = new RegtreeFmllrDiagGmm();
264  bool binary_in;
265  Input ki("tmpf", &binary_in);
266  std::cout << "Reading the transform from disk.\n";
267  fmllr_read->Read(ki.Stream(), binary_in);
268  fmllr_read->Validate();
269 
270  // transform features
271  std::vector<Vector<BaseFloat> > trans_feats(1);
272  Vector<BaseFloat> trans_logdet;
273 // new_fmllr->ComputeLogDets();
274  trans_logdet.Resize(fmllr_read->NumRegClasses());
275  fmllr_read->GetLogDets(&trans_logdet);
276  for (size_t j = 0; j < adapt_feats.size(); j++) {
277  fmllr_read->TransformFeature(*adapt_feats[j], &trans_feats);
278  logdet[j]->operator()(0) += trans_logdet(0);
279  adapt_feats[j]->CopyFromVec(trans_feats[0]);
280  }
281  iteration++;
282  delete new_fmllr;
283  delete fmllr_read;
284 
285  unlink("tmpf");
286  }
287 
288 // // transform features with empty transform
289 // std::vector<Vector<BaseFloat> > trans_feats(1);
290 // RegtreeFmllrDiagGmm *empty_fmllr = new RegtreeFmllrDiagGmm();
291 // empty_fmllr->Init(0, 0);
292 // for (size_t j = 0; j < adapt_feats.size(); j++) {
293 // empty_fmllr->TransformFeature(*adapt_feats[j], &trans_feats);
294 // }
295 // delete empty_fmllr;
296 
297  // clean up
298  delete fmllr_accs;
299  delete est_am;
300  delete am;
301  delete gmm;
302  DeletePointers(&logdet);
303  DeletePointers(&train_feats);
304  DeletePointers(&adapt_feats);
305 }
void MleAmDiagGmmUpdate(const MleDiagGmmOptions &config, const AccumAmDiagGmm &am_diag_gmm_acc, GmmFlagsType flags, AmDiagGmm *am_gmm, BaseFloat *obj_change_out, BaseFloat *count_out)
for computing the maximum-likelihood estimates of the parameters of an acoustic model that uses diago...
void DeletePointers(std::vector< A *> *v)
Deletes any non-NULL pointers in the vector v, and sets the corresponding entries of v to NULL...
Definition: stl-utils.h:184
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
kaldi::int32 int32
static void generate_features(cova_type covariance_type, size_t n_gaussians, size_t dim, Matrix< BaseFloat > &trans_mat, size_t frames_per_gaussian, std::vector< Vector< BaseFloat > *> &train_feats, std::vector< Vector< BaseFloat > *> &adapt_feats)
uint16 GmmFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:35
float BaseFloat
Definition: kaldi-types.h:29
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45

◆ UnitTestRemoveRow()

static void kaldi::UnitTestRemoveRow ( )
static

Definition at line 389 of file matrix-lib-test.cc.

References rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), Vector< Real >::RemoveElement(), Matrix< Real >::RemoveRow(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::SetRandn().

389  {
390 
391  // this is for matrix
392  for (MatrixIndexT p = 0;p< 10;p++) {
393  MatrixIndexT dimM = 10+Rand()%10, dimN = 10+Rand()%10;
394  Matrix<Real> M(dimM, dimN);
395  M.SetRandn();
396  MatrixIndexT i = Rand() % dimM; // Row to remove.
397  Matrix<Real> N(M);
398  N.RemoveRow(i);
399  for (MatrixIndexT j = 0;j < i;j++) {
400  for (MatrixIndexT k = 0;k < dimN;k++) {
401  KALDI_ASSERT(M(j, k) == N(j, k));
402  }
403  }
404  for (MatrixIndexT j = i+1;j < dimM;j++) {
405  for (MatrixIndexT k = 0;k < dimN;k++) {
406  KALDI_ASSERT(M(j, k) == N(j-1, k));
407  }
408  }
409  }
410 
411  // this is for vector
412  for (MatrixIndexT p = 0;p< 10;p++) {
413  MatrixIndexT dimM = 10+Rand()%10;
414  Vector<Real> V(dimM);
415  V.SetRandn();
416  MatrixIndexT i = Rand() % dimM; // Element to remove.
417  Vector<Real> N(V);
418  N.RemoveElement(i);
419  for (MatrixIndexT j = 0;j < i;j++) {
420  KALDI_ASSERT(V(j) == N(j));
421  }
422  for (MatrixIndexT j = i+1;j < dimM;j++) {
423  KALDI_ASSERT(V(j) == N(j-1));
424  }
425  }
426 
427 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestReplaceValue()

static void kaldi::UnitTestReplaceValue ( )
static

Definition at line 657 of file matrix-lib-test.cc.

References AssertEqual(), VectorBase< Real >::Dim(), rnnlm::i, Rand(), VectorBase< Real >::ReplaceValue(), and VectorBase< Real >::SetRandn().

657  {
658  // for vector
659  MatrixIndexT dim = 10 + Rand() % 2;
660  Real orig = 0.1 * (Rand() % 100), changed = 0.1 * (Rand() % 50);
661  Vector<Real> V(dim);
662  V.SetRandn();
663  V(dim / 2) = orig;
664  Vector<Real> V1(V);
665  for (MatrixIndexT i = 0; i < V1.Dim(); i ++) {
666  if (V1(i) == orig) V1(i) = changed;
667  }
668  V.ReplaceValue(orig, changed);
669  AssertEqual(V, V1);
670 }
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestResize()

static void kaldi::UnitTestResize ( )
static

Definition at line 1899 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, SpMatrix< Real >::IsZero(), MatrixBase< Real >::IsZero(), rnnlm::j, KALDI_ASSERT, kCopyData, kSetZero, Rand(), SpMatrix< Real >::Resize(), Vector< Real >::Resize(), Matrix< Real >::Resize(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and VectorBase< Real >::Sum().

1899  {
1900  for (size_t i = 0; i < 10; i++) {
1901  MatrixIndexT dimM1 = Rand() % 10, dimN1 = Rand() % 10,
1902  dimM2 = Rand() % 10, dimN2 = Rand() % 10;
1903  if (dimM1*dimN1 == 0) dimM1 = dimN1 = 0;
1904  if (dimM2*dimN2 == 0) dimM2 = dimN2 = 0;
1905  for (MatrixIndexT j = 0; j < 3; j++) {
1906  MatrixResizeType resize_type = static_cast<MatrixResizeType>(j);
1907  Matrix<Real> M(dimM1, dimN1);
1908  M.SetRandn();
1909  Matrix<Real> Mcopy(M);
1910  Vector<Real> v(dimM1);
1911  v.SetRandn();
1912  Vector<Real> vcopy(v);
1913  SpMatrix<Real> S(dimM1);
1914  S.SetRandn();
1915  SpMatrix<Real> Scopy(S);
1916  M.Resize(dimM2, dimN2, resize_type);
1917  v.Resize(dimM2, resize_type);
1918  S.Resize(dimM2, resize_type);
1919  if (resize_type == kSetZero) {
1920  KALDI_ASSERT(S.IsZero());
1921  KALDI_ASSERT(v.Sum() == 0.0);
1922  KALDI_ASSERT(M.IsZero());
1923  } else if (resize_type == kCopyData) {
1924  for (MatrixIndexT i = 0; i < dimM2; i++) {
1925  if (i < dimM1) AssertEqual(v(i), vcopy(i));
1926  else KALDI_ASSERT(v(i) == 0);
1927  for (MatrixIndexT j = 0; j < dimN2; j++) {
1928  if (i < dimM1 && j < dimN1) AssertEqual(M(i, j), Mcopy(i, j));
1929  else AssertEqual(M(i, j), 0.0);
1930  }
1931  for (MatrixIndexT i2 = 0; i2 < dimM2; i2++) {
1932  if (i < dimM1 && i2 < dimM1) AssertEqual(S(i, i2), Scopy(i, i2));
1933  else AssertEqual(S(i, i2), 0.0);
1934  }
1935  }
1936  }
1937  }
1938  }
1939 }
Packed symetric matrix class.
Definition: matrix-common.h:62
MatrixResizeType
Definition: matrix-common.h:37
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestResizeCopyDataDifferentStrideType()

static void kaldi::UnitTestResizeCopyDataDifferentStrideType ( )
static

Make sure that when Resize() is called with resize_type = kCopyData and a stride_type different from this's stride_type, the resized matrix is equivalent to the original matrix (modulo the stride).

Definition at line 1879 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, kCopyData, kDefaultStride, kSetZero, kStrideEqualNumCols, PlaceNansInGaps(), Rand(), and Matrix< Real >::Resize().

1879  {
1880  for (size_t i = 0; i < 10; i++) {
1881  MatrixIndexT num_rows = Rand() % 10, num_cols = Rand() % 10;
1882  if (num_rows * num_cols == 0) num_rows = num_cols = 0;
1883  MatrixStrideType src_stride_type = (Rand() % 2 == 0) ?
1885  // Always pick the other stride type.
1886  MatrixStrideType resize_stride_type = (src_stride_type == kDefaultStride) ?
1888  Matrix<Real> src(num_rows, num_cols, kSetZero, src_stride_type);
1889  Matrix<Real> clone(src);
1890  PlaceNansInGaps(&clone);
1891  src.Resize(num_rows, num_cols, kCopyData, resize_stride_type);
1892  PlaceNansInGaps(&src);
1893  AssertEqual(src, clone);
1894  }
1895 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
void PlaceNansInGaps(Matrix< Real > *mat)
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixStrideType
Definition: matrix-common.h:44
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestRoundUpToNearestPowerOfTwo()

void kaldi::UnitTestRoundUpToNearestPowerOfTwo ( )

Definition at line 47 of file kaldi-math-test.cc.

References KALDI_ASSERT, and RoundUpToNearestPowerOfTwo().

Referenced by main().

47  {
57  KALDI_ASSERT(RoundUpToNearestPowerOfTwo(1073700000) == 1073741824);
58 }
int32 RoundUpToNearestPowerOfTwo(int32 n)
Definition: kaldi-math.cc:32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestRow()

static void kaldi::UnitTestRow ( )
static

Definition at line 984 of file matrix-lib-test.cc.

References AssertEqual(), VectorBase< Real >::CopyColFromMat(), VectorBase< Real >::CopyRowFromMat(), rnnlm::i, InitRandNonsingular(), rnnlm::j, and Rand().

984  {
985 
986  for (MatrixIndexT p = 0;p< 10;p++) {
987  MatrixIndexT dimM = 10+Rand()%10, dimN = 10+Rand()%10;
988  Matrix<Real> M(dimM, dimN);
990 
991  MatrixIndexT i = Rand() % dimM; // Row to get.
992 
993  Vector<Real> V(dimN);
994  V.CopyRowFromMat(M, i); // get row.
995  for (MatrixIndexT k = 0;k < dimN;k++) {
996  AssertEqual(M(i, k), V(k));
997  }
998 
999  {
1000  SpMatrix<Real> S(dimN);
1001  InitRandNonsingular(&S);
1002  Vector<Real> v1(dimN), v2(dimN);
1003  Matrix<Real> M(S);
1004  MatrixIndexT dim2 = Rand() % dimN;
1005  v1.CopyRowFromSp(S, dim2);
1006  v2.CopyRowFromMat(M, dim2);
1007  AssertEqual(v1, v2);
1008  }
1009 
1010  MatrixIndexT j = Rand() % dimN; // Col to get.
1011  Vector<Real> W(dimM);
1012  W.CopyColFromMat(M, j); // get row.
1013  for (MatrixIndexT k = 0;k < dimM;k++) {
1014  AssertEqual(M(k, j), W(k));
1015  }
1016 
1017  }
1018 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
static void InitRandNonsingular(SpMatrix< Real > *M)

◆ UnitTestScale()

static void kaldi::UnitTestScale ( )
static

Definition at line 2712 of file matrix-lib-test.cc.

References MatrixBase< Real >::CopyFromMat(), rnnlm::i, rnnlm::j, KALDI_ASSERT, MatrixBase< Real >::MulColsVec(), MatrixBase< Real >::MulRowsVec(), Rand(), MatrixBase< Real >::Scale(), VectorBase< Real >::SetRandn(), and MatrixBase< Real >::Sum().

2712  {
2713 
2714  for (MatrixIndexT i = 0;i < 5;i++) {
2715  MatrixIndexT dimM = (Rand()%10) + 10;
2716  MatrixIndexT dimN = (Rand()%10) + 10;
2717 
2718  Matrix<Real> M(dimM, dimN);
2719 
2720  Matrix<Real> N(M);
2721  float f = (float)((Rand()%10)-5);
2722  M.Scale(f);
2723  KALDI_ASSERT(M.Sum() == f * N.Sum());
2724 
2725  {
2726  // now test scale_rows
2727  M.CopyFromMat(N); // make same.
2728  Vector<Real> V(dimM);
2729  V.SetRandn();
2730  M.MulRowsVec(V);
2731  for (MatrixIndexT i = 0; i < dimM;i++)
2732  for (MatrixIndexT j = 0;j < dimN;j++)
2733  KALDI_ASSERT(M(i, j) - N(i, j)*V(i) < 0.0001);
2734  }
2735 
2736  {
2737  // now test scale_cols
2738  M.CopyFromMat(N); // make same.
2739  Vector<Real> V(dimN);
2740  V.SetRandn();
2741  M.MulColsVec(V);
2742  for (MatrixIndexT i = 0; i < dimM;i++)
2743  for (MatrixIndexT j = 0;j < dimN;j++)
2744  KALDI_ASSERT(M(i, j) - N(i, j)*V(j) < 0.0001);
2745  }
2746 
2747  }
2748 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestScaleDiag()

static void kaldi::UnitTestScaleDiag ( )
static

Definition at line 2842 of file matrix-lib-test.cc.

References AssertEqual(), rnnlm::i, Rand(), PackedMatrix< Real >::ScaleDiag(), and PackedMatrix< Real >::SetRandn().

2842  {
2843 
2844  MatrixIndexT N = 1 + Rand() % 10;
2845  SpMatrix<Real> S(N);
2846  S.SetRandn();
2847  SpMatrix<Real> S2(S);
2848  S.ScaleDiag(0.5);
2849  for (MatrixIndexT i = 0; i < N; i++) S2(i, i) *= 0.5;
2850  AssertEqual(S, S2);
2851 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSearch()

static void kaldi::UnitTestSearch ( )
static

Definition at line 289 of file pitch-functions-test.cc.

References AssertEqual(), ComputeKaldiPitch(), rnnlm::i, KALDI_LOG, M_2PI, rnnlm::n, PitchExtractionOptions::nccf_ballast_online, RandGauss(), and PitchExtractionOptions::samp_freq.

Referenced by UnitTestFeatNoKeele().

289  {
290  KALDI_LOG << "=== UnitTestSearch() ===\n";
291  for (int32 n = 0; n < 3; n++) {
292  // the parametrization object
294  op.nccf_ballast_online = true; // this is necessary for the computation
295  // to be identical regardless how many pieces we break the signal into.
296 
297  int32 size = 1000 + rand() % 1000;
298 
299  Vector<BaseFloat> v(size);
300  // init with noise plus a sine-wave whose frequency is changing randomly.
301 
302  double cur_freq = 200.0, normalized_time = 0.0;
303 
304  for (int32 i = 0; i < size; i++) {
305  v(i) = RandGauss() + cos(normalized_time * M_2PI);
306  cur_freq += RandGauss(); // let the frequency wander a little.
307  if (cur_freq < 100.0) cur_freq = 100.0;
308  if (cur_freq > 300.0) cur_freq = 300.0;
309  normalized_time += cur_freq / op.samp_freq;
310  }
311 
313  ComputeKaldiPitch(op, v, &m1);
314 
315  pitch_use_naive_search = true;
316 
318  ComputeKaldiPitch(op, v, &m2);
319 
320  pitch_use_naive_search = false;
321 
322  AssertEqual(m1, m2, 1.0e-08); // should be identical.
323  }
324  KALDI_LOG << "Test passed :)\n";
325 }
void ComputeKaldiPitch(const PitchExtractionOptions &opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function extracts (pitch, NCCF) per frame, using the pitch extraction method described in "A Pit...
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
struct rnnlm::@11::@12 n
bool pitch_use_naive_search
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define M_2PI
Definition: kaldi-math.h:52
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSetDiag()

static void kaldi::UnitTestSetDiag ( )
static

Definition at line 2854 of file matrix-lib-test.cc.

References AssertEqual(), Rand(), and PackedMatrix< Real >::SetDiag().

2854  {
2855 
2856  MatrixIndexT N = 1 + Rand() % 10;
2857  SpMatrix<Real> S(N), T(N);
2858  S.SetUnit();
2859  S.ScaleDiag(0.5);
2860  T.SetDiag(0.5);
2861  AssertEqual(S, T);
2862 
2863 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSetRandn()

static void kaldi::UnitTestSetRandn ( )
static

Definition at line 449 of file matrix-lib-test.cc.

References MatrixBase< Real >::ApplyPow(), DoubleFactorial(), rnnlm::i, KALDI_ASSERT, Rand(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::Sum().

449  {
450  for (MatrixIndexT i = 0; i < 5; i++) {
451  MatrixIndexT rows = 100 + Rand() % 50, cols = 100 + Rand() % 50;
452  Matrix<Real> M(rows, cols);
453  M.SetRandn();
454 
455  for (MatrixIndexT pow = 1; pow < 5; pow++) {
456  // test moments 1 through 4 of
457  // the distribution.
458  Matrix<Real> Mpow(M);
459  Mpow.ApplyPow(pow);
460  Real observed_moment = Mpow.Sum() / (rows * cols);
461  // see http://en.wikipedia.org/wiki/Normal_distribution#Moments,
462  // note that mu = 0 and sigma = 1.
463  Real expected_moment = (pow % 2 == 1 ? 0 : DoubleFactorial(pow - 1));
464  Real k = 10.0; // This is just a constant we use to give us some wiggle
465  // room before rejecting the distribution... e.g. 10 sigma,
466  // quite approximately.
467  Real allowed_deviation = k * pow / sqrt(static_cast<Real>(rows * cols));
468  // give it a bit more wiggle room for higher powers.. this is quite
469  // unscientific, it would be better to involve the absolute moments or
470  // something like that, and use one of those statistical inequalities,
471  // but it involves the gamma function and it's too much hassle to implement.
472  Real lower_bound = expected_moment - allowed_deviation,
473  upper_bound = expected_moment + allowed_deviation;
474  KALDI_ASSERT(observed_moment >= lower_bound && observed_moment <= upper_bound);
475  }
476  }
477 }
static int32 DoubleFactorial(int32 i)
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestSetRandUniform()

static void kaldi::UnitTestSetRandUniform ( )
static

Definition at line 481 of file matrix-lib-test.cc.

References MatrixBase< Real >::Add(), MatrixBase< Real >::ApplyPow(), VectorBase< Real >::Dim(), rnnlm::i, KALDI_ASSERT, Rand(), MatrixBase< Real >::SetRandUniform(), and MatrixBase< Real >::Sum().

481  {
482  for (MatrixIndexT i = 0; i < 5; i++) {
483  MatrixIndexT rows = 200 + Rand() % 50, cols = 200 + Rand() % 50;
484  Matrix<Real> M(rows, cols);
485  M.SetRandUniform();
486 
487  M.Add(-0.5); // we'll be testing the central moments, so
488  // center it around zero first.
489  // Got these moments from http://mathworld.wolfram.com/UniformDistribution.html
490  Vector<Real> central_moments(5);
491  central_moments(0) = 0.0;
492  central_moments(1) = 0.0;
493  central_moments(2) = 1.0 / 12; // times (b - a)^2, which equals 1.
494  central_moments(3) = 0.0;
495  central_moments(4) = 1.0 / 80; // times (b - a)^4, which equals 1.
496 
497  for (MatrixIndexT pow = 1; pow < central_moments.Dim(); pow++) {
498  Matrix<Real> Mpow(M);
499  Mpow.ApplyPow(pow);
500  Real observed_moment = Mpow.Sum() / (rows * cols);
501  // see http://en.wikipedia.org/wiki/Normal_distribution#Moments,
502  // note that mu = 0 and sigma = 1.
503  Real expected_moment = central_moments(pow);
504  Real k = 10.0; // This is just a constant we use to give us some wiggle
505  // room before rejecting the distribution... e.g. 10 sigma,
506  // quite approximately.
507  Real allowed_deviation = k / sqrt(static_cast<Real>(rows * cols));
508  Real lower_bound = expected_moment - allowed_deviation,
509  upper_bound = expected_moment + allowed_deviation;
510  KALDI_ASSERT(observed_moment >= lower_bound && observed_moment <= upper_bound);
511  }
512  }
513 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestSetZeroAboveDiag()

static void kaldi::UnitTestSetZeroAboveDiag ( )
static

Definition at line 60 of file cu-test.cc.

References CuMatrixBase< Real >::CopyToMat(), rnnlm::i, rnnlm::j, KALDI_LOG, MatrixBase< Real >::SetRandn(), and CuMatrixBase< Real >::SetZeroAboveDiag().

60  {
61  for (MatrixIndexT i = 1; i < 10; i++) {
62  MatrixIndexT dim = 10 * i;
63  Matrix<Real> A(dim,dim);
64  A.SetRandn();
65  CuMatrix<Real> B(A);
66 
67  B.SetZeroAboveDiag();
68 
69  Real sum = 0.0;
70  for (MatrixIndexT i = 0; i < dim; i++) {
71  for (MatrixIndexT j = i + 1; j < dim; j++)
72  sum += A(i,j);
73  }
74 
75  KALDI_LOG << "the upper diaganoal sum for A is : " << sum;
76  B.CopyToMat(&A);
77  sum = 0.0;
78  for (MatrixIndexT i = 0; i < dim; i++) {
79  for (MatrixIndexT j = i + 1; j < dim; j++)
80  sum += A(i,j);
81  }
82  KALDI_LOG << "the upper diaganoal sum for B is : " << sum;
83  }
84 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSger()

static void kaldi::UnitTestSger ( )
static

Definition at line 1161 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddVecVec(), KALDI_ASSERT, rnnlm::n, Rand(), and VectorBase< Real >::SetRandn().

1161  {
1162  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1163  MatrixIndexT dimM = 10 + Rand() % 10;
1164  MatrixIndexT dimN = 10 + Rand() % 10;
1165  Matrix<Real> M(dimM, dimN), M2(dimM, dimN);
1166  Vector<Real> v1(dimM); v1.SetRandn();
1167  Vector<Real> v2(dimN); v2.SetRandn();
1168  Vector<double> v1d(v1), v2d(v2);
1169  M.AddVecVec(1.0f, v1, v2);
1170  M2.AddVecVec(1.0f, v1, v2);
1171  for (MatrixIndexT m = 0;m < dimM;m++)
1172  for (MatrixIndexT n = 0;n < dimN;n++) {
1173  KALDI_ASSERT(M(m, n) - v1(m)*v2(n) < 0.01);
1174  KALDI_ASSERT(M(m, n) - M2(m, n) < 0.01);
1175  }
1176  }
1177 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestSigmoid()

static void kaldi::UnitTestSigmoid ( )
static

Definition at line 2383 of file matrix-lib-test.cc.

References AssertEqual(), MatrixBase< Real >::DiffSigmoid(), Exp(), rnnlm::i, Rand(), and MatrixBase< Real >::Sigmoid().

2383  {
2384  for (MatrixIndexT i = 0; i < 10; i++) {
2385  MatrixIndexT dimM = 5 + Rand() % 10, dimN = 5 + Rand() % 10;
2386  Matrix<Real> M(dimM, dimN), P(dimM, dimN), Q(dimM, dimN), R(dimM, dimN);
2387  M.SetRandn();
2388  P.SetRandn();
2389  Matrix<Real> N(M);
2390  for(int32 r = 0; r < dimM; r++) {
2391  for (int32 c = 0; c < dimN; c++) {
2392  Real x = N(r, c),
2393  y = 1.0 / (1 + Exp(-x));
2394  N(r, c) = y;
2395  Real out_diff = P(r, c), in_diff = out_diff * y * (1.0 - y);
2396  Q(r, c) = in_diff;
2397  }
2398  }
2399  M.Sigmoid(M);
2400  R.DiffSigmoid(N, P);
2401  AssertEqual(M, N);
2402  AssertEqual(Q, R);
2403  }
2404 }
double Exp(double x)
Definition: kaldi-math.h:83
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSimple() [1/2]

static void kaldi::UnitTestSimple ( )
static

Definition at line 52 of file pitch-functions-test.cc.

References ComputeAndProcessKaldiPitch(), VectorBase< Real >::Dim(), rnnlm::i, and KALDI_LOG.

52  {
53  KALDI_LOG << "=== UnitTestSimple() ===";
54  Vector<BaseFloat> v(1000);
55  Matrix<BaseFloat> m1, m2;
56  // init with noise
57  for (int32 i = 0; i < v.Dim(); i++) {
58  v(i) = (abs(i * 433024253) % 65535) - (65535 / 2);
59  }
60  KALDI_LOG << "<<<=== Just make sure it runs... Nothing is compared";
61  // trying to compute and process pitch with same opts as baseline.
64  ComputeAndProcessKaldiPitch(op1, op2, v, &m1);
65  KALDI_LOG << "Test passed :)";
66 }
kaldi::int32 int32
void ComputeAndProcessKaldiPitch(const PitchExtractionOptions &pitch_opts, const ProcessPitchOptions &process_opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function combines ComputeKaldiPitch and ProcessPitch.
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSimple() [2/2]

static void kaldi::UnitTestSimple ( )
static

Definition at line 2427 of file matrix-lib-test.cc.

References MatrixBase< Real >::ApplyExp(), VectorBase< Real >::ApplyLogAndCopy(), AssertEqual(), VectorBase< Real >::Dim(), Exp(), rnnlm::i, MatrixBase< Real >::IsDiagonal(), MatrixBase< Real >::IsSymmetric(), MatrixBase< Real >::IsUnit(), MatrixBase< Real >::IsZero(), rnnlm::j, KALDI_ASSERT, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::SetUnit(), and MatrixBase< Real >::SetZero().

Referenced by UnitTestFeat(), and UnitTestFeatNoKeele().

2427  {
2428  for (MatrixIndexT i = 0;i < 5;i++) {
2429  MatrixIndexT dimM = 20 + Rand()%10, dimN = 20 + Rand()%20;
2430  Matrix<Real> M(dimM, dimN);
2431  M.SetUnit();
2432  KALDI_ASSERT(M.IsUnit());
2433  KALDI_ASSERT(!M.IsZero());
2434  KALDI_ASSERT(M.IsDiagonal());
2435 
2436  SpMatrix<Real> S(dimM);
2437  S.SetRandn();
2438  Matrix<Real> N(S);
2439  KALDI_ASSERT(!N.IsDiagonal()); // technically could be diagonal, but almost infinitely unlikely.
2440  KALDI_ASSERT(N.IsSymmetric());
2441  KALDI_ASSERT(!N.IsUnit());
2442  KALDI_ASSERT(!N.IsZero());
2443 
2444  M.SetZero();
2445  KALDI_ASSERT(M.IsZero());
2446  Vector<Real> V(dimM*dimN);
2447  V.SetRandn();
2448  Vector<Real> V2(V), V3(dimM*dimN);
2449  V2.ApplyExp();
2450  AssertEqual(V.Sum(), V2.SumLog());
2451  V3.ApplyLogAndCopy(V2);
2452  V2.ApplyLog();
2453  AssertEqual(V, V2);
2454  AssertEqual(V3, V2);
2455 
2456  {
2457  Vector<Real> V2(V);
2458  for (MatrixIndexT i = 0; i < V2.Dim(); i++)
2459  V2(i) = Exp(V2(i));
2460  V.ApplyExp();
2461  AssertEqual(V, V2);
2462  }
2463  {
2464  Matrix<Real> N2(N), N3(N);
2465  for (MatrixIndexT i = 0; i < N.NumRows(); i++)
2466  for (MatrixIndexT j = 0; j < N.NumCols(); j++)
2467  N2(i, j) = Exp(N2(i, j));
2468  N3.ApplyExp();
2469  AssertEqual(N2, N3);
2470  }
2471  KALDI_ASSERT(!S.IsDiagonal());
2472  KALDI_ASSERT(!S.IsUnit());
2473  N.SetUnit();
2474  S.CopyFromMat(N);
2475  KALDI_ASSERT(S.IsDiagonal());
2476  KALDI_ASSERT(S.IsUnit());
2477  N.SetZero();
2478  S.CopyFromMat(N);
2479  KALDI_ASSERT(S.IsZero());
2480  KALDI_ASSERT(S.IsDiagonal());
2481  }
2482 }
double Exp(double x)
Definition: kaldi-math.h:83
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSimpleForMat()

static void kaldi::UnitTestSimpleForMat ( )
static

Definition at line 878 of file matrix-lib-test.cc.

References MatrixBase< Real >::Add(), SpMatrix< Real >::AddVec2(), MatrixBase< Real >::ApplySoftMax(), AssertEqual(), VectorBase< Real >::Data(), rnnlm::i, InitRandNonsingular(), rnnlm::j, KALDI_ASSERT, MatrixBase< Real >::LogDet(), MatrixBase< Real >::LogSumExp(), MatrixBase< Real >::MulElements(), rnnlm::n, Rand(), MatrixBase< Real >::RowData(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), PackedMatrix< Real >::SetZero(), and MatrixBase< Real >::Sum().

878  { // test some simple operates on all kinds of matrix
879 
880  for (MatrixIndexT p = 0; p < 10; p++) {
881  // for FrobeniousNorm() function
882  MatrixIndexT dimM = 10 + Rand() % 10, dimN = 10 + Rand() % 10;
883  Matrix<Real> M(dimM, dimN);
884  M.SetRandn();
885  {
886  Matrix<Real> N(M);
887  Real a = M.LogSumExp(), b = N.ApplySoftMax();
888  AssertEqual(a, b);
889  AssertEqual(1.0, N.Sum());
890  }
891  {
892  Matrix<Real> N(M);
893  N.Add(2.0);
894  for (MatrixIndexT m = 0; m < dimM; m++)
895  for (MatrixIndexT n = 0; n < dimN; n++)
896  N(m, n) -= 2.0;
897  AssertEqual(M, N);
898  }
899 
900  Matrix<Real> N(M), M1(M);
901  M1.MulElements(M);
902  Real tmp1 = sqrt(M1.Sum());
903  Real tmp2 = N.FrobeniusNorm();
904  KALDI_ASSERT(std::abs(tmp1 - tmp2) < 0.00001);
905 
906  // for LargestAbsElem() function
907  Vector<Real> V(dimM);
908  for (MatrixIndexT i = 0; i < dimM; i++) {
909  for (MatrixIndexT j = 0; j < dimN; j++) {
910  M(i, j) = std::abs(M(i, j));
911  }
912  std::sort(M.RowData(i), M.RowData(i) + dimN);
913  V(i) = M(i, dimN - 1);
914  }
915  std::sort(V.Data(), V.Data() + dimM);
916  KALDI_ASSERT(std::abs(V(dimM - 1) - N.LargestAbsElem()) < 0.00001);
917  }
918 
919  SpMatrix<Real> x(3);
920  x.SetZero();
921 
922  std::stringstream ss;
923 
924  ss << "DP 3\n";
925  ss << "4.6863" << '\n';
926  ss << "3.7062 4.6032" << '\n';
927  ss << "3.4160 3.7256 5.2474" << '\n';
928 
929  ss >> x;
930  KALDI_ASSERT(x.IsPosDef() == true); // test IsPosDef() function
931 
932  TpMatrix<Real> y(3);
933  y.SetZero();
934  y.Cholesky(x);
935 
936 
937  // test sp-matrix's LogPosDefDet() function
938  Matrix<Real> B(x);
939  Real tmp;
940  Real *DetSign = &tmp;
941  KALDI_ASSERT(std::abs(B.LogDet(DetSign) - x.LogPosDefDet()) < 0.00001);
942 
943  for (MatrixIndexT p = 0; p < 10; p++) { // test for sp and tp matrix's AddSp() and AddTp() function
944  MatrixIndexT dimM = 10 + Rand() % 10;
945  SpMatrix<Real> S(dimM), S1(dimM);
946  TpMatrix<Real> T(dimM), T1(dimM);
947  S.SetRandn();
948  S1.SetRandn();
949  T.SetRandn();
950  T1.SetRandn();
951  Matrix<Real> M(S), M1(S1), N(T), N1(T1);
952 
953  S.AddSp(1.0, S1);
954  T.AddTp(1.0, T1);
955  M.AddMat(1.0, M1);
956  N.AddMat(1.0, N1);
957  Matrix<Real> S2(S);
958  Matrix<Real> T2(T);
959 
960  AssertEqual(S2, M);
961  AssertEqual(T2, N);
962  }
963 
964  for (MatrixIndexT i = 0; i < 10; i++) { // test for sp matrix's AddVec2() function
965  MatrixIndexT dimM = 10 + Rand() % 10;
966  SpMatrix<Real> M(dimM);
967  Vector<Real> V(dimM);
968 
970  SpMatrix<double> Md(M);
971  V.SetRandn();
972  SpMatrix<Real> Sorig(M);
973  M.AddVec2(0.5, V);
974  Md.AddVec2(static_cast<Real>(0.5), V);
975  for (MatrixIndexT i = 0; i < dimM; i++)
976  for (MatrixIndexT j = 0; j < dimM; j++) {
977  KALDI_ASSERT(std::abs(M(i, j) - (Sorig(i, j)+0.5*V(i)*V(j))) < 0.001);
978  KALDI_ASSERT(std::abs(Md(i, j) - (Sorig(i, j)+0.5*V(i)*V(j))) < 0.001);
979  }
980  }
981 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
struct rnnlm::@11::@12 n
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
static void InitRandNonsingular(SpMatrix< Real > *M)

◆ UnitTestSimpleForVec()

static void kaldi::UnitTestSimpleForVec ( )
static

Definition at line 517 of file matrix-lib-test.cc.

References VectorBase< Real >::AddColSumMat(), VectorBase< Real >::AddVecDivVec(), VectorBase< Real >::ApplyLogSoftMax(), AssertEqual(), VectorBase< Real >::CopyColFromMat(), VectorBase< Real >::CopyFromVec(), Exp(), rnnlm::i, VectorBase< Real >::IsZero(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, VectorBase< Real >::MulElements(), VectorBase< Real >::Norm(), Rand(), RandUniform(), VectorBase< Real >::Scale(), VectorBase< Real >::Set(), MatrixBase< Real >::SetRandn(), and VectorBase< Real >::Sum().

517  { // testing some simple operators on vector
518 
519  for (MatrixIndexT i = 0; i < 5; i++) {
520  Vector<Real> V(100), V1(100), V2(100), V3(100), V4(100);
521  V.SetRandn();
522  if (i % 2 == 0) {
523  V1.SetZero();
524  V1.Add(1.0);
525  } else {
526  V1.Set(1.0);
527  }
528 
529  V2.CopyFromVec(V);
530  V3.CopyFromVec(V1);
531  V2.InvertElements();
532  V3.DivElements(V);
533  V4.CopyFromVec(V3);
534  V4.AddVecDivVec(1.0, V1, V, 0.0);
535  AssertEqual(V3, V2);
536  AssertEqual(V4, V3);
537  V4.MulElements(V);
538  AssertEqual(V4, V1);
539  V3.AddVecVec(1.0, V, V2, 0.0);
540  AssertEqual(V3, V1);
541 
542  Vector<Real> V5(V), V6(V1), V7(V1), V8(V);
543  V5.AddVec(1.0, V);
544  V8.Scale(2.0);
545  V6.AddVec2(1.0, V);
546  V7.AddVecVec(1.0, V, V, 1.0);
547  AssertEqual(V6, V7);
548  AssertEqual(V5, V8);
549  }
550 
551  for (MatrixIndexT i = 0; i < 5; i++) {
552  std::vector<MatrixIndexT> sizes;
553  sizes.push_back(16);
554  sizes.push_back(128);
555  for(int i = 0; i < sizes.size(); i++) {
556  MatrixIndexT dimM = sizes[i] + Rand() % 10, dimN = sizes[i] + Rand() % 10;
557  Matrix<Real> M(dimM, dimN);
558  M.SetRandn();
559  Vector<Real> Vr(dimN), Vc(dimM);
560  Vr.AddRowSumMat(0.4, M);
561  Vr.AddRowSumMat(0.3, M, 0.5); // note: 0.3 + 0.4*0.5 = 0.5.
562  Vc.AddColSumMat(0.4, M);
563  Vc.AddColSumMat(0.3, M, 0.5); // note: 0.3 + 0.4*0.5 = 0.5.
564  Vr.Scale(2.0);
565  Vc.Scale(2.0);
566  KALDI_LOG << Vr;
567  KALDI_LOG << Vc;
568 
569  Vector<Real> V2r(dimN), V2c(dimM);
570  for (MatrixIndexT k = 0; k < dimM; k++) {
571  V2r.CopyRowFromMat(M, k);
572  KALDI_ASSERT(fabs(V2r.Sum() - Vc(k)) < 0.01);
573  }
574  for (MatrixIndexT j = 0; j < dimN; j++) {
575  V2c.CopyColFromMat(M, j);
576  KALDI_ASSERT(fabs(V2c.Sum() - Vr(j)) < 0.01);
577  }
578  }
579  }
580 
581  for (MatrixIndexT i = 0; i < 5; i++) {
582  Vector<Real> V(100), V1(100), V2(100);
583  V.SetRandn();
584 
585  V1.CopyFromVec(V);
586  V1.ApplyExp();
587  Real a = V.LogSumExp();
588  V2.Set(Exp(V.LogSumExp()));
589  V1.DivElements(V2);
590  V2.CopyFromVec(V);
591 
592  Real b = V.ApplySoftMax();
593  AssertEqual(V1, V);
594  AssertEqual(a, b);
595 
596  V.ApplyLog();
597  Real c = V2.ApplyLogSoftMax();
598  AssertEqual(V2, V);
599  AssertEqual(a, c);
600  }
601 
602  for (MatrixIndexT i = 0; i < 5; i++) {
603  MatrixIndexT dimV = 10 + Rand() % 10;
604  Real p = 0.5 + RandUniform() * 4.5;
605  Vector<Real> V(dimV), V1(dimV), V2(dimV);
606  V.SetRandn();
607  V1.AddVecVec(1.0, V, V, 0.0); // V1:=V.*V.
608  V2.CopyFromVec(V1);
609  AssertEqual(V1.Norm(p), V2.Norm(p));
610  AssertEqual(sqrt(V1.Sum()), V.Norm(2.0));
611  }
612 
613  for (MatrixIndexT i = 0; i < 5; i++) {
614  MatrixIndexT dimV = 10 + Rand() % 10;
615  Real p = RandUniform() * 1.0e-5;
616  Vector<Real> V(dimV);
617  V.Set(p);
618  KALDI_ASSERT(V.IsZero(p));
619  KALDI_ASSERT(!V.IsZero(p*0.9));
620  }
621 
622  // Test ApplySoftMax() for matrix.
623  Matrix<Real> M(10, 10);
624  M.SetRandn();
625  M.ApplySoftMax();
626  KALDI_ASSERT( fabs(1.0 - M.Sum()) < 0.01);
627 
628 }
double Exp(double x)
Definition: kaldi-math.h:83
float RandUniform(struct RandomState *state=NULL)
Returns a random number strictly between 0 and 1.
Definition: kaldi-math.h:151
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSimpleOptions()

void kaldi::UnitTestSimpleOptions ( )

Definition at line 24 of file simple-options-test.cc.

References SimpleOptions::GetOptionType(), KALDI_ASSERT, SimpleOptions::kInt32, SimpleOptions::Register(), and SimpleOptions::SetOption().

Referenced by main().

24  {
25  std::string str="default_for_str";
26  int32 num = 1;
27  uint32 unum = 2;
28  float realnum = 0.1;
29  bool flag = false;
30  bool rval;
31  SimpleOptions so;
32 
33  so.Register("num", &num, "Description of num");
34  so.Register("unum", &unum, "Description of unum");
35  so.Register("str", &str, "Description of str");
36  so.Register("flag", &flag, "Description of flag");
37  so.Register("realnum", &realnum, "Description of realnum");
38 
39  rval = so.SetOption("num", 42);
40  KALDI_ASSERT(rval);
41  so.SetOption("unum", static_cast<uint32>(43));
42  KALDI_ASSERT(rval);
43  rval = so.SetOption("str", (std::string)"foo");
44  KALDI_ASSERT(rval);
45  rval = so.SetOption("flag", false);
46  KALDI_ASSERT(rval);
47 
48  KALDI_ASSERT(num == 42);
49  KALDI_ASSERT(unum == 43);
50  KALDI_ASSERT(str == "foo");
51  KALDI_ASSERT(flag == false);
52 
53  rval = so.SetOption("str", "foo2");
54  KALDI_ASSERT(rval);
55  KALDI_ASSERT(str == "foo2");
56 
57  // test automatic conversion between int and uint
58  rval = so.SetOption("unum", 44);
59  KALDI_ASSERT(rval);
60  KALDI_ASSERT(unum == 44);
61 
62  // test automatic conversion between float and double
63  rval = so.SetOption("realnum", static_cast<float>(0.2));
64  KALDI_ASSERT(rval);
65  KALDI_ASSERT(realnum - 0.2 < 0.000001);
66  rval = so.SetOption("realnum", static_cast<double>(0.3));
67  KALDI_ASSERT(rval);
68  KALDI_ASSERT(realnum - 0.3 < 0.000001);
69 
71  rval = so.GetOptionType("num", &type);
72  KALDI_ASSERT(rval);
73  KALDI_ASSERT(type == SimpleOptions::kInt32);
74 
75  rval = so.GetOptionType("xxxx", &type);
76  KALDI_ASSERT(rval == false);
77 }
The class SimpleOptions is an implementation of OptionsItf that allows setting and getting option val...
kaldi::int32 int32
bool GetOptionType(const std::string &key, OptionType *type)
void Register(const std::string &name, bool *ptr, const std::string &doc)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
bool SetOption(const std::string &key, const bool &value)

◆ UnitTestSnipEdges()

static void kaldi::UnitTestSnipEdges ( )
static

Definition at line 71 of file pitch-functions-test.cc.

References ApproxEqual(), AssertEqual(), ComputeAndProcessKaldiPitch(), VectorBase< Real >::CopyColFromMat(), WaveData::Data(), PitchExtractionOptions::frame_length_ms, PitchExtractionOptions::frame_shift_ms, KALDI_ASSERT, KALDI_ERR, KALDI_LOG, KALDI_WARN, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), WaveData::Read(), WaveData::SampFreq(), PitchExtractionOptions::snip_edges, and VecVec().

Referenced by UnitTestFeatNoKeele().

71  {
72  KALDI_LOG << "=== UnitTestSnipEdges() ===\n";
73  PitchExtractionOptions op_SnipEdges, op_NoSnipEdges;
74  Matrix<BaseFloat> m1, m2;
76  int nbad = 0;
77 
78  // Load test wave file
79  WaveData wave;
80  {
81  std::ifstream is("test_data/test.wav");
82  wave.Read(is);
83  }
84  KALDI_ASSERT(wave.Data().NumRows() == 1);
85  SubVector<BaseFloat> waveform(wave.Data(), 0);
86 
87  // Process files with snip edge enabled or disabled, on various
88  // frame shifts and frame lengths
89  for (int fs = 4; fs <= 10; fs += 2) {
90  for (int wl = 20; wl <= 100; wl += 20) {
91  // Rather dirty way to round, but works fine
92  int32 ms_fs = (int32)(wave.SampFreq() * 0.001 * fs + 0.5);
93  int32 ms_wl = (int32)(wave.SampFreq() * 0.001 * wl + 0.5);
94  op_SnipEdges.snip_edges = true;
95  op_SnipEdges.frame_shift_ms = fs;
96  op_SnipEdges.frame_length_ms = wl;
97  op_NoSnipEdges.snip_edges = false;
98  op_NoSnipEdges.frame_shift_ms = fs;
99  op_NoSnipEdges.frame_length_ms = wl;
100  ComputeAndProcessKaldiPitch(op_SnipEdges, opp, waveform, &m1);
101  ComputeAndProcessKaldiPitch(op_NoSnipEdges, opp, waveform, &m2);
102 
103  // Check the output differ in a predictable manner:
104  // 1. The length of the output should only depend on the window size & window shift
105  KALDI_LOG << "Output: " << m1.NumRows() << " ; " << m2.NumRows();
106  // - with snip edges disabled, depends on file size and frame shift only */
107  AssertEqual(m2.NumRows(), ((int)(wave.Data().NumCols() + ms_fs / 2)) / ms_fs);
108  // - with snip edges disabled, depend on file size, frame shift, frame length */
109  AssertEqual(m1.NumRows(), ((int)(wave.Data().NumCols() - ms_wl + ms_fs)) / ms_fs);
110  // 2. The signal should be delayed in a predictable manner
111  Vector<BaseFloat> f0_1(m1.NumRows());
112  f0_1.CopyColFromMat(m1, 1);
113  Vector<BaseFloat> f0_2(m2.NumRows());
114  f0_2.CopyColFromMat(m2, 1);
115 
116  BaseFloat bcorr = -1;
117  int32 blag = -1;
118  int32 max_lag = wl / fs * 2;
119  int num_frames_f0 = m1.NumRows() - max_lag;
120 
121  /* Looks for the best correlation between the output signals,
122  identify the lag, compares it with theoretical value */
123  SubVector<BaseFloat> sub_vec1(f0_1, 0, num_frames_f0);
124  for (int32 lag = 0; lag < max_lag + 1; lag++) {
125  SubVector<BaseFloat> sub_vec2(f0_2, lag, num_frames_f0);
126  BaseFloat corr = VecVec(sub_vec1, sub_vec2);
127  if (corr > bcorr) {
128  bcorr = corr;
129  blag = lag;
130  }
131  }
132  KALDI_LOG << "Best lag: " << blag * fs << "ms with value: " << bcorr <<
133  "; expected lag: " << wl / 2 + 10 - fs / 2 << " ± " << fs;
134  // BP: the lag should in theory be equal to wl / 2 - fs / 2, but it seems
135  // to be: wl / 2 + 10 - fs / 2! It appears the 10 ms comes from the nccf_lag which
136  // is 82 samples with the default settings => nccf_lag / resample_freq / 2 => 10.25ms
137  // We should really be using the full_frame_length of the algorithm for accurate results,
138  // but there is no method to obtain it (and it is potentially variable), so that makes
139  // the pitch value *with snip edge* particularly unreliable.
140  if (!ApproxEqual(blag * fs, (BaseFloat)(wl / 2 + 10 - fs / 2), (BaseFloat)fs / wl)) {
141  KALDI_WARN << "Bad lag for window size " << wl << " and frame shift " << fs;
142  nbad++;
143  }
144  /*AssertEqual(blag * fs, (BaseFloat)(wl / 2 + 10 - fs / 2), (BaseFloat)fs / wl);*/
145  }
146  }
147  /* If more than 10% of tests fail, crash */
148  if (nbad > 9) KALDI_ERR << "Too many bad lags: " << nbad;
149 
150 }
void Read(std::istream &is)
Read() will throw on error.
Definition: wave-reader.cc:272
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
BaseFloat SampFreq() const
Definition: wave-reader.h:126
const Matrix< BaseFloat > & Data() const
Definition: wave-reader.h:124
float BaseFloat
Definition: kaldi-types.h:29
void ComputeAndProcessKaldiPitch(const PitchExtractionOptions &pitch_opts, const ProcessPitchOptions &process_opts, const VectorBase< BaseFloat > &wave, Matrix< BaseFloat > *output)
This function combines ComputeKaldiPitch and ProcessPitch.
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
void CopyColFromMat(const MatrixBase< OtherReal > &M, MatrixIndexT col)
Extracts a column of the matrix M.
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestSoftHinge()

static void kaldi::UnitTestSoftHinge ( )
static

Definition at line 2406 of file matrix-lib-test.cc.

References AssertEqual(), Exp(), rnnlm::i, Log1p(), Rand(), and MatrixBase< Real >::SoftHinge().

2406  {
2407  for (MatrixIndexT i = 0; i < 10; i++) {
2408  MatrixIndexT dimM = 5 + Rand() % 10, dimN = 5 + Rand() % 10;
2409  Matrix<Real> M(dimM, dimN), N(dimM, dimN), O(dimM, dimN);
2410  M.SetRandn();
2411  M.Scale(20.0);
2412 
2413  for(int32 r = 0; r < dimM; r++) {
2414  for (int32 c = 0; c < dimN; c++) {
2415  Real x = M(r, c);
2416  Real &y = N(r, c);
2417  if (x > 10.0) y = x;
2418  else y = Log1p(Exp(x));
2419  }
2420  }
2421  O.SoftHinge(M);
2422  AssertEqual(N, O);
2423  }
2424 }
double Exp(double x)
Definition: kaldi-math.h:83
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
double Log1p(double x)
Definition: kaldi-math.h:104

◆ UnitTestSolve()

static void kaldi::UnitTestSolve ( )
static

Definition at line 3017 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::AddMatSp(), VectorBase< Real >::AddSpVec(), AssertEqual(), SolverOptions::diagonal_precondition, rnnlm::i, SpMatrix< Real >::Invert(), KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, SolverOptions::optimize_delta, Rand(), RandPosdefSpMatrix(), VectorBase< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), SolveDoubleQuadraticMatrixProblem(), SolveQuadraticMatrixProblem(), SolveQuadraticProblem(), TraceMatMat(), TraceMatSpMat(), TraceMatSpMatSp(), VecSpVec(), and VecVec().

3017  {
3018 
3019  for (MatrixIndexT i = 0;i < 5;i++) {
3020  MatrixIndexT dimM = (Rand()%10) + 10;
3021  MatrixIndexT dimN = dimM - (Rand()%3); // slightly lower-dim.
3022 
3023  SpMatrix<Real> H(dimM);
3024  Matrix<Real> M(dimM, dimN);
3025  M.SetRandn();
3026  H.AddMat2(1.0, M, kNoTrans, 0.0); // H = M M^T
3027 
3028  Vector<Real> x(dimM);
3029  x.SetRandn();
3030  Vector<Real> tmp(dimM);
3031  tmp.SetRandn();
3032  Vector<Real> g(dimM);
3033  g.AddSpVec(1.0, H, tmp, 0.0); // Limit to subspace that H is in.
3034  Vector<Real> x2(x), x3(x);
3035  SolverOptions opts2, opts3;
3036  opts2.diagonal_precondition = Rand() % 2;
3037  opts2.optimize_delta = Rand() % 2;
3038  opts3.diagonal_precondition = Rand() % 2;
3039  opts3.optimize_delta = Rand() % 2;
3040 
3041  double ans2 = SolveQuadraticProblem(H, g, opts2, &x2),
3042  ans3 = SolveQuadraticProblem(H, g, opts3, &x3);
3043 
3044  double observed_impr2 = (VecVec(x2, g) -0.5* VecSpVec(x2, H, x2)) -
3045  (VecVec(x, g) -0.5* VecSpVec(x, H, x)),
3046  observed_impr3 = (VecVec(x3, g) -0.5* VecSpVec(x3, H, x3)) -
3047  (VecVec(x, g) -0.5* VecSpVec(x, H, x));
3048  AssertEqual(observed_impr2, ans2);
3049  AssertEqual(observed_impr3, ans3);
3050  KALDI_ASSERT(ans2 >= 0);
3051  KALDI_ASSERT(ans3 >= 0);
3052  KALDI_ASSERT(std::abs(ans2 - ans3) / std::max(ans2, ans3) < 0.01);
3053  //AssertEqual(x2, x3);
3054  //AssertEqual(ans1, ans2);
3055  }
3056 
3057 
3058  for (MatrixIndexT i = 0; i < 5; i++) {
3059  MatrixIndexT dimM = (Rand() % 10) + 10;
3060  MatrixIndexT dimN = dimM - (Rand() % 3); // slightly lower-dim.
3061  MatrixIndexT dimO = (Rand() % 10) + 10;
3062 
3063  SpMatrix<Real> Q(dimM), SigmaInv(dimO);
3064  Matrix<Real> Mtmp(dimM, dimN);
3065  Mtmp.SetRandn();
3066  Q.AddMat2(1.0, Mtmp, kNoTrans, 0.0); // H = M M^T
3067 
3068  Matrix<Real> Ntmp(dimO, dimN);
3069  Ntmp.SetRandn();
3070  SigmaInv.AddMat2(1.0, Ntmp, kNoTrans, 0.0); // H = M M^T
3071 
3072  Matrix<Real> M(dimO, dimM), Y(dimO, dimM);
3073  M.SetRandn();
3074  Y.SetRandn();
3075 
3076  Matrix<Real> M2(M);
3077 
3078  SpMatrix<Real> Qinv(Q);
3079  if (Q.Cond() < 1000.0) Qinv.Invert();
3080 
3081  SolverOptions opts;
3082  opts.optimize_delta = Rand() % 2;
3083  opts.diagonal_precondition = Rand() % 2;
3084  double ans = SolveQuadraticMatrixProblem(Q, Y, SigmaInv, opts, &M2);
3085 
3086  Matrix<Real> M3(M);
3087  M3.AddMatSp(1.0, Y, kNoTrans, Qinv, 0.0);
3088  if (Q.Cond() < 1000.0) {
3089  AssertEqual(M2, M3); // This equality only holds if SigmaInv full-rank,
3090  // which is overwhelmingly likely if dimO > dimM
3091  }
3092 
3093  {
3094  Real a1 = TraceMatSpMat(M2, kTrans, SigmaInv, Y, kNoTrans),
3095  a2 = TraceMatSpMatSp(M2, kNoTrans, Q, M2, kTrans, SigmaInv),
3096  b1 = TraceMatSpMat(M, kTrans, SigmaInv, Y, kNoTrans),
3097  b2 = TraceMatSpMatSp(M, kNoTrans, Q, M, kTrans, SigmaInv),
3098  a3 = a1 - 0.5 * a2,
3099  b3 = b1 - 0.5 * b2;
3100  KALDI_ASSERT(a3 >= b3);
3101  AssertEqual(a3 - b3, ans);
3102  // KALDI_LOG << "a3 = " << a3 << ", b3 = " << b3 << ", c3 = " << c3;
3103  } // Check objf not decreased.
3104  }
3105 
3106  for (MatrixIndexT i = 0; i < 5; i++) {
3107  MatrixIndexT dimM = (Rand() % 10) + 10;
3108  MatrixIndexT dimO = (Rand() % 10) + 10;
3109 
3110  SpMatrix<Real> Q1(dimM), Q2(dimM), P1(dimO), P2(dimO);
3111  RandPosdefSpMatrix(dimM, &Q1);
3112  RandPosdefSpMatrix(dimM, &Q2);
3113  RandPosdefSpMatrix(dimO, &P1);
3114  RandPosdefSpMatrix(dimO, &P1);
3115 
3116  Matrix<Real> M(dimO, dimM), G(dimO, dimM);
3117  M.SetRandn();
3118  G.SetRandn();
3119  // InitRandNonsingular(&M);
3120  // InitRandNonsingular(&G);
3121 
3122  Matrix<Real> M2(M);
3123 
3124  SolverOptions opts;
3125  opts.optimize_delta = Rand() % 2;
3126  SolveDoubleQuadraticMatrixProblem(G, P1, P2, Q1, Q2, opts, &M2);
3127 
3128  {
3129  Real a1 = TraceMatMat(M2, G, kTrans),
3130  a2 = TraceMatSpMatSp(M2, kNoTrans, Q1, M2, kTrans, P1),
3131  a3 = TraceMatSpMatSp(M2, kNoTrans, Q2, M2, kTrans, P2),
3132  b1 = TraceMatMat(M, G, kTrans),
3133  b2 = TraceMatSpMatSp(M, kNoTrans, Q1, M, kTrans, P1),
3134  b3 = TraceMatSpMatSp(M, kNoTrans, Q2, M, kTrans, P2),
3135  a4 = a1 - 0.5 * a2 - 0.5 * a3,
3136  b4 = b1 - 0.5 * b2 - 0.5 * b3;
3137  KALDI_LOG << "a4 = " << a4 << ", b4 = " << b4;
3138  KALDI_ASSERT(a4 >= b4);
3139  } // Check objf not decreased.
3140  }
3141 }
Packed symetric matrix class.
Definition: matrix-common.h:62
This class describes the options for maximizing various quadratic objective functions.
Definition: sp-matrix.h:443
double SolveQuadraticProblem(const SpMatrix< double > &H, const VectorBase< double > &g, const SolverOptions &opts, VectorBase< double > *x)
Definition: sp-matrix.cc:635
Real SolveQuadraticMatrixProblem(const SpMatrix< Real > &Q, const MatrixBase< Real > &Y, const SpMatrix< Real > &SigmaInv, const SolverOptions &opts, MatrixBase< Real > *M)
Maximizes the auxiliary function : Like a numerically stable version of .
Definition: sp-matrix.cc:729
A class for storing matrices.
Definition: kaldi-matrix.h:823
Real SolveDoubleQuadraticMatrixProblem(const MatrixBase< Real > &G, const SpMatrix< Real > &P1, const SpMatrix< Real > &P2, const SpMatrix< Real > &Q1, const SpMatrix< Real > &Q2, const SolverOptions &opts, MatrixBase< Real > *M)
Maximizes the auxiliary function : Encountered in matrix update with a prior.
Definition: sp-matrix.cc:827
int32 MatrixIndexT
Definition: matrix-common.h:98
Real TraceMatSpMat(const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const MatrixBase< Real > &C, MatrixTransposeType transC)
Returns tr(A B C) (A and C may be transposed as specified by transA and transC).
Definition: sp-matrix.cc:415
Real VecSpVec(const VectorBase< Real > &v1, const SpMatrix< Real > &M, const VectorBase< Real > &v2)
Computes v1^T * M * v2.
Definition: sp-matrix.cc:964
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Real TraceMatSpMatSp(const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const MatrixBase< Real > &C, MatrixTransposeType transC, const SpMatrix< Real > &D)
Returns tr (A B C D) (A and C may be transposed as specified by transA and transB).
Definition: sp-matrix.cc:438
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37
void RandPosdefSpMatrix(size_t dim, SpMatrix< BaseFloat > *matrix, TpMatrix< BaseFloat > *matrix_sqrt=NULL, BaseFloat *logdet=NULL)

◆ UnitTestSpAddDiagVec()

static void kaldi::UnitTestSpAddDiagVec ( )
static

Definition at line 279 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddDiagVec(), AssertEqual(), rnnlm::i, Rand(), VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

279  {
280  for (MatrixIndexT i = 0;i< 10;i++) {
281  BaseFloat alpha = (i<5 ? 1.0 : 0.5);
282  MatrixIndexT dimM = 10+Rand()%10;
283  SpMatrix<Real> S(dimM);
284  S.SetRandn();
285  SpMatrix<Real> T(S);
286  Vector<OtherReal> v(dimM);
287  v.SetRandn();
288  S.AddDiagVec(alpha, v);
289  for (MatrixIndexT i = 0; i < dimM; i++)
290  T(i, i) += alpha * v(i);
291  AssertEqual(S, T);
292  }
293 }
Packed symetric matrix class.
Definition: matrix-common.h:62
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSpAddVecVec()

static void kaldi::UnitTestSpAddVecVec ( )
static

Definition at line 297 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddVecVec(), MatrixBase< Real >::AddVecVec(), AssertEqual(), rnnlm::i, Rand(), VectorBase< Real >::SetRandn(), and PackedMatrix< Real >::SetRandn().

297  {
298  for (MatrixIndexT i = 0;i< 10;i++) {
299  BaseFloat alpha = (i<5 ? 1.0 : 0.5);
300  MatrixIndexT dimM = 10+Rand()%10;
301  SpMatrix<Real> S(dimM);
302  S.SetRandn();
303  Matrix<Real> T(S);
304 
305  Vector<Real> v(dimM), w(dimM);
306  v.SetRandn();
307  w.SetRandn();
308  S.AddVecVec(alpha, v, w);
309  T.AddVecVec(alpha, v, w);
310  T.AddVecVec(alpha, w, v);
311  Matrix<Real> U(S);
312  AssertEqual(U, T);
313  }
314 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSparseMatrixAddToMat()

void kaldi::UnitTestSparseMatrixAddToMat ( )

Definition at line 152 of file sparse-matrix-test.cc.

References MatrixBase< Real >::AddMat(), SparseMatrix< Real >::AddToMat(), AssertEqual(), SparseMatrix< Real >::CopyToMat(), rnnlm::i, Rand(), MatrixBase< Real >::SetRandn(), and SparseMatrix< Real >::SetRandn().

152  {
153  for (int32 i = 0; i < 10; i++) {
154  MatrixIndexT row = 10 + Rand() % 40;
155  MatrixIndexT col = 10 + Rand() % 50;
156 
157  SparseMatrix<Real> smat(row, col);
158  smat.SetRandn(0.8);
159 
160  Matrix<Real> mat(row, col);
161  mat.SetRandn();
162  smat.CopyToMat(&mat);
163 
164  Matrix<Real> other_mat1(row, col);
165  other_mat1.SetRandn();
166  Matrix<Real> other_mat2 = other_mat1;
167 
168  smat.AddToMat(0.7, &other_mat1);
169  other_mat2.AddMat(0.7, mat);
170  AssertEqual(other_mat1, other_mat2, 0.00001);
171  }
172 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSparseMatrixConstructor()

void kaldi::UnitTestSparseMatrixConstructor ( )

Definition at line 175 of file sparse-matrix-test.cc.

References AssertEqual(), SparseMatrix< Real >::CopyToMat(), RandGauss(), RandInt(), and MatrixBase< Real >::SetRandn().

175  {
176  int32 num_rows = RandInt(1, 10),
177  num_cols = RandInt(0, 10);
178  if (num_cols == 0)
179  num_rows = 0;
180 
181  Matrix<Real> mat(num_rows, num_cols);
182 
183  for (int32 r = 0; r < num_rows; r++) {
184  for (int32 c = 0; c < num_cols; c++) {
185  if (RandInt(0, 5) == 0)
186  mat(r, c) = RandGauss();
187  }
188  }
189  SparseMatrix<Real> smat(mat);
190 
191  Matrix<Real> mat2(num_rows, num_cols);
192  mat2.SetRandn();
193  smat.CopyToMat(&mat2);
194  AssertEqual(mat, mat2);
195 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
kaldi::int32 int32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestSparseMatrixFrobeniusNorm()

void kaldi::UnitTestSparseMatrixFrobeniusNorm ( )

Definition at line 133 of file sparse-matrix-test.cc.

References AssertEqual(), SparseMatrix< Real >::CopyToMat(), SparseMatrix< Real >::FrobeniusNorm(), MatrixBase< Real >::FrobeniusNorm(), rnnlm::i, Rand(), MatrixBase< Real >::SetRandn(), and SparseMatrix< Real >::SetRandn().

133  {
134  for (int32 i = 0; i < 10; i++) {
135  MatrixIndexT row = 10 + Rand() % 40;
136  MatrixIndexT col = 10 + Rand() % 50;
137 
138  SparseMatrix<Real> smat(row, col);
139  smat.SetRandn(0.8);
140 
141  Matrix<Real> mat(row, col);
142  mat.SetRandn();
143  smat.CopyToMat(&mat);
144 
145  Real norm1 = smat.FrobeniusNorm();
146  Real norm2 = mat.FrobeniusNorm();
147  AssertEqual(norm1, norm2, 0.00001);
148  }
149 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSparseMatrixSum()

void kaldi::UnitTestSparseMatrixSum ( )

Definition at line 114 of file sparse-matrix-test.cc.

References AssertEqual(), SparseMatrix< Real >::CopyToMat(), rnnlm::i, Rand(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), SparseMatrix< Real >::Sum(), and MatrixBase< Real >::Sum().

114  {
115  for (int32 i = 0; i < 10; i++) {
116  MatrixIndexT row = 10 + Rand() % 40;
117  MatrixIndexT col = 10 + Rand() % 50;
118 
119  SparseMatrix<Real> smat(row, col);
120  smat.SetRandn(0.8);
121 
122  Matrix<Real> mat(row, col);
123  mat.SetRandn();
124  smat.CopyToMat(&mat);
125 
126  Real sum1 = smat.Sum();
127  Real sum2 = mat.Sum();
128  AssertEqual(sum1, sum2, 0.00001);
129  }
130 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSparseMatrixTraceMatSmat()

void kaldi::UnitTestSparseMatrixTraceMatSmat ( )

Definition at line 198 of file sparse-matrix-test.cc.

References AssertEqual(), SparseMatrix< Real >::CopyToMat(), rnnlm::i, kNoTrans, kTrans, Rand(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), TraceMatMat(), and TraceMatSmat().

198  {
199  for (int32 i = 0; i < 10; i++) {
200  MatrixIndexT row = 10 + Rand() % 40;
201  MatrixIndexT col = 10 + Rand() % 50;
202 
203  Matrix<Real> mat1(row, col);
204  Matrix<Real> mat2(col, row);
205  Matrix<Real> mat3(row, col);
206  mat1.SetRandn();
207  mat2.SetRandn();
208  mat3.SetRandn();
209 
210  SparseMatrix<Real> smat1(row, col);
211  SparseMatrix<Real> smat2(col, row);
212  smat1.SetRandn(0.8);
213  smat2.SetRandn(0.8);
214 
215  smat1.CopyToMat(&mat1);
216  smat2.CopyToMat(&mat2);
217 
218  Real trace1 = TraceMatMat(mat3, mat1, kTrans);
219  Real trace2 = TraceMatSmat(mat3, smat1, kTrans);
220  AssertEqual(trace1, trace2, 0.00001);
221 
222  trace1 = TraceMatMat(mat3, mat2, kNoTrans);
223  trace2 = TraceMatSmat(mat3, smat2, kNoTrans);
224  AssertEqual(trace1, trace2, 0.00001);
225  }
226 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Real TraceMatSmat(const MatrixBase< Real > &A, const SparseMatrix< Real > &B, MatrixTransposeType trans)

◆ UnitTestSparseVectorAddToVec()

void kaldi::UnitTestSparseVectorAddToVec ( )

Definition at line 44 of file sparse-matrix-test.cc.

References SparseVector< Real >::AddToVec(), VectorBase< Real >::AddVec(), AssertEqual(), SparseVector< Real >::CopyElementsToVec(), rnnlm::i, Rand(), VectorBase< Real >::SetRandn(), and SparseVector< Real >::SetRandn().

44  {
45  for (int32 i = 0; i < 10; i++) {
46  MatrixIndexT dim = 10 + Rand() % 40;
47 
48  SparseVector<Real> svec(dim);
49  svec.SetRandn(0.8);
50 
51  Vector<Real> vec(dim);
52  vec.SetRandn();
53  svec.CopyElementsToVec(&vec);
54 
55  Vector<Real> other_vec1(dim);
56  other_vec1.SetRandn();
57  Vector<Real> other_vec2 = other_vec1;
58 
59  svec.AddToVec(0.7, &other_vec1);
60  other_vec2.AddVec(0.7, vec);
61  AssertEqual(other_vec1, other_vec2, 0.00001);
62  }
63 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSparseVectorMax()

void kaldi::UnitTestSparseVectorMax ( )

Definition at line 66 of file sparse-matrix-test.cc.

References AssertEqual(), SparseVector< Real >::CopyElementsToVec(), rnnlm::i, SparseVector< Real >::Max(), VectorBase< Real >::Max(), Rand(), RandInt(), VectorBase< Real >::SetRandn(), and SparseVector< Real >::SetRandn().

66  {
67  for (int32 i = 0; i < 10; i++) {
68  MatrixIndexT dim = 10 + Rand() % 40;
69  if (RandInt(0, 3) == 0)
70  dim = RandInt(1, 5);
71 
72  SparseVector<Real> svec(dim);
73  if (RandInt(0, 3) != 0)
74  svec.SetRandn(0.8);
75 
76  Vector<Real> vec(dim);
77  vec.SetRandn();
78  svec.CopyElementsToVec(&vec);
79 
80  int32 index1, index2;
81  Real max1, max2;
82 
83  max1 = svec.Max(&index1);
84  max2 = vec.Max(&index2);
85 
86  AssertEqual(max1, max2, 0.00001);
87  AssertEqual(index1, index2, 0.00001);
88  }
89 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestSparseVectorSum()

void kaldi::UnitTestSparseVectorSum ( )

Definition at line 26 of file sparse-matrix-test.cc.

References AssertEqual(), SparseVector< Real >::CopyElementsToVec(), rnnlm::i, Rand(), VectorBase< Real >::SetRandn(), SparseVector< Real >::SetRandn(), SparseVector< Real >::Sum(), and VectorBase< Real >::Sum().

26  {
27  for (int32 i = 0; i < 10; i++) {
28  MatrixIndexT dim = 10 + Rand() % 40;
29 
30  SparseVector<Real> svec(dim);
31  svec.SetRandn(0.8);
32 
33  Vector<Real> vec(dim);
34  vec.SetRandn();
35  svec.CopyElementsToVec(&vec);
36 
37  Real sum1 = svec.Sum();
38  Real sum2 = vec.Sum();
39  AssertEqual(sum1, sum2, 0.00001);
40  }
41 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSparseVectorVecSvec()

void kaldi::UnitTestSparseVectorVecSvec ( )

Definition at line 92 of file sparse-matrix-test.cc.

References SparseVector< Real >::CopyElementsToVec(), rnnlm::i, KALDI_ASSERT, Rand(), VectorBase< Real >::SetRandn(), SparseVector< Real >::SetRandn(), VecSvec(), and VecVec().

92  {
93  for (int32 i = 0; i < 10; i++) {
94  MatrixIndexT dim = 10 + Rand() % 40;
95 
96  SparseVector<Real> svec(dim);
97  svec.SetRandn(0.8);
98 
99  Vector<Real> vec(dim);
100  vec.SetRandn();
101  svec.CopyElementsToVec(&vec);
102 
103  Vector<Real> other_vec(dim);
104  other_vec.SetRandn();
105 
106  Real product1 = VecSvec(other_vec, svec);
107  Real product2 = VecVec(other_vec, vec);
108 
109  KALDI_ASSERT(fabs(product1 - product2) < 1.0e-04);
110  }
111 }
kaldi::int32 int32
Real VecSvec(const VectorBase< Real > &vec, const SparseVector< Real > &svec)
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
Real VecVec(const VectorBase< Real > &a, const VectorBase< Real > &b)
Returns dot product between v1 and v2.
Definition: kaldi-vector.cc:37

◆ UnitTestSpInvert()

static void kaldi::UnitTestSpInvert ( )
static

Definition at line 2160 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), SpMatrix< Real >::CopyFromSp(), rnnlm::i, SpMatrix< Real >::Invert(), SpMatrix< Real >::InvertDouble(), MatrixBase< Real >::IsUnit(), rnnlm::j, KALDI_ASSERT, kNoTrans, PackedMatrix< Real >::NumRows(), Rand(), and RandGauss().

2160  {
2161  for (MatrixIndexT i = 0;i < 30;i++) {
2162  MatrixIndexT dimM = 6 + Rand()%20;
2163  SpMatrix<Real> M(dimM);
2164  for (MatrixIndexT i = 0;i < M.NumRows();i++)
2165  for (MatrixIndexT j = 0;j<=i;j++) M(i, j) = RandGauss();
2166  SpMatrix<Real> N(dimM);
2167  N.CopyFromSp(M);
2168  if (Rand() % 2 == 0)
2169  N.Invert();
2170  else
2171  N.InvertDouble();
2172  Matrix<Real> Mm(dimM, dimM), Nm(dimM, dimM), Om(dimM, dimM);
2173  Mm.CopyFromSp(M); Nm.CopyFromSp(N);
2174  Om.AddMatMat(1.0, Mm, kNoTrans, Nm, kNoTrans, 0.0);
2175  KALDI_ASSERT(Om.IsUnit( 0.01*dimM ));
2176  }
2177 }
Packed symetric matrix class.
Definition: matrix-common.h:62
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestSpliceRows()

static void kaldi::UnitTestSpliceRows ( )
static

Definition at line 339 of file matrix-lib-test.cc.

References AssertEqual(), VectorBase< Real >::CopyColFromMat(), MatrixBase< Real >::CopyColFromVec(), VectorBase< Real >::CopyColsFromMat(), MatrixBase< Real >::CopyColsFromVec(), VectorBase< Real >::CopyDiagFromMat(), MatrixBase< Real >::CopyDiagFromVec(), VectorBase< Real >::CopyRowFromMat(), MatrixBase< Real >::CopyRowFromVec(), VectorBase< Real >::CopyRowsFromMat(), MatrixBase< Real >::CopyRowsFromVec(), rnnlm::i, rnnlm::j, KALDI_ASSERT, and Rand().

339  {
340 
341  for (MatrixIndexT i = 0;i< 10;i++) {
342  MatrixIndexT dimM = 10+Rand()%10, dimN = 10+Rand()%10;
343 
344  Vector<Real> V(dimM*dimN), V10(dimM*dimN);
345  Vector<Real> Vs(std::min(dimM, dimN)), Vs10(std::min(dimM, dimN));
346  V.SetRandn();
347  Matrix<Real> M(dimM, dimN);
348  M.CopyRowsFromVec(V);
349  V10.CopyRowsFromMat(M);
350  AssertEqual(V, V10);
351 
352  for (MatrixIndexT i = 0;i < dimM;i++)
353  for (MatrixIndexT j = 0;j < dimN;j++)
354  KALDI_ASSERT(M(i, j) == V(i*dimN + j));
355 
356  {
357  Vector<Real> V2(dimM), V3(dimM);
358  V2.SetRandn();
359  MatrixIndexT x;
360  M.CopyColFromVec(V2, x = (Rand() % dimN));
361  V3.CopyColFromMat(M, x);
362  AssertEqual(V2, V3);
363  }
364 
365  {
366  Vector<Real> V2(dimN), V3(dimN);
367  V2.SetRandn();
368  MatrixIndexT x;
369  M.CopyRowFromVec(V2, x = (Rand() % dimM));
370  V3.CopyRowFromMat(M, x);
371  AssertEqual(V2, V3);
372  }
373 
374  {
375  M.CopyColsFromVec(V);
376  V10.CopyColsFromMat(M);
377  AssertEqual(V, V10);
378  }
379 
380  {
381  M.CopyDiagFromVec(Vs);
382  Vs10.CopyDiagFromMat(M);
383  AssertEqual(Vs, Vs10);
384  }
385 
386  }
387 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSplitRadixComplexFft()

static void kaldi::UnitTestSplitRadixComplexFft ( )
static

Definition at line 3453 of file matrix-lib-test.cc.

References AssertEqual(), ComplexFt(), SplitRadixComplexFft< Real >::Compute(), VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Data(), Rand(), and VectorBase< Real >::Scale().

3453  {
3454 
3455  // Make sure it inverts properly.
3456  for (MatrixIndexT N_ = 0; N_ < 30; N_+=3) {
3457  MatrixIndexT logn = 1 + Rand() % 10;
3458  MatrixIndexT N = 1 << logn;
3459 
3460  MatrixIndexT twoN = 2*N;
3461  std::vector<Real> temp_buffer;
3462  SplitRadixComplexFft<Real> srfft(N), srfft2(srfft);
3463  for (MatrixIndexT p = 0; p < 3; p++) {
3464  Vector<Real> v(twoN), w_base(twoN), w_alg(twoN), x_base(twoN), x_alg(twoN);
3465 
3466  v.SetRandn();
3467 
3468  if (N< 100) ComplexFt(v, &w_base, true);
3469  w_alg.CopyFromVec(v);
3470 
3471  if (Rand() % 2 == 0)
3472  srfft.Compute(w_alg.Data(), true);
3473  else
3474  srfft2.Compute(w_alg.Data(), true, &temp_buffer);
3475 
3476  if (N< 100) AssertEqual(w_base, w_alg, 0.01*N);
3477 
3478  if (N< 100) ComplexFt(w_base, &x_base, false);
3479  x_alg.CopyFromVec(w_alg);
3480  srfft.Compute(x_alg.Data(), false);
3481 
3482  if (N< 100) AssertEqual(x_base, x_alg, 0.01*N);
3483  x_alg.Scale(1.0/N);
3484  AssertEqual(v, x_alg, 0.001*N);
3485  }
3486  }
3487 }
void ComplexFt(const VectorBase< Real > &in, VectorBase< Real > *out, bool forward)
ComplexFt is the same as ComplexFft but it implements the Fourier transform in an inefficient way...
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSplitRadixComplexFft2()

static void kaldi::UnitTestSplitRadixComplexFft2 ( )
static

Definition at line 3591 of file matrix-lib-test.cc.

References ApproxEqual(), SplitRadixComplexFft< Real >::Compute(), VectorBase< Real >::CopyFromVec(), KALDI_ASSERT, and Rand().

3591  {
3592 
3593  // Make sure it inverts properly.
3594  for (MatrixIndexT p = 0; p < 30; p++) {
3595  MatrixIndexT logn = 1 + Rand() % 10;
3596  MatrixIndexT N = 1 << logn;
3597  SplitRadixComplexFft<Real> srfft(N);
3598  for (MatrixIndexT q = 0; q < 3; q++) {
3599  Vector<Real> v(N*2), vorig(N*2);
3600  v.SetRandn();
3601  vorig.CopyFromVec(v);
3602  srfft.Compute(v.Data(), true); // forward
3603  srfft.Compute(v.Data(), false); // backward
3604  v.Scale(1.0/N);
3605  KALDI_ASSERT(ApproxEqual(v, vorig));
3606  }
3607  }
3608 }
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestSplitRadixRealFft()

static void kaldi::UnitTestSplitRadixRealFft ( )
static

Definition at line 3639 of file matrix-lib-test.cc.

References AssertEqual(), SplitRadixRealFft< Real >::Compute(), VectorBase< Real >::CopyFromVec(), VectorBase< Real >::Data(), Rand(), RealFftInefficient(), and VectorBase< Real >::Scale().

3639  {
3640 
3641  for (MatrixIndexT p = 0; p < 30; p++) {
3642  MatrixIndexT logn = 2 + Rand() % 9,
3643  N = 1 << logn;
3644 
3645  SplitRadixRealFft<Real> srfft(N), srfft2(srfft);
3646  std::vector<Real> temp_buffer;
3647  for (MatrixIndexT q = 0; q < 3; q++) {
3648  Vector<Real> v(N), w(N), x(N), y(N);
3649  v.SetRandn();
3650  w.CopyFromVec(v);
3651  RealFftInefficient(&w, true);
3652  y.CopyFromVec(v);
3653  if (Rand() % 2 == 0)
3654  srfft.Compute(y.Data(), true);
3655  else
3656  srfft2.Compute(y.Data(), true, &temp_buffer);
3657 
3658  // KALDI_LOG <<"v = "<<v;
3659  // KALDI_LOG << "Inefficient real fft of v is: "<< w;
3660  // KALDI_LOG << "Efficient real fft of v is: "<< y;
3661  AssertEqual(w, y, 0.01*N);
3662  x.CopyFromVec(w);
3663  RealFftInefficient(&x, false);
3664  srfft.Compute(y.Data(), false);
3665  // KALDI_LOG << "Inefficient real fft of v twice is: "<< x;
3666  x.Scale(1.0/N);
3667  y.Scale(1.0/N);
3668  AssertEqual(v, x, 0.001*N);
3669  AssertEqual(v, y, 0.001*N); // ?
3670  }
3671  }
3672 }
void RealFftInefficient(VectorBase< Real > *v, bool forward)
Inefficient version of Fourier transform, for testing purposes.
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSplitRadixRealFftSpeed() [1/2]

static void kaldi::UnitTestSplitRadixRealFftSpeed ( )
static

Definition at line 50 of file matrix-lib-speed-test.cc.

References SplitRadixRealFft< Real >::Compute(), VectorBase< Real >::Data(), Timer::Elapsed(), rnnlm::i, and KALDI_LOG.

50  {
51  Timer t;
52  MatrixIndexT sz = 512; // fairly typical size.
53  SplitRadixRealFft<Real> srfft(sz);
54  for (MatrixIndexT i = 0; i < 6000; i++) {
55  if (i % 1000 == 0)
56  KALDI_LOG << "done 1000 [ == ten seconds of speech, split-radix]";
57  Vector<Real> v(sz);
58  srfft.Compute(v.Data(), true);
59  }
60  CsvResult<Real>(__func__, 512, t.Elapsed(), "seconds");
61 }
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestSplitRadixRealFftSpeed() [2/2]

static void kaldi::UnitTestSplitRadixRealFftSpeed ( )
static

Definition at line 3688 of file matrix-lib-test.cc.

References SplitRadixRealFft< Real >::Compute(), VectorBase< Real >::Data(), rnnlm::i, and KALDI_LOG.

3688  {
3689  KALDI_LOG << "starting. ";
3690  MatrixIndexT sz = 512; // fairly typical size.
3691  SplitRadixRealFft<Real> srfft(sz);
3692  for (MatrixIndexT i = 0; i < 6000; i++) {
3693  if (i % 1000 == 0)
3694  KALDI_LOG << "done 1000 [ == ten seconds of speech, split-radix]";
3695  Vector<Real> v(sz);
3696  srfft.Compute(v.Data(), true);
3697  }
3698 }
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSpVec()

static void kaldi::UnitTestSpVec ( )
static

Definition at line 1265 of file matrix-lib-test.cc.

References AssertEqual(), and PackedMatrix< Real >::CopyFromVec().

1265  {
1266  // Test conversion back and forth between SpMatrix and Vector.
1267  for (MatrixIndexT iter = 0;iter < 1;iter++) {
1268  MatrixIndexT dimM =10; // 20 + Rand()%10;
1269  SpMatrix<Real> A(dimM), B(dimM);
1270  SubVector<Real> vec(A);
1271  B.CopyFromVec(vec);
1272  AssertEqual(A, B);
1273  }
1274 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestSubvector()

static void kaldi::UnitTestSubvector ( )
static

Definition at line 430 of file matrix-lib-test.cc.

References AssertEqual(), VectorBase< Real >::CopyFromVec(), rnnlm::i, and VectorBase< Real >::SetRandn().

430  {
431 
432  Vector<Real> V(100);
433  V.SetRandn();
434  Vector<Real> V2(100);
435  for (MatrixIndexT i = 0;i < 10;i++) {
436  SubVector<Real> tmp(V, i*10, 10);
437  SubVector<Real> tmp2(V2, i*10, 10);
438  tmp2.CopyFromVec(tmp);
439  }
440  AssertEqual(V, V2);
441 }
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestSvd()

static void kaldi::UnitTestSvd ( )
static

Definition at line 1292 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMatMat(), AssertEqual(), MatrixBase< Real >::CopyDiagFromVec(), MatrixBase< Real >::CopyFromMat(), KALDI_LOG, kNoTrans, Rand(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::SetZero().

1292  {
1293  MatrixIndexT Base = 3, Rand_ = 2, Iter = 25;
1294  for (MatrixIndexT iter = 0;iter < Iter;iter++) {
1295  MatrixIndexT dimM = Base + Rand() % Rand_, dimN = Base + Rand() % Rand_;
1296  Matrix<Real> M(dimM, dimN);
1297  Matrix<Real> U(dimM, std::min(dimM, dimN)), Vt(std::min(dimM, dimN), dimN);
1298  Vector<Real> s(std::min(dimM, dimN));
1299  M.SetRandn();
1300  if (iter < 2) KALDI_LOG << "M " << M;
1301  Matrix<Real> M2(dimM, dimN); M2.CopyFromMat(M);
1302  M.Svd(&s, &U, &Vt);
1303  if (iter < 2) {
1304  KALDI_LOG << " s " << s;
1305  KALDI_LOG << " U " << U;
1306  KALDI_LOG << " Vt " << Vt;
1307  }
1308  MatrixIndexT min_dim = std::min(dimM, dimN);
1309  Matrix<Real> S(min_dim, min_dim);
1310  S.CopyDiagFromVec(s);
1311  Matrix<Real> Mtmp(dimM, dimN);
1312  Mtmp.SetZero();
1313  Mtmp.AddMatMatMat(1.0, U, kNoTrans, S, kNoTrans, Vt, kNoTrans, 0.0);
1314  AssertEqual(Mtmp, M2);
1315  }
1316 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSvdBad()

static void kaldi::UnitTestSvdBad ( )
static

Definition at line 1318 of file matrix-lib-test.cc.

References rnnlm::i, rnnlm::j, MatrixBase< Real >::Set(), MatrixBase< Real >::Svd(), and SpMatrix< Real >::SymPosSemiDefEig().

1318  {
1319  MatrixIndexT N = 20;
1320  {
1321  Matrix<Real> M(N, N);
1322  // M.Set(1591.3614306764898);
1323  M.Set(1.0);
1324  M(0, 0) *= 1.000001;
1325  Matrix<Real> U(N, N), V(N, N);
1326  Vector<Real> l(N);
1327  M.Svd(&l, &U, &V);
1328  }
1329  SpMatrix<Real> M(N);
1330  for(MatrixIndexT i =0; i < N; i++)
1331  for(MatrixIndexT j = 0; j <= i; j++)
1332  M(i, j) = 1591.3614306764898;
1333  M(0, 0) *= 1.00001;
1334  M(10, 10) *= 1.00001;
1335  Matrix<Real> U(N, N);
1336  Vector<Real> l(N);
1337  M.SymPosSemiDefEig(&l, &U);
1338 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406

◆ UnitTestSvdJustvec()

static void kaldi::UnitTestSvdJustvec ( )
static

Definition at line 1398 of file matrix-lib-test.cc.

References AssertEqual(), Rand(), and MatrixBase< Real >::Svd().

1398  { // Making sure gives same answer if we get just the vector, not the eigs.
1399  MatrixIndexT Base = 10, Rand_ = 5, Iter = 25;
1400  for (MatrixIndexT iter = 0;iter < Iter;iter++) {
1401  MatrixIndexT dimM = Base + Rand() % Rand_, dimN = Base + Rand() % Rand_; // M>=N.
1402  MatrixIndexT minsz = std::min(dimM, dimN);
1403 
1404  Matrix<Real> M(dimM, dimN);
1405  Matrix<Real> U(dimM, minsz), Vt(minsz, dimN); Vector<Real> v(minsz);
1406  M.Svd(&v, &U, &Vt);
1407  Vector<Real> v2(minsz);
1408  M.Svd(&v2);
1409  AssertEqual(v, v2);
1410  }
1411 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestSvdNodestroy()

static void kaldi::UnitTestSvdNodestroy ( )
static

Definition at line 1360 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), VectorBase< Real >::Dim(), rnnlm::i, rnnlm::j, KALDI_ASSERT, KALDI_LOG, kNoTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::SetRandn(), SortSvd(), and MatrixBase< Real >::Svd().

1360  {
1361  MatrixIndexT Base = 3, Rand_ = 2, Iter = 25;
1362  for (MatrixIndexT iter = 0;iter < Iter;iter++) {
1363  MatrixIndexT dimN = Base + Rand() % Rand_, dimM = dimN + Rand() % Rand_; // M>=N, as required by JAMA Svd.
1364  MatrixIndexT minsz = std::min(dimM, dimN);
1365  Matrix<Real> M(dimM, dimN);
1366  Matrix<Real> U(dimM, minsz), Vt(minsz, dimN); Vector<Real> v(minsz);
1367  M.SetRandn();
1368  if (iter < 2) KALDI_LOG << "M " << M;
1369  M.Svd(&v, &U, &Vt);
1370  if (iter < 2) {
1371  KALDI_LOG << " v " << v;
1372  KALDI_LOG << " U " << U;
1373  KALDI_LOG << " Vt " << Vt;
1374  }
1375 
1376  for (MatrixIndexT it = 0;it < 2;it++) {
1377  Matrix<Real> Mtmp(minsz, minsz);
1378  for (MatrixIndexT i = 0;i < v.Dim();i++) Mtmp(i, i) = v(i);
1379  Matrix<Real> Mtmp2(minsz, dimN);
1380  Mtmp2.AddMatMat(1.0, Mtmp, kNoTrans, Vt, kNoTrans, 0.0);
1381  Matrix<Real> Mtmp3(dimM, dimN);
1382  Mtmp3.AddMatMat(1.0, U, kNoTrans, Mtmp2, kNoTrans, 0.0);
1383  for (MatrixIndexT i = 0;i < Mtmp.NumRows();i++) {
1384  for (MatrixIndexT j = 0;j < Mtmp.NumCols();j++) {
1385  KALDI_ASSERT(std::abs(Mtmp3(i, j) - M(i, j)) < 0.0001);
1386  }
1387  }
1388 
1389  SortSvd(&v, &U, &Vt); // and re-check...
1390  for (MatrixIndexT i = 0; i + 1 < v.Dim(); i++) // check SortSvd is working.
1391  KALDI_ASSERT(std::abs(v(i+1)) <= std::abs(v(i)));
1392  }
1393  }
1394 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153
void SortSvd(VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt, bool sort_on_absolute_value)
Function to ensure that SVD is sorted.

◆ UnitTestSvdSpeed() [1/2]

static void kaldi::UnitTestSvdSpeed ( )
static

Definition at line 64 of file matrix-lib-speed-test.cc.

References SpMatrix< Real >::Eig(), Timer::Elapsed(), rnnlm::i, PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::Svd().

64  {
65  Timer t;
66  std::vector<MatrixIndexT> sizes;
67  sizes.push_back(100);
68  sizes.push_back(150);
69  sizes.push_back(200);
70  sizes.push_back(300);
71  // sizes.push_back(500);
72  // sizes.push_back(750);
73  for (size_t i = 0; i < sizes.size(); i++) {
74  MatrixIndexT size = sizes[i];
75  {
76  Timer t1;
77  SpMatrix<Real> S(size);
78  Vector<Real> l(size);
79  S.Eig(&l);
80  CsvResult<Real>("Eig w/o eigenvectors", size, t1.Elapsed(), "seconds");
81  }
82  {
83  Timer t1;
84  SpMatrix<Real> S(size);
85  S.SetRandn();
86  Vector<Real> l(size);
87  Matrix<Real> P(size, size);
88  S.Eig(&l, &P);
89  CsvResult<Real>("Eig with eigenvectors", size, t1.Elapsed(), "seconds");
90  }
91  {
92  Timer t1;
93  Matrix<Real> M(size, size);
94  M.SetRandn();
95  Vector<Real> l(size);
96  M.Svd(&l, NULL, NULL);
97  CsvResult<Real>("SVD w/o eigenvectors", size, t1.Elapsed(), "seconds");
98  }
99  {
100  Timer t1;
101  Matrix<Real> M(size, size), U(size, size), V(size, size);
102  M.SetRandn();
103  Vector<Real> l(size);
104  M.Svd(&l, &U, &V);
105  CsvResult<Real>("SVD with eigenvectors", size, t1.Elapsed(), "seconds");
106  }
107  }
108  CsvResult<Real>(__func__, sizes.size(), t.Elapsed(), "seconds");
109 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74

◆ UnitTestSvdSpeed() [2/2]

static void kaldi::UnitTestSvdSpeed ( )
static

Definition at line 3953 of file matrix-lib-test.cc.

References SpMatrix< Real >::Eig(), rnnlm::i, KALDI_LOG, PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and MatrixBase< Real >::Svd().

3953  {
3954  std::vector<MatrixIndexT> sizes;
3955  sizes.push_back(100);
3956  sizes.push_back(150);
3957  sizes.push_back(200);
3958  sizes.push_back(300);
3959  sizes.push_back(500);
3960  sizes.push_back(750);
3961  sizes.push_back(1000);
3962  sizes.push_back(2000);
3963  time_t start, end;
3964  for (size_t i = 0; i < sizes.size(); i++) {
3965  MatrixIndexT size = sizes[i];
3966  {
3967  start = time(NULL);
3968  SpMatrix<Real> S(size);
3969  Vector<Real> l(size);
3970  S.Eig(&l);
3971  end = time(NULL);
3972  double diff = difftime(end, start);
3973  KALDI_LOG << "For size " << size << ", Eig without eigenvectors took " << diff
3974  << " seconds.";
3975  }
3976  {
3977  start = time(NULL);
3978  SpMatrix<Real> S(size);
3979  S.SetRandn();
3980  Vector<Real> l(size);
3981  Matrix<Real> P(size, size);
3982  S.Eig(&l, &P);
3983  end = time(NULL);
3984  double diff = difftime(end, start);
3985  KALDI_LOG << "For size " << size << ", Eig with eigenvectors took " << diff
3986  << " seconds.";
3987  }
3988  {
3989  start = time(NULL);
3990  Matrix<Real> M(size, size);
3991  M.SetRandn();
3992  Vector<Real> l(size);
3993  M.Svd(&l, NULL, NULL);
3994  end = time(NULL);
3995  double diff = difftime(end, start);
3996  KALDI_LOG << "For size " << size << ", SVD without eigenvectors took " << diff
3997  << " seconds.";
3998  }
3999  {
4000  start = time(NULL);
4001  Matrix<Real> M(size, size), U(size, size), V(size, size);
4002  M.SetRandn();
4003  Vector<Real> l(size);
4004  M.Svd(&l, &U, &V);
4005  end = time(NULL);
4006  double diff = difftime(end, start);
4007  KALDI_LOG << "For size " << size << ", SVD with eigenvectors took " << diff
4008  << " seconds.";
4009  }
4010  }
4011 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSvdZero()

static void kaldi::UnitTestSvdZero ( )
static

Definition at line 1341 of file matrix-lib-test.cc.

References MatrixBase< Real >::CopyFromMat(), KALDI_ASSERT, KALDI_LOG, Rand(), and MatrixBase< Real >::SetZero().

1341  {
1342  MatrixIndexT Base = 3, Rand_ = 2, Iter = 30;
1343  for (MatrixIndexT iter = 0;iter < Iter;iter++) {
1344  MatrixIndexT dimM = Base + Rand() % Rand_, dimN = Base + Rand() % Rand_; // M>=N.
1345  Matrix<Real> M(dimM, dimN);
1346  Matrix<Real> U(dimM, dimM), Vt(dimN, dimN); Vector<Real> v(std::min(dimM, dimN));
1347  if (iter%2 == 0) M.SetZero();
1348  else M.Unit();
1349  if (iter < 2) KALDI_LOG << "M " << M;
1350  Matrix<Real> M2(dimM, dimN); M2.CopyFromMat(M);
1351  bool ans = M.Svd(&v, &U, &Vt);
1352  KALDI_ASSERT(ans); // make sure works with zero matrix.
1353  }
1354 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestSwapCu2Cu()

void kaldi::UnitTestSwapCu2Cu ( )

Definition at line 2533 of file cu-matrix-test.cc.

References ApproxEqual(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), MatrixBase< Real >::SetRandn(), and CuMatrix< Real >::Swap().

2533  {
2534  Matrix<Real> Hi(100,111);
2535  Hi.SetRandn();
2536  CuMatrix<Real> Di(100,111);
2537  Di.CopyFromMat(Hi);
2538 
2539  Matrix<Real> Hi2(110,121);
2540  Hi2.SetRandn();
2541  CuMatrix<Real> Di2(110,121);
2542  Di2.CopyFromMat(Hi2);
2543 
2544  Di.Swap(&Di2);
2545  Matrix<Real> Hf(Di.NumRows(), Di.NumCols());
2546  Di.CopyToMat(&Hf);
2547  Matrix<Real> Hf2(Di2.NumRows(), Di2.NumCols());
2548  Di2.CopyToMat(&Hf2);
2549  KALDI_ASSERT(ApproxEqual(Hi,Hf2));
2550  KALDI_ASSERT(ApproxEqual(Hi2,Hf));
2551 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestSwapCu2M()

void kaldi::UnitTestSwapCu2M ( )

Definition at line 2554 of file cu-matrix-test.cc.

References ApproxEqual(), MatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyFromMat(), CuMatrixBase< Real >::CopyToMat(), KALDI_ASSERT, CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), MatrixBase< Real >::SetRandn(), and CuMatrix< Real >::Swap().

2554  {
2555  Matrix<Real> Hi(100,111);
2556  Hi.SetRandn();
2557  CuMatrix<Real> Di(100,111);
2558  Di.CopyFromMat(Hi);
2559 
2560  Matrix<Real> Hi2(110,121);
2561  Hi2.SetRandn();
2562  Matrix<Real> Di2(110,121);
2563  Di2.CopyFromMat(Hi2);
2564 
2565  Di.Swap(&Hi2);
2566  Matrix<Real> Hf(Di.NumRows(), Di.NumCols());
2567  Di.CopyToMat(&Hf);
2568  KALDI_ASSERT(ApproxEqual(Di2,Hf));
2569  KALDI_ASSERT(ApproxEqual(Hi2,Hi));
2570 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestSymAddMat2()

static void kaldi::UnitTestSymAddMat2 ( )
static

Definition at line 2980 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), AssertEqual(), TpMatrix< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::SetRandn(), MatrixBase< Real >::Sum(), MatrixBase< Real >::SymAddMat2(), and Matrix< Real >::Transpose().

2980  {
2981  for (int32 i = 0; i < 5; i++) {
2982  int32 dimM = 10 + Rand() % 200, dimN = 10 + Rand() % 30;
2983  KALDI_LOG << "dimM = " << dimM << ", dimN = " << dimN;
2984 
2985  Matrix<Real> M(dimM, dimM); // square matrix..
2986  Matrix<Real> N(dimM, dimN);
2987  M.SetRandn();
2988  N.SetRandn();
2989  //MatrixTransposeType trans = (i % 2 == 0 ? kTrans : kNoTrans),
2990  MatrixTransposeType trans = kTrans,
2991  other_trans = (trans == kTrans ? kNoTrans : kTrans);
2992  if (trans == kTrans) N.Transpose();
2993  KALDI_LOG << "N sum is " << N.Sum();
2994  Matrix<Real> M2(M);
2995  KALDI_LOG << "M sum is " << M.Sum();
2996 
2997  Real alpha = 0.2 * (Rand() % 6),
2998  beta = 0.2 * (Rand() % 6);
2999  //Real alpha = 0.3, beta = 1.75432;
3000  M.SymAddMat2(alpha, N, trans, beta);
3001 
3002  KALDI_LOG << "M(0, 0) is " << M(0, 0);
3003  KALDI_LOG << "M sum2 is " << M.Sum();
3004 
3005  M2.AddMatMat(alpha, N, trans, N, other_trans, beta);
3006 
3007  TpMatrix<Real> T1(M.NumRows()), T2(M2.NumRows());
3008  T1.CopyFromMat(M);
3009  T2.CopyFromMat(M2);
3010  Matrix<Real> X1(T1), X2(T2); // so we can test equality.
3011  AssertEqual(X1, X2);
3012  KALDI_ASSERT(dimM == 0 || X1.Trace() != 0 || (alpha == 0 && beta == 0));
3013  }
3014 }
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void CopyFromMat(const MatrixBase< Real > &M, MatrixTransposeType Trans=kNoTrans)
CopyFromMat copies the lower triangle of M into *this (or the upper triangle, if Trans == kTrans)...
Definition: tp-matrix.cc:117
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestTableRandomBothDouble()

void kaldi::UnitTestTableRandomBothDouble ( bool  binary,
bool  read_scp,
bool  sorted,
bool  called_sorted,
bool  once 
)

Definition at line 768 of file kaldi-table-test.cc.

References ApproxEqual(), CharToString(), TableWriter< Holder >::Close(), RandomAccessTableReader< Holder >::HasKey(), rnnlm::i, KALDI_ASSERT, Rand(), RandomizeVector(), Uniq(), RandomAccessTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

770  {
771  int32 sz = Rand() % 10;
772  std::vector<std::string> k;
773  std::vector<double> v;
774 
775  for (int32 i = 0; i < sz; i++) {
776  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
777  // some single quotes too but it doesn't really matter.
778  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
779  // different lengths.
780  v.push_back((Rand() / static_cast<double>(Rand())));
781  }
782 
783  if (!sorted)
784  RandomizeVector(&k);
785 
786 
787  bool ans;
788  DoubleWriter bw(binary ? "b,f,ark,scp:tmpf,tmpf.scp" :
789  "t,f,ark,scp:tmpf,tmpf.scp"); // Putting the "flush" option
790  // in too, just for good measure..
791  for (int32 i = 0; i < sz; i++) {
792  bw.Write(k[i], v[i]);
793  }
794  ans = bw.Close();
795  KALDI_ASSERT(ans);
796 
797 
798  std::string name;
799  if (sorted) name += "s,";
800  else if (Rand()%2 == 0) name += "ns,";
801  if (called_sorted) name += "cs,";
802  else if (Rand()%2 == 0) name += "ncs,";
803  if (once) name += "o,";
804  else if (Rand()%2 == 0) name += "no,";
805  name += std::string(read_scp ? "scp:tmpf.scp" : "ark:tmpf");
806 
807  RandomAccessDoubleReader sbr(name);
808 
809  if (sz != 0) {
810  std::vector<std::string> read_keys;
811  int32 read_sz = Rand() % 5;
812  for (int32 i = 0; i < read_sz; i++)
813  read_keys.push_back(k[Rand() % k.size()]);
814  std::sort(read_keys.begin(), read_keys.end());
815  if (once) Uniq(&read_keys);
816  if (!called_sorted)
817  RandomizeVector(&read_keys);
818 
819  for (size_t i = 0; i < read_keys.size(); i++) {
820  std::cout << "Looking up key " << read_keys[i] << std::endl;
821  std::string cur_key = read_keys[i];
822 
823  auto it = std::find(k.begin(), k.end(), cur_key);
824  KALDI_ASSERT(it != k.end());
825  size_t idx = std::distance(k.begin(), it);
826  double value = v[idx];
827  if (Rand() % 2 == 0) {
828  bool ans = sbr.HasKey(cur_key);
829  KALDI_ASSERT(ans == true);
830  }
831  if (binary) {
832  KALDI_ASSERT(value == sbr.Value(cur_key));
833  } else {
834  KALDI_ASSERT(ApproxEqual(value, sbr.Value(cur_key)));
835  }
836  }
837  }
838 }
void Uniq(std::vector< T > *vec)
Removes duplicate elements from a sorted list.
Definition: stl-utils.h:78
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void RandomizeVector(std::vector< T > *v)
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestTableRandomBothDoubleMatrix()

void kaldi::UnitTestTableRandomBothDoubleMatrix ( bool  binary,
bool  read_scp,
bool  sorted,
bool  called_sorted,
bool  once 
)

Definition at line 972 of file kaldi-table-test.cc.

References MatrixBase< Real >::ApproxEqual(), CharToString(), TableWriter< Holder >::Close(), RandomAccessTableReader< Holder >::HasKey(), rnnlm::i, rnnlm::j, KALDI_ASSERT, Rand(), RandomizeVector(), Uniq(), RandomAccessTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

974  {
975  int32 sz = Rand() % 10;
976  std::vector<std::string> k;
977  std::vector<Matrix<double> > v;
978 
979  for (int32 i = 0; i < sz; i++) {
980  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
981  // some single quotes too but it doesn't really matter.
982  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
983  // different lengths.
984  v.resize(v.size()+1);
985  v.back().Resize(1 + Rand()%3, 1 + Rand()%3);
986  for (int32 j = 0; j < v.back().NumRows(); j++)
987  for (int32 k = 0; k < v.back().NumCols(); k++)
988  v.back()(j, k) = (Rand() % 100);
989  }
990 
991  if (!sorted)
992  RandomizeVector(&k);
993 
994 
995  bool ans;
996  DoubleMatrixWriter bw(binary ? "b,f,ark,scp:tmpf,tmpf.scp" :
997  "t,f,ark,scp:tmpf,tmpf.scp"); // Putting the "flush"
998  // option in too, just for good measure..
999  for (int32 i = 0; i < sz; i++) {
1000  bw.Write(k[i], v[i]);
1001  }
1002  ans = bw.Close();
1003  KALDI_ASSERT(ans);
1004 
1005 
1006  std::string name;
1007  if (sorted) name += "s,";
1008  else if (Rand()%2 == 0) name += "ns,";
1009  if (called_sorted) name += "cs,";
1010  else if (Rand()%2 == 0) name += "ncs,";
1011  if (once) name += "o,";
1012  else if (Rand()%2 == 0) name += "no,";
1013  name += std::string(read_scp ? "scp:tmpf.scp" : "ark:tmpf");
1015 
1016  if (sz != 0) {
1017  std::vector<std::string> read_keys;
1018  int32 read_sz = Rand() % 5;
1019  for (int32 i = 0; i < read_sz; i++)
1020  read_keys.push_back(k[Rand() % k.size()]);
1021  std::sort(read_keys.begin(), read_keys.end());
1022  if (once) Uniq(&read_keys);
1023  if (!called_sorted)
1024  RandomizeVector(&read_keys);
1025 
1026  for (size_t i = 0; i < read_keys.size(); i++) {
1027  std::cout << "Looking up key " << read_keys[i] << std::endl;
1028  std::string cur_key = read_keys[i];
1029  Matrix<double> *value_ptr = NULL;
1030  for (size_t i = 0; i < k.size(); i++)
1031  if (cur_key == k[i]) value_ptr = &(v[i]);
1032  if (Rand() % 2 == 0) {
1033  bool ans = sbr.HasKey(cur_key);
1034  KALDI_ASSERT(ans == true);
1035  }
1036  if (binary) {
1037  KALDI_ASSERT(value_ptr->ApproxEqual(sbr.Value(cur_key), 1.0e-10));
1038  } else {
1039  KALDI_ASSERT(value_ptr->ApproxEqual(sbr.Value(cur_key), 0.01));
1040  }
1041  }
1042  }
1043  unlink("tmpf");
1044  unlink("tmpf.scp");
1045 }
void Uniq(std::vector< T > *vec)
Removes duplicate elements from a sorted list.
Definition: stl-utils.h:78
bool ApproxEqual(const MatrixBase< Real > &other, float tol=0.01) const
Returns true if ((*this)-other).FrobeniusNorm() <= tol * (*this).FrobeniusNorm(). ...
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void RandomizeVector(std::vector< T > *v)

◆ UnitTestTableSequentialBaseFloatVectorBoth()

void kaldi::UnitTestTableSequentialBaseFloatVectorBoth ( bool  binary,
bool  read_scp 
)

Definition at line 704 of file kaldi-table-test.cc.

References ApproxEqual(), CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandGauss(), RandInt(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

704  {
705  int32 sz = Rand() % 10;
706  std::vector<std::string> k;
707  std::vector<Vector<BaseFloat>*> v;
708 
709  for (int32 i = 0; i < sz; i++) {
710  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
711  // some single quotes too but it doesn't really matter.
712  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
713  // different lengths.
714  v.push_back(new Vector<BaseFloat>(1 + Rand()%4));
715  for (int32 i = 0; i < v.back()->Dim(); i++)
716  (*(v.back()))(i) = RandGauss();
717  }
718 
719  bool ans;
720  BaseFloatVectorWriter bw(binary ? "b,ark,scp:tmpf,tmpf.scp" :
721  "t,ark,scp:tmpf,tmpf.scp");
722  for (int32 i = 0; i < sz; i++) {
723  bw.Write(k[i], *(v[i]));
724  }
725  ans = bw.Close();
726  KALDI_ASSERT(ans);
727 
729  RandInt(0, 1) == 0 ?
730  (read_scp ? "scp:tmpf.scp" : "ark:tmpf") :
731  (read_scp ? "scp,bg:tmpf.scp" : "ark,bg:tmpf"));
732  std::vector<std::string> k2;
733  std::vector<Vector<BaseFloat>* > v2;
734  for (; !sbr.Done(); sbr.Next()) {
735  k2.push_back(sbr.Key());
736  v2.push_back(new Vector<BaseFloat>(sbr.Value()));
737  }
738  KALDI_ASSERT(sbr.Close());
739  KALDI_ASSERT(k2 == k);
740  if (binary) {
741  for (size_t i = 0; i < v2.size(); i++)
742  KALDI_ASSERT(v2[i]->ApproxEqual(*(v[i]), 1.0e-10));
743  } else {
744  KALDI_ASSERT(v2.size() == v.size());
745  for (size_t i = 0; i < v2.size(); i++)
746  KALDI_ASSERT(v2[i]->ApproxEqual(*(v[i])));
747  }
748  for (int32 i = 0; i < sz; i++) {
749  delete v[i];
750  delete v2[i];
751  }
752 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialBool()

void kaldi::UnitTestTableSequentialBool ( bool  binary)

Definition at line 356 of file kaldi-table-test.cc.

References CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandInt(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

356  {
357  int32 sz = Rand() % 10;
358  std::vector<std::string> k;
359  std::vector<bool> v;
360 
361  for (int32 i = 0; i < sz; i++) {
362  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
363  // some single quotes too but it doesn't really matter.
364  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
365  // different lengths.
366  v.push_back((Rand()%2 == 0));
367  }
368 
369  bool ans;
370  BoolWriter bw(binary ? "b,ark:tmpf" : "t,ark:tmpf");
371  for (int32 i = 0; i < sz; i++) {
372  bw.Write(k[i], v[i]);
373  }
374  ans = bw.Close();
375  KALDI_ASSERT(ans);
376 
377  SequentialBoolReader sbr(RandInt(0, 1) == 0 ? "ark:tmpf" : "ark,bg:tmpf");
378  std::vector<std::string> k2;
379  std::vector<bool> v2;
380  for (; !sbr.Done(); sbr.Next()) {
381  k2.push_back(sbr.Key());
382  v2.push_back(sbr.Value());
383  }
384  KALDI_ASSERT(sbr.Close());
385  KALDI_ASSERT(k2 == k);
386  KALDI_ASSERT(v2 == v);
387 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialDouble()

void kaldi::UnitTestTableSequentialDouble ( bool  binary)

Definition at line 390 of file kaldi-table-test.cc.

References ApproxEqual(), CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandInt(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

390  {
391  int32 sz = Rand() % 10;
392  std::vector<std::string> k;
393  std::vector<double> v;
394 
395  for (int32 i = 0; i < sz; i++) {
396  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
397  // some single quotes too but it doesn't really matter.
398  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
399  // different lengths.
400  v.push_back((Rand() / static_cast<double>(Rand())));
401  }
402 
403  bool ans;
404  DoubleWriter bw(binary ? "b,ark:tmpf" : "t,ark:tmpf");
405  for (int32 i = 0; i < sz; i++) {
406  bw.Write(k[i], v[i]);
407  }
408  ans = bw.Close();
409  KALDI_ASSERT(ans);
410 
411  SequentialDoubleReader sbr(RandInt(0, 1) == 0 ? "ark:tmpf" : "ark,bg:tmpf");
412  std::vector<std::string> k2;
413  std::vector<double> v2;
414  for (; !sbr.Done(); sbr.Next()) {
415  k2.push_back(sbr.Key());
416  v2.push_back(sbr.Value());
417  }
418  KALDI_ASSERT(sbr.Close());
419  KALDI_ASSERT(k2 == k);
420  if (binary) {
421  KALDI_ASSERT(v2 == v);
422  } else {
423  KALDI_ASSERT(v2.size() == v.size());
424  for (size_t i = 0; i < v2.size(); i++)
425  KALDI_ASSERT(ApproxEqual(v[i], v2[i]));
426  }
427 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialDoubleBoth()

void kaldi::UnitTestTableSequentialDoubleBoth ( bool  binary,
bool  read_scp 
)

Definition at line 431 of file kaldi-table-test.cc.

References ApproxEqual(), CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandInt(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

431  {
432  int32 sz = Rand() % 10;
433  std::vector<std::string> k;
434  std::vector<double> v;
435 
436  for (int32 i = 0; i < sz; i++) {
437  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
438  // some single quotes too but it doesn't really matter.
439  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
440  // different lengths.
441  v.push_back((Rand() / static_cast<double>(Rand())));
442  }
443 
444  bool ans;
445  DoubleWriter bw(binary ? "b,ark,scp:tmpf,tmpf.scp" :
446  "t,ark,scp:tmpf,tmpf.scp");
447  for (int32 i = 0; i < sz; i++) {
448  bw.Write(k[i], v[i]);
449  }
450  ans = bw.Close();
451  KALDI_ASSERT(ans);
452 
453  SequentialDoubleReader sbr(RandInt(0, 1) == 0 ?
454  (read_scp ? "scp:tmpf.scp" : "ark:tmpf") :
455  (read_scp ? "scp,bg:tmpf.scp" : "ark,bg:tmpf"));
456  std::vector<std::string> k2;
457  std::vector<double> v2;
458  for (; !sbr.Done(); sbr.Next()) {
459  k2.push_back(sbr.Key());
460  v2.push_back(sbr.Value());
461  }
462  KALDI_ASSERT(sbr.Close());
463  KALDI_ASSERT(k2 == k);
464  if (binary) {
465  KALDI_ASSERT(v2 == v);
466  } else {
467  KALDI_ASSERT(v2.size() == v.size());
468  for (size_t i = 0; i < v2.size(); i++)
469  KALDI_ASSERT(ApproxEqual(v[i], v2[i]));
470  }
471  unlink("tmpf.scp");
472  unlink("tmpf");
473 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialDoubleMatrixBoth()

void kaldi::UnitTestTableSequentialDoubleMatrixBoth ( bool  binary,
bool  read_scp 
)

Definition at line 652 of file kaldi-table-test.cc.

References ApproxEqual(), CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, rnnlm::j, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandGauss(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

652  {
653  int32 sz = Rand() % 10;
654  std::vector<std::string> k;
655  std::vector<Matrix<double>*> v;
656 
657  for (int32 i = 0; i < sz; i++) {
658  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
659  // some single quotes too but it doesn't really matter.
660  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
661  // different lengths.
662  v.push_back(new Matrix<double>(1 + Rand()%4, 1 + Rand() % 4));
663  for (int32 i = 0; i < v.back()->NumRows(); i++)
664  for (int32 j = 0; j < v.back()->NumCols(); j++)
665  (*(v.back()))(i, j) = RandGauss();
666  }
667 
668  bool ans;
669  DoubleMatrixWriter bw(binary ? "b,ark,scp:tmpf,tmpf.scp" :
670  "t,ark,scp:tmpf,tmpf.scp");
671  for (int32 i = 0; i < sz; i++) {
672  bw.Write(k[i], *(v[i]));
673  }
674  ans = bw.Close();
675  KALDI_ASSERT(ans);
676 
677  SequentialDoubleMatrixReader sbr(read_scp ? "scp:tmpf.scp" : "ark:tmpf");
678  std::vector<std::string> k2;
679  std::vector<Matrix<double>* > v2;
680  for (; !sbr.Done(); sbr.Next()) {
681  k2.push_back(sbr.Key());
682  v2.push_back(new Matrix<double>(sbr.Value()));
683  }
684  KALDI_ASSERT(sbr.Close());
685  KALDI_ASSERT(k2 == k);
686  if (binary) {
687  for (size_t i = 0; i < v2.size(); i++)
688  KALDI_ASSERT(v2[i]->ApproxEqual(*(v[i]), 1.0e-10));
689  } else {
690  KALDI_ASSERT(v2.size() == v.size());
691  for (size_t i = 0; i < v2.size(); i++)
692  KALDI_ASSERT(v2[i]->ApproxEqual(*(v[i])));
693  }
694  for (int32 i = 0; i < sz; i++) {
695  delete v[i];
696  delete v2[i];
697  }
698  unlink("tmpf");
699  unlink("tmpf.scp");
700 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTestTableSequentialInt32()

void kaldi::UnitTestTableSequentialInt32 ( bool  binary)

Definition at line 323 of file kaldi-table-test.cc.

References CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandInt(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

323  {
324  int32 sz = Rand() % 10;
325  std::vector<std::string> k;
326  std::vector<int32> v;
327 
328  for (int32 i = 0; i < sz; i++) {
329  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
330  // some single quotes too but it doesn't really matter.
331  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
332  // different lengths.
333  v.push_back(Rand());
334  }
335 
336  bool ans;
337  Int32Writer bw(binary ? "b,ark:tmpf" : "t,ark:tmpf");
338  for (int32 i = 0; i < sz; i++) {
339  bw.Write(k[i], v[i]);
340  }
341  ans = bw.Close();
342  KALDI_ASSERT(ans);
343 
344  SequentialInt32Reader sbr(RandInt(0, 1) == 0 ? "ark:tmpf" : "ark,bg:tmpf");
345  std::vector<std::string> k2;
346  std::vector<int32> v2;
347  for (; !sbr.Done(); sbr.Next()) {
348  k2.push_back(sbr.Key());
349  v2.push_back(sbr.Value());
350  }
351  KALDI_ASSERT(sbr.Close());
352  KALDI_ASSERT(k2 == k);
353  KALDI_ASSERT(v2 == v);
354 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialInt32PairVectorBoth()

void kaldi::UnitTestTableSequentialInt32PairVectorBoth ( bool  binary,
bool  read_scp 
)

Definition at line 518 of file kaldi-table-test.cc.

References CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, rnnlm::j, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandInt(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

518  {
519  int32 sz = Rand() % 10;
520  std::vector<std::string> k(sz);
521  std::vector<std::vector<std::pair<int32, int32> > > v(sz);
522 
523  for (int32 i = 0; i < sz; i++) {
524  k[i] = CharToString('a' + static_cast<char>(i)); // This gives us
525  // some single quotes too but it doesn't really matter.
526  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
527  // different lengths.
528  int32 sz2 = Rand() % 5;
529  for (int32 j = 0; j < sz2; j++)
530  v[i].push_back(std::pair<int32, int32>(Rand() % 10, Rand() % 10));
531  }
532 
533  bool ans;
534  Int32PairVectorWriter bw(binary ? "b,ark,scp:tmpf,tmpf.scp" :
535  "t,ark,scp:tmpf,tmpf.scp");
536  for (int32 i = 0; i < sz; i++) {
537  bw.Write(k[i], v[i]);
538  }
539  ans = bw.Close();
540  KALDI_ASSERT(ans);
541 
543  (read_scp ? "scp:tmpf.scp" : "ark:tmpf") :
544  (read_scp ? "scp,bg:tmpf.scp" : "ark,bg:tmpf"));
545  std::vector<std::string> k2;
546  std::vector<std::vector<std::pair<int32, int32> > > v2;
547  for (; !sbr.Done(); sbr.Next()) {
548  k2.push_back(sbr.Key());
549  v2.push_back(sbr.Value());
550  }
551  KALDI_ASSERT(sbr.Close());
552  KALDI_ASSERT(k2 == k);
553  KALDI_ASSERT(v2 == v);
554 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialInt32Script()

void kaldi::UnitTestTableSequentialInt32Script ( bool  binary)

Definition at line 600 of file kaldi-table-test.cc.

References SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandInt(), ReadScriptFile(), SequentialTableReader< Holder >::Value(), TableWriter< Holder >::Write(), and WriteScriptFile().

Referenced by main().

600  {
601  int32 sz = Rand() % 10;
602  std::vector<std::pair<std::string, std::string> > script;
603  std::vector<std::string> k;
604  std::vector<int32> v;
605 
606  for (int32 i = 0; i < sz; i++) {
607  char buf[3];
608  buf[0] = 'a' + static_cast<char>(i);
609  buf[1] = (i%2 == 0 ? 'b'+static_cast<char>(i) : '\0');
610  buf[2] = '\0';
611  k.push_back(std::string(buf));
612  script.push_back(std::make_pair(std::string(buf),
613  std::string(buf) + ".tmp"));
614  v.push_back(Rand());
615  }
616 
617  WriteScriptFile("tmp.scp", script);
618  {
619  std::vector<std::pair<std::string, std::string> > script2;
620  ReadScriptFile("tmp.scp", true, &script2);
621  KALDI_ASSERT(script2 == script); // This tests WriteScriptFile and
622  // ReadScriptFile.
623  }
624 
625  bool ans;
626  Int32Writer bw(binary ? "b,scp:tmp.scp" : "t,scp:tmp.scp");
627  for (int32 i = 0; i < sz; i++) {
628  bw.Write(k[i], v[i]);
629  }
630  ans = bw.Close();
631  KALDI_ASSERT(ans);
632 
633  SequentialInt32Reader sbr(RandInt(0, 1) == 0 ?
634  "scp:tmp.scp" : "scp,bg:tmp.scp");
635  std::vector<std::string> k2;
636  std::vector<int32> v2;
637  for (; !sbr.Done(); sbr.Next()) {
638  k2.push_back(sbr.Key());
639  v2.push_back(sbr.Value());
640  }
641  KALDI_ASSERT(sbr.Close());
642 
643  unlink("tmp.scp");
644  for (size_t i = 0; i < script.size(); i++) {
645  unlink(script[i].second.c_str());
646  }
647  KALDI_ASSERT(k2 == k);
648  KALDI_ASSERT(v2 == v);
649 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
bool WriteScriptFile(std::ostream &os, const std::vector< std::pair< std::string, std::string > > &script)
Definition: kaldi-table.cc:83
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
bool ReadScriptFile(const std::string &rxfilename, bool warn, std::vector< std::pair< std::string, std::string > > *script_out)
Definition: kaldi-table.cc:26
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialInt32VectorBoth()

void kaldi::UnitTestTableSequentialInt32VectorBoth ( bool  binary,
bool  read_scp 
)

Definition at line 477 of file kaldi-table-test.cc.

References CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, rnnlm::j, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), RandInt(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

477  {
478  int32 sz = Rand() % 10;
479  std::vector<std::string> k;
480  std::vector<std::vector<int32> > v;
481 
482  for (int32 i = 0; i < sz; i++) {
483  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
484  // some single quotes too but it doesn't really matter.
485  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
486  // different lengths.
487  v.push_back(std::vector<int32>());
488  int32 sz2 = Rand() % 5;
489  for (int32 j = 0; j < sz2; j++)
490  v.back().push_back(Rand() % 100);
491  }
492 
493  bool ans;
494  Int32VectorWriter bw(binary ? "b,ark,scp:tmpf,tmpf.scp" :
495  "t,ark,scp:tmpf,tmpf.scp");
496  for (int32 i = 0; i < sz; i++) {
497  bw.Write(k[i], v[i]);
498  }
499  ans = bw.Close();
500  KALDI_ASSERT(ans);
501 
502  SequentialInt32VectorReader sbr(RandInt(0, 1) == 0 ?
503  (read_scp ? "scp:tmpf.scp" : "ark:tmpf") :
504  (read_scp ? "scp,bg:tmpf.scp" : "ark,bg:tmpf"));
505  std::vector<std::string> k2;
506  std::vector<std::vector<int32> > v2;
507  for (; !sbr.Done(); sbr.Next()) {
508  k2.push_back(sbr.Key());
509  v2.push_back(sbr.Value());
510  }
511  KALDI_ASSERT(sbr.Close());
512  KALDI_ASSERT(k2 == k);
513  KALDI_ASSERT(v2 == v);
514 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
int32 RandInt(int32 min_val, int32 max_val, struct RandomState *state)
Definition: kaldi-math.cc:95

◆ UnitTestTableSequentialInt32VectorVectorBoth()

void kaldi::UnitTestTableSequentialInt32VectorVectorBoth ( bool  binary,
bool  read_scp 
)

Definition at line 558 of file kaldi-table-test.cc.

References CharToString(), SequentialTableReader< Holder >::Close(), TableWriter< Holder >::Close(), SequentialTableReader< Holder >::Done(), rnnlm::i, rnnlm::j, KALDI_ASSERT, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), Rand(), SequentialTableReader< Holder >::Value(), and TableWriter< Holder >::Write().

Referenced by main().

558  {
559  int32 sz = Rand() % 10;
560  std::vector<std::string> k;
561  std::vector<std::vector<std::vector<int32> > > v;
562 
563  for (int32 i = 0; i < sz; i++) {
564  k.push_back(CharToString('a' + static_cast<char>(i))); // This gives us
565  // some single quotes too but it doesn't really matter.
566  if (i%2 == 0) k.back() = k.back() + CharToString('a' + i); // make them
567  // different lengths.
568  v.push_back(std::vector<std::vector<int32> >());
569  int32 sz2 = Rand() % 5;
570  for (int32 j = 0; j < sz2; j++) {
571  v.back().push_back(std::vector<int32>());
572  int32 sz3 = Rand() % 2;
573  for (int32 k = 0; k < sz3; k++)
574  v.back().back().push_back(Rand() % 100);
575  }
576  }
577 
578  bool ans;
579  Int32VectorVectorWriter bw(binary ? "b,ark,scp:tmpf,tmpf.scp" :
580  "t,ark,scp:tmpf,tmpf.scp");
581  for (int32 i = 0; i < sz; i++) {
582  bw.Write(k[i], v[i]);
583  }
584  ans = bw.Close();
585  KALDI_ASSERT(ans);
586 
587  SequentialInt32VectorVectorReader sbr(read_scp ? "scp:tmpf.scp" : "ark:tmpf");
588  std::vector<std::string> k2;
589  std::vector<std::vector<std::vector<int32> > > v2;
590  for (; !sbr.Done(); sbr.Next()) {
591  k2.push_back(sbr.Key());
592  v2.push_back(sbr.Value());
593  }
594  KALDI_ASSERT(sbr.Close());
595  KALDI_ASSERT(k2 == k);
596  KALDI_ASSERT(v2 == v);
597 }
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
std::string CharToString(const char &c)
Definition: kaldi-utils.cc:36
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestTanh()

static void kaldi::UnitTestTanh ( )
static

Definition at line 2356 of file matrix-lib-test.cc.

References AssertEqual(), MatrixBase< Real >::DiffTanh(), Exp(), rnnlm::i, Rand(), and MatrixBase< Real >::Tanh().

2356  {
2357  for (MatrixIndexT i = 0; i < 10; i++) {
2358  MatrixIndexT dimM = 5 + Rand() % 10, dimN = 5 + Rand() % 10;
2359  Matrix<Real> M(dimM, dimN), P(dimM, dimN), Q(dimM, dimN), R(dimM, dimN);
2360  M.SetRandn();
2361  P.SetRandn();
2362  Matrix<Real> N(M);
2363  for(int32 r = 0; r < dimM; r++) {
2364  for (int32 c = 0; c < dimN; c++) {
2365  Real x = N(r, c);
2366  if (x > 0.0) {
2367  x = -1.0 + 2.0 / (1.0 + Exp(-2.0 * x));
2368  } else {
2369  x = 1.0 - 2.0 / (1.0 + Exp(2.0 * x));
2370  }
2371  N(r, c) = x;
2372  Real out_diff = P(r, c), in_diff = out_diff * (1.0 - x * x);
2373  Q(r, c) = in_diff;
2374  }
2375  }
2376  M.Tanh(M);
2377  R.DiffTanh(N, P);
2378  AssertEqual(M, N);
2379  AssertEqual(Q, R);
2380  }
2381 }
double Exp(double x)
Definition: kaldi-math.h:83
kaldi::int32 int32
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestTopEigs()

static void kaldi::UnitTestTopEigs ( )
static

Definition at line 4518 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), MatrixBase< Real >::AddMatMat(), VectorBase< Real >::ApplyAbs(), AssertEqual(), VectorBase< Real >::CopyDiagFromMat(), VectorBase< Real >::Data(), SpMatrix< Real >::Eig(), rnnlm::i, SpMatrix< Real >::IsUnit(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, NonUnitness(), RandGauss(), and SpMatrix< Real >::TopEigs().

4518  {
4519  for (MatrixIndexT i = 0; i < 2; i++) {
4520  // Previously tested with this but takes too long.
4521  MatrixIndexT dim = 400, num_eigs = 100;
4522  SpMatrix<Real> mat(dim);
4523  for (MatrixIndexT i = 0; i < dim; i++)
4524  for (MatrixIndexT j = 0; j <= i; j++)
4525  mat(i, j) = RandGauss();
4526 
4527  Matrix<Real> P(dim, num_eigs);
4528  Vector<Real> s(num_eigs);
4529  mat.TopEigs(&s, &P);
4530  { // P should have orthogonal columns. Check this.
4531  SpMatrix<Real> S(num_eigs);
4532  S.AddMat2(1.0, P, kTrans, 0.0);
4533  KALDI_LOG << "Non-unit-ness of S is " << NonUnitness(S);
4534  KALDI_ASSERT(S.IsUnit(1.0e-04));
4535  }
4536  // Note: we call the matrix "mat" by the name "S" below.
4537  Matrix<Real> SP(dim, num_eigs); // diag of P^T SP should be eigs.
4538  SP.AddSpMat(1.0, mat, P, kNoTrans, 0.0);
4539  Matrix<Real> PSP(num_eigs, num_eigs);
4540  PSP.AddMatMat(1.0, P, kTrans, SP, kNoTrans, 0.0);
4541  Vector<Real> s2(num_eigs);
4542  s2.CopyDiagFromMat(PSP);
4543  AssertEqual(s, s2);
4544  // Now check that eigs are close to real top eigs.
4545  {
4546  Matrix<Real> fullP(dim, dim);
4547  Vector<Real> fulls(dim);
4548  mat.Eig(&fulls, &fullP);
4549  KALDI_LOG << "Approximate eigs are " << s;
4550  // find sum of largest-abs-value eigs.
4551  fulls.ApplyAbs();
4552  std::sort(fulls.Data(), fulls.Data() + dim);
4553  SubVector<Real> tmp(fulls, dim - num_eigs, num_eigs);
4554  KALDI_LOG << "abs(real eigs) are " << tmp;
4555  BaseFloat real_sum = tmp.Sum();
4556  s.ApplyAbs();
4557  BaseFloat approx_sum = s.Sum();
4558  KALDI_LOG << "real sum is " << real_sum << ", approx_sum = " << approx_sum;
4559  }
4560  }
4561 }
Packed symetric matrix class.
Definition: matrix-common.h:62
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
A class for storing matrices.
Definition: kaldi-matrix.h:823
float BaseFloat
Definition: kaldi-types.h:29
int32 MatrixIndexT
Definition: matrix-common.h:98
static Real NonUnitness(const SpMatrix< Real > &S)
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501

◆ UnitTestTp2()

static void kaldi::UnitTestTp2 ( )
static

Definition at line 1968 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2(), AssertEqual(), kNoTrans, kTrans, Rand(), and PackedMatrix< Real >::SetRandn().

1968  {
1969  // Tests AddTp2()
1970  for (MatrixIndexT iter = 0; iter < 4; iter++) {
1971  MatrixIndexT dimM = 10 + Rand()%3;
1972 
1973  TpMatrix<Real> T(dimM);
1974  T.SetRandn();
1975 
1976  Matrix<Real> M(T);
1977 
1978  SpMatrix<Real> A(dimM), B(dimM);
1979  A.AddTp2(0.5, T, (iter < 2 ? kNoTrans : kTrans), 0.0);
1980  B.AddMat2(0.5, M, (iter < 2 ? kNoTrans : kTrans), 0.0);
1981  AssertEqual(A, B);
1982  }
1983 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestTp2Sp()

static void kaldi::UnitTestTp2Sp ( )
static

Definition at line 1943 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2Sp(), AssertEqual(), rnnlm::i, rnnlm::j, kNoTrans, kTrans, Rand(), and PackedMatrix< Real >::SetRandn().

1943  {
1944  // Tests AddTp2Sp()
1945  for (MatrixIndexT iter = 0; iter < 4; iter++) {
1946  MatrixIndexT dimM = 10 + Rand()%3;
1947 
1948  TpMatrix<Real> T(dimM);
1949  T.SetRandn();
1950  SpMatrix<Real> S(dimM);
1951  S.SetRandn();
1952 
1953  Matrix<Real> M(T);
1954  for ( MatrixIndexT i = 0; i < dimM; i++)
1955  for (MatrixIndexT j = 0; j < dimM; j++) {
1956  if (j <= i) AssertEqual(T(i,j), M(i,j));
1957  else AssertEqual(M(i,j), 0.0);
1958  }
1959 
1960  SpMatrix<Real> A(dimM), B(dimM);
1961  A.AddTp2Sp(0.5, T, (iter < 2 ? kNoTrans : kTrans), S, 0.0);
1962  B.AddMat2Sp(0.5, M, (iter < 2 ? kNoTrans : kTrans), S, 0.0);
1963  AssertEqual(A, B);
1964  }
1965 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestTpInvert()

static void kaldi::UnitTestTpInvert ( )
static

Definition at line 2180 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), TpMatrix< Real >::CopyFromTp(), rnnlm::i, TpMatrix< Real >::Invert(), MatrixBase< Real >::IsUnit(), rnnlm::j, KALDI_ASSERT, kNoTrans, PackedMatrix< Real >::NumRows(), Rand(), and RandGauss().

2180  {
2181  for (MatrixIndexT i = 0;i < 30;i++) {
2182  MatrixIndexT dimM = 20 + Rand()%10;
2183  TpMatrix<Real> M(dimM);
2184  for (MatrixIndexT i = 0;i < M.NumRows();i++) {
2185  for (MatrixIndexT j = 0;j < i;j++) M(i, j) = RandGauss();
2186  M(i, i) = 20 * std::max((Real)0.1, (Real) RandGauss()); // make sure invertible by making it diagonally dominant (-ish)
2187  }
2188  TpMatrix<Real> N(dimM);
2189  N.CopyFromTp(M);
2190  N.Invert();
2191  TpMatrix<Real> O(dimM);
2192 
2193  Matrix<Real> Mm(dimM, dimM), Nm(dimM, dimM), Om(dimM, dimM);
2194  Mm.CopyFromTp(M); Nm.CopyFromTp(N);
2195 
2196  Om.AddMatMat(1.0, Mm, kNoTrans, Nm, kNoTrans, 0.0);
2197  KALDI_ASSERT(Om.IsUnit(0.001));
2198  }
2199 }
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestTrace() [1/2]

static void kaldi::UnitTestTrace ( )
static

Definition at line 119 of file cu-test.cc.

References KALDI_LOG, PackedMatrix< Real >::SetRandn(), CuPackedMatrix< Real >::Trace(), and SpMatrix< Real >::Trace().

119  {
120  for (MatrixIndexT iter = 1; iter < 18; iter++) {
121  MatrixIndexT dim = iter;
122  KALDI_LOG << "dim is : " << iter;
123  SpMatrix<Real> A(dim);
124  A.SetRandn();
125  CuSpMatrix<Real> B(A);
126  KALDI_LOG << "cpu trace is : " << A.Trace();
127  KALDI_LOG << "gpu trace is : " << B.Trace();
128  }
129  /*
130  Vector<Real> tim(100);
131  Vector<Real> d(100);
132  for (MatrixIndexT iter = 0; iter < 100; iter++) {
133  MatrixIndexT dim = 10000 + Rand() % 400;
134  Matrix<Real> A(dim,dim);
135  A.SetRandn();
136  CuMatrix<Real> B(A);
137  CuSpMatrix<Real> C(B,kTakeLower);
138  clock_t t1 = clock();
139  tim(iter) = C.Trace();
140  clock_t t2 = clock();
141  //tim(iter) = t2 - t1;
142  d(iter) = dim;
143  KALDI_LOG << tim(iter) << iter;
144  KALDI_LOG << d(iter) << iter;
145  }
146  KALDI_LOG << "tim is " << tim;
147  KALDI_LOG << "dim is " << d;
148  */
149 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestTrace() [2/2]

static void kaldi::UnitTestTrace ( )
static

Definition at line 3327 of file matrix-lib-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::AddMatMatMat(), approx_equal(), AssertEqual(), MatrixBase< Real >::CopyFromMat(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, Rand(), PackedMatrix< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), MatrixBase< Real >::Trace(), TraceMat(), TraceMatMat(), TraceMatMatMat(), TraceMatMatMatMat(), TraceMatSpMat(), TraceMatSpMatSp(), and TraceSpMat().

3327  {
3328 
3329  for (MatrixIndexT i = 0;i < 5;i++) {
3330  MatrixIndexT dimM = 20 + Rand()%10, dimN = 20 + Rand()%10, dimO = 20 + Rand()%10, dimP = dimM;
3331  Matrix<Real> A(dimM, dimN), B(dimN, dimO), C(dimO, dimP);
3332  A.SetRandn(); B.SetRandn(); C.SetRandn();
3333  Matrix<Real> AT(dimN, dimM), BT(dimO, dimN), CT(dimP, dimO);
3334  AT.CopyFromMat(A, kTrans); BT.CopyFromMat(B, kTrans); CT.CopyFromMat(C, kTrans);
3335 
3336  Matrix<Real> AB(dimM, dimO);
3337  AB.AddMatMat(1.0, A, kNoTrans, B, kNoTrans, 0.0);
3338  Matrix<Real> BC(dimN, dimP);
3339  BC.AddMatMat(1.0, B, kNoTrans, C, kNoTrans, 0.0);
3340  Matrix<Real> ABC(dimM, dimP);
3341  ABC.AddMatMat(1.0, A, kNoTrans, BC, kNoTrans, 0.0);
3342 
3343  Real
3344  t1 = TraceMat(ABC),
3345  t2 = ABC.Trace(),
3346  t3 = TraceMatMat(A, BC),
3347  t4 = TraceMatMat(AT, BC, kTrans),
3348  t5 = TraceMatMat(BC, AT, kTrans),
3349  t6 = TraceMatMatMat(A, kNoTrans, B, kNoTrans, C, kNoTrans),
3350  t7 = TraceMatMatMat(AT, kTrans, B, kNoTrans, C, kNoTrans),
3351  t8 = TraceMatMatMat(AT, kTrans, BT, kTrans, C, kNoTrans),
3352  t9 = TraceMatMatMat(AT, kTrans, BT, kTrans, CT, kTrans);
3353 
3354  Matrix<Real> ABC1(dimM, dimP); // tests AddMatMatMat.
3355  ABC1.AddMatMatMat(1.0, A, kNoTrans, B, kNoTrans, C, kNoTrans, 0.0);
3356  AssertEqual(ABC, ABC1);
3357 
3358  Matrix<Real> ABC2(dimM, dimP); // tests AddMatMatMat.
3359  ABC2.AddMatMatMat(0.25, A, kNoTrans, B, kNoTrans, C, kNoTrans, 0.0);
3360  ABC2.AddMatMatMat(0.25, AT, kTrans, B, kNoTrans, C, kNoTrans, 2.0); // the extra 1.0 means another 0.25.
3361  ABC2.AddMatMatMat(0.125, A, kNoTrans, BT, kTrans, C, kNoTrans, 1.0);
3362  ABC2.AddMatMatMat(0.125, A, kNoTrans, B, kNoTrans, CT, kTrans, 1.0);
3363  AssertEqual(ABC, ABC2);
3364 
3365  Real tol = 0.001;
3366  KALDI_ASSERT((std::abs(t1-t2) < tol) && (std::abs(t2-t3) < tol) && (std::abs(t3-t4) < tol)
3367  && (std::abs(t4-t5) < tol) && (std::abs(t5-t6) < tol) && (std::abs(t6-t7) < tol)
3368  && (std::abs(t7-t8) < tol) && (std::abs(t8-t9) < tol));
3369  }
3370 
3371  for (MatrixIndexT i = 0;i < 5;i++) {
3372  MatrixIndexT dimM = 20 + Rand()%10, dimN = 20 + Rand()%10;
3373  SpMatrix<Real> S(dimM), T(dimN);
3374  S.SetRandn(); T.SetRandn();
3375  Matrix<Real> M(dimM, dimN), O(dimM, dimN);
3376  M.SetRandn(); O.SetRandn();
3377  Matrix<Real> sM(S), tM(T);
3378 
3379  Real x1 = TraceMatMat(tM, tM);
3380  Real x2 = TraceSpMat(T, tM);
3381  KALDI_ASSERT(approx_equal(x1, x2) || fabs(x1-x2) < 0.1);
3382 
3383  Real t1 = TraceMatMatMat(M, kNoTrans, tM, kNoTrans, M, kTrans);
3384  Real t2 = TraceMatSpMat(M, kNoTrans, T, M, kTrans);
3385  KALDI_ASSERT(approx_equal(t1, t2) || fabs(t1-12) < 0.1);
3386 
3387  Real u1 = TraceMatSpMatSp(M, kNoTrans, T, O, kTrans, S);
3388  Real u2 = TraceMatMatMatMat(M, kNoTrans, tM, kNoTrans, O, kTrans, sM, kNoTrans);
3389  KALDI_ASSERT(approx_equal(u1, u2) || fabs(u1-u2) < 0.1);
3390  }
3391 
3392 }
Real TraceMatMatMat(const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const MatrixBase< Real > &C, MatrixTransposeType transC)
Returns tr(A B C)
Packed symetric matrix class.
Definition: matrix-common.h:62
double TraceMat(const MatrixBase< Real > &A)
Returns trace of matrix.
Real TraceSpMat(const SpMatrix< Real > &A, const MatrixBase< Real > &B)
Returns tr(A B).
Definition: sp-matrix.cc:389
A class for storing matrices.
Definition: kaldi-matrix.h:823
static bool approx_equal(Real a, Real b)
int32 MatrixIndexT
Definition: matrix-common.h:98
Real TraceMatSpMat(const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const MatrixBase< Real > &C, MatrixTransposeType transC)
Returns tr(A B C) (A and C may be transposed as specified by transA and transC).
Definition: sp-matrix.cc:415
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
Real TraceMatSpMatSp(const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const MatrixBase< Real > &C, MatrixTransposeType transC, const SpMatrix< Real > &D)
Returns tr (A B C D) (A and C may be transposed as specified by transA and transB).
Definition: sp-matrix.cc:438
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
Real TraceMatMatMatMat(const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const MatrixBase< Real > &C, MatrixTransposeType transC, const MatrixBase< Real > &D, MatrixTransposeType transD)
Returns tr(A B C D)

◆ UnitTestTraceProduct()

static void kaldi::UnitTestTraceProduct ( )
static

Definition at line 1277 of file matrix-lib-test.cc.

References KALDI_ASSERT, KALDI_LOG, kTrans, Rand(), MatrixBase< Real >::SetRandn(), and TraceMatMat().

1277  {
1278  for (MatrixIndexT iter = 0;iter < 5;iter++) { // First test the 2 det routines are the same
1279  int dimM = 10 + Rand() % 10, dimN = 10 + Rand() % 10;
1280  Matrix<Real> M(dimM, dimN), N(dimM, dimN);
1281 
1282  M.SetRandn();
1283  N.SetRandn();
1284  Matrix<Real> Nt(N, kTrans);
1285  Real a = TraceMatMat(M, Nt), b = TraceMatMat(M, N, kTrans);
1286  printf("m = %d, n = %d\n", dimM, dimN);
1287  KALDI_LOG << a << " " << b;
1288  KALDI_ASSERT(std::abs(a-b) < 0.1);
1289  }
1290 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
Real TraceMatMat(const MatrixBase< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType trans)
We need to declare this here as it will be a friend function.
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestTraceSpSpLower()

static void kaldi::UnitTestTraceSpSpLower ( )
static

Definition at line 2865 of file matrix-lib-test.cc.

References AssertEqual(), Rand(), PackedMatrix< Real >::Scale(), PackedMatrix< Real >::ScaleDiag(), PackedMatrix< Real >::SetRandn(), TraceSpSp(), and TraceSpSpLower().

2865  {
2866 
2867  MatrixIndexT N = 1 + Rand() % 10;
2868  SpMatrix<Real> S(N), T(N);
2869  S.SetRandn();
2870  T.SetRandn();
2871 
2872  SpMatrix<Real> Sfast(S);
2873  Sfast.Scale(2.0);
2874  Sfast.ScaleDiag(0.5);
2875 
2876  AssertEqual(TraceSpSp(S, T), TraceSpSpLower(Sfast, T));
2877 }
Packed symetric matrix class.
Definition: matrix-common.h:62
int32 MatrixIndexT
Definition: matrix-common.h:98
double TraceSpSp(const SpMatrix< double > &A, const SpMatrix< double > &B)
Definition: sp-matrix.cc:326
Real TraceSpSpLower(const SpMatrix< Real > &A, const SpMatrix< Real > &B)
Definition: sp-matrix.cc:1171
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestTrain()

void kaldi::UnitTestTrain ( )

Definition at line 67 of file logistic-regression-test.cc.

References MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::CopyFromMat(), LogisticRegression::GetObjfAndGrad(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, Log(), LogisticRegressionConfig::max_steps, LogisticRegressionConfig::normalizer, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), Rand(), MatrixBase< Real >::SetRandn(), LogisticRegression::Train(), and LogisticRegression::weights_.

Referenced by main().

67  {
68 
69  int32 n_features = Rand() % 600 + 10,
70  n_xs = Rand() % 200 + 100,
71  n_labels = Rand() % 20 + 10;
72  double normalizer = 0.01;
73  Matrix<BaseFloat> xs(n_xs, n_features);
74  xs.SetRandn();
75 
76  std::vector<int32> ys;
77  for (int32 i = 0; i < n_xs; i++) {
78  ys.push_back(Rand() % n_labels);
79  }
80 
82  conf.max_steps = 20;
83  conf.normalizer = normalizer;
84  // Train the classifier
86  classifier.Train(xs, ys, conf);
87 
88  // Internally in LogisticRegression we add an additional element to
89  // the x vectors: a 1.0 which handles the prior.
90  Matrix<BaseFloat> xs_with_prior(n_xs, n_features + 1);
91  for (int32 i = 0; i < n_xs; i++) {
92  xs_with_prior(i, n_features) = 1.0;
93  }
94  SubMatrix<BaseFloat> sub_xs(xs_with_prior, 0, n_xs, 0, n_features);
95  sub_xs.CopyFromMat(xs);
96 
97  Matrix<BaseFloat> xw(n_xs, n_labels);
98  xw.AddMatMat(1.0, xs_with_prior, kNoTrans, classifier.weights_,
99  kTrans, 0.0);
100 
101  Matrix<BaseFloat> grad(classifier.weights_.NumRows(),
102  classifier.weights_.NumCols());
103 
104  double objf_trained = classifier.GetObjfAndGrad(xs_with_prior,
105  ys, xw, &grad, normalizer);
106 
107  // Calculate objective function using a random weight matrix.
108  Matrix<BaseFloat> xw_rand(n_xs, n_labels);
109 
110  Matrix<BaseFloat> weights_rand(classifier.weights_);
111  weights_rand.SetRandn();
112  xw.AddMatMat(1.0, xs_with_prior, kNoTrans, weights_rand,
113  kTrans, 0.0);
114 
115  // Verify that the objective function after training is better
116  // than the objective function with a random weight matrix.
117  double objf_rand_w = classifier.GetObjfAndGrad(xs_with_prior, ys,
118  xw_rand, &grad, normalizer);
119  KALDI_ASSERT(objf_trained > objf_rand_w);
120  KALDI_ASSERT(objf_trained > Log(1.0 / n_xs));
121 }
BaseFloat GetObjfAndGrad(const Matrix< BaseFloat > &xs, const std::vector< int32 > &ys, const Matrix< BaseFloat > &xw, Matrix< BaseFloat > *grad, BaseFloat normalizer)
MatrixIndexT NumCols() const
Returns number of columns (or zero for empty matrix).
Definition: kaldi-matrix.h:67
kaldi::int32 int32
void Train(const Matrix< BaseFloat > &xs, const std::vector< int32 > &ys, const LogisticRegressionConfig &conf)
double Log(double x)
Definition: kaldi-math.h:100
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
Matrix< BaseFloat > weights_
Sub-matrix representation.
Definition: kaldi-matrix.h:988

◆ UnitTestTranspose()

static void kaldi::UnitTestTranspose ( )
static

Definition at line 3491 of file matrix-lib-test.cc.

References AssertEqual(), kTrans, Rand(), MatrixBase< Real >::SetRandn(), and Matrix< Real >::Transpose().

3491  {
3492 
3493  Matrix<Real> M(Rand() % 5 + 1, Rand() % 10 + 1);
3494  M.SetRandn();
3495  Matrix<Real> N(M, kTrans);
3496  N.Transpose();
3497  AssertEqual(M, N);
3498 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestTransposeScatter()

static void kaldi::UnitTestTransposeScatter ( )
static

Definition at line 2076 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2Sp(), MatrixBase< Real >::AddMatMat(), MatrixBase< Real >::CopyFromSp(), rnnlm::i, rnnlm::j, KALDI_ASSERT, kNoTrans, kTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), PackedMatrix< Real >::NumRows(), Rand(), RandGauss(), and Matrix< Real >::Resize().

2076  {
2077  for (MatrixIndexT iter = 0;iter < 10;iter++) {
2078 
2079  MatrixIndexT dimA = 10 + Rand()%3;
2080  MatrixIndexT dimO = 10 + Rand()%3;
2081  Matrix<Real> Af(dimA, dimA);
2082  SpMatrix<Real> Ap(dimA);
2083  Matrix<Real> M(dimO, dimA);
2084  Matrix<Real> Of(dimO, dimO);
2085  SpMatrix<Real> Op(dimO);
2086  Matrix<Real> A_MT(dimA, dimO);
2087 
2088  for (MatrixIndexT i = 0;i < Ap.NumRows();i++) {
2089  for (MatrixIndexT j = 0; j<=i; j++) {
2090  Ap(i, j) = RandGauss();
2091  }
2092  }
2093  for (MatrixIndexT i = 0;i < M.NumRows();i++) {
2094  for (MatrixIndexT j = 0; j < M.NumCols(); j++) {
2095  M(i, j) = RandGauss();
2096  }
2097  }
2098  /*
2099  std::stringstream ss("1 2 3");
2100  ss >> Ap;
2101  ss.clear();
2102  ss.str("5 6 7 8 9 10");
2103  ss >> M;
2104  */
2105 
2106  Af.CopyFromSp(Ap);
2107  A_MT.AddMatMat(1.0, Af, kNoTrans, M, kTrans, 0.0);
2108  Of.AddMatMat(1.0, M, kNoTrans, A_MT, kNoTrans, 0.0);
2109  Op.AddMat2Sp(1.0, M, kNoTrans, Ap, 0.0);
2110 
2111 
2112  // KALDI_LOG << "A" << '\n' << Af;
2113  // KALDI_LOG << "M" << '\n' << M;
2114  // KALDI_LOG << "Op" << '\n' << Op;
2115 
2116  for (MatrixIndexT i = 0; i < dimO; i++) {
2117  for (MatrixIndexT j = 0; j<=i; j++) {
2118  KALDI_ASSERT(std::abs(Of(i, j) - Op(i, j)) < 0.0001);
2119  }
2120  }
2121 
2122  A_MT.Resize(dimO, dimA);
2123  A_MT.AddMatMat(1.0, Of, kNoTrans, M, kNoTrans, 0.0);
2124  Af.AddMatMat(1.0, M, kTrans, A_MT, kNoTrans, 1.0);
2125  Ap.AddMat2Sp(1.0, M, kTrans, Op, 1.0);
2126 
2127  // KALDI_LOG << "Ap" << '\n' << Ap;
2128  // KALDI_LOG << "Af" << '\n' << Af;
2129 
2130  for (MatrixIndexT i = 0; i < dimA; i++) {
2131  for (MatrixIndexT j = 0; j<=i; j++) {
2132  KALDI_ASSERT(std::abs(Af(i, j) - Ap(i, j)) < 0.01);
2133  }
2134  }
2135  }
2136 }
Packed symetric matrix class.
Definition: matrix-common.h:62
float RandGauss(struct RandomState *state=NULL)
Definition: kaldi-math.h:155
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestTridiag()

static void kaldi::UnitTestTridiag ( )
static

Definition at line 4468 of file matrix-lib-test.cc.

References SpMatrix< Real >::IsTridiagonal(), and KALDI_ASSERT.

4468  {
4469  SpMatrix<Real> A(3);
4470  A(1,1) = 1.0;
4471  A(1, 2) = 1.0;
4472  KALDI_ASSERT(A.IsTridiagonal());
4473  A(0, 2) = 1.0;
4474  KALDI_ASSERT(!A.IsTridiagonal());
4475  A(0, 2) = 0.0;
4476  A(0, 1) = 1.0;
4477  KALDI_ASSERT(A.IsTridiagonal());
4478 }
Packed symetric matrix class.
Definition: matrix-common.h:62
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestTridiagonalize()

static void kaldi::UnitTestTridiagonalize ( )
static

Definition at line 1579 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2Sp(), AssertEqual(), cblas_Xspmv(), rnnlm::i, InitRandNonsingular(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, SpMatrix< Real >::LogDet(), NonUnitness(), Rand(), MatrixBase< Real >::Set(), SpMatrix< Real >::Trace(), and SpMatrix< Real >::Tridiagonalize().

1579  {
1580 
1581  {
1582  float tmp[5];
1583  tmp[4] = 1.0;
1584  cblas_Xspmv(1, 0.0, tmp+2,
1585  tmp+1, 1, 0.0, tmp+4, 1);
1586  KALDI_ASSERT(tmp[4] == 0.0);
1587  }
1588  for (MatrixIndexT i = 0; i < 4; i++) {
1589  MatrixIndexT dim = 40 + Rand() % 4;
1590  // We happened to find out that a 16x16 matrix of 27's causes problems for
1591  // Tridiagonalize.
1592  if (i == 0 || i == 1)
1593  dim = 16;
1594  SpMatrix<Real> S(dim), S2(dim), R(dim), S3(dim);
1595  Matrix<Real> Q(dim, dim);
1596  InitRandNonsingular(&S);
1597  // Very small or large scaling is challenging to qr due to squares that
1598  // could go out of range.
1599  if (Rand() % 3 == 0)
1600  S.Scale(1.0e-15);
1601  else if (Rand() % 2 == 0)
1602  S.Scale(1.0e+15);
1603  if (i == 0 || i == 1) {
1604  Matrix<Real> temp(dim, dim);
1605  if (i == 0)
1606  temp.Set(27.0);
1607  else
1608  temp.Set(-1.61558713e-27);
1609  S.CopyFromMat(temp);
1610  }
1611  SpMatrix<Real> T(S);
1612  T.Tridiagonalize(&Q);
1613  KALDI_LOG << "S trace " << S.Trace() << ", T trace " << T.Trace();
1614  // KALDI_LOG << S << "\n" << T;
1615  AssertEqual(S.Trace(), T.Trace());
1616  // Also test Trace().
1617  Real ans = 0.0;
1618  for (MatrixIndexT j = 0; j < dim; j++) ans += T(j, j);
1619  AssertEqual(ans, T.Trace());
1620  if (S.LogDet() > -50.0) {
1621  // don't check logdet equality if original logdet is very negative- could
1622  // be singular.
1623  AssertEqual(T.LogDet(), S.LogDet());
1624  }
1625  R.AddMat2(1.0, Q, kNoTrans, 0.0);
1626  KALDI_LOG << "Non-unit-ness of R is " << NonUnitness(R);
1627  KALDI_ASSERT(R.IsUnit(0.01)); // Check Q is orthogonal.
1628  S2.AddMat2Sp(1.0, Q, kTrans, T, 0.0);
1629  S3.AddMat2Sp(1.0, Q, kNoTrans, S, 0.0);
1630  //KALDI_LOG << "T is " << T;
1631  //KALDI_LOG << "S is " << S;
1632  //KALDI_LOG << "S2 (should be like S) is " << S2;
1633  //KALDI_LOG << "S3 (should be like T) is " << S3;
1634  AssertEqual(S, S2);
1635  AssertEqual(T, S3);
1636  }
1637 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static Real NonUnitness(const SpMatrix< Real > &S)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void cblas_Xspmv(const float alpha, const int num_rows, const float *Mdata, const float *v, const int v_inc, const float beta, float *y, const int y_inc)
static void InitRandNonsingular(SpMatrix< Real > *M)
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestTridiagonalizeAndQr()

static void kaldi::UnitTestTridiagonalizeAndQr ( )
static

Definition at line 1640 of file matrix-lib-test.cc.

References SpMatrix< Real >::AddMat2Sp(), AssertEqual(), cblas_Xspmv(), rnnlm::i, InitRandNonsingular(), SpMatrix< Real >::IsDiagonal(), rnnlm::j, KALDI_ASSERT, KALDI_LOG, kNoTrans, kTrans, SpMatrix< Real >::LogDet(), NonUnitness(), SpMatrix< Real >::Qr(), Rand(), SpMatrix< Real >::Trace(), and SpMatrix< Real >::Tridiagonalize().

1640  {
1641 
1642  {
1643  float tmp[5];
1644  tmp[4] = 1.0;
1645  // cblas_sspmv(CblasRowMajor, CblasLower, 1, 0.0, tmp+2,
1646  // tmp+1, 1, 0.0, tmp+4, 1);
1647  cblas_Xspmv(1, 0.0, tmp+2,
1648  tmp+1, 1, 0.0, tmp+4, 1);
1649 
1650  KALDI_ASSERT(tmp[4] == 0.0);
1651  }
1652  for (MatrixIndexT i = 0; i < 4; i++) {
1653  MatrixIndexT dim = 50 + Rand() % 4;
1654  SpMatrix<Real> S(dim), S2(dim), R(dim), S3(dim), S4(dim);
1655  Matrix<Real> Q(dim, dim);
1656  InitRandNonsingular(&S);
1657  SpMatrix<Real> T(S);
1658  T.Tridiagonalize(&Q);
1659  KALDI_LOG << "S trace " << S.Trace() << ", T trace " << T.Trace();
1660  // KALDI_LOG << S << "\n" << T;
1661  AssertEqual(S.Trace(), T.Trace());
1662  // Also test Trace().
1663  Real ans = 0.0;
1664  for (MatrixIndexT j = 0; j < dim; j++) ans += T(j, j);
1665  AssertEqual(ans, T.Trace());
1666  AssertEqual(T.LogDet(), S.LogDet());
1667  R.AddMat2(1.0, Q, kNoTrans, 0.0);
1668  KALDI_LOG << "Non-unit-ness of R after tridiag is " << NonUnitness(R);
1669  KALDI_ASSERT(R.IsUnit(0.001)); // Check Q is orthogonal.
1670  S2.AddMat2Sp(1.0, Q, kTrans, T, 0.0);
1671  S3.AddMat2Sp(1.0, Q, kNoTrans, S, 0.0);
1672  //KALDI_LOG << "T is " << T;
1673  //KALDI_LOG << "S is " << S;
1674  //KALDI_LOG << "S2 (should be like S) is " << S2;
1675  //KALDI_LOG << "S3 (should be like T) is " << S3;
1676  AssertEqual(S, S2);
1677  AssertEqual(T, S3);
1678  SpMatrix<Real> T2(T);
1679  T2.Qr(&Q);
1680  R.AddMat2(1.0, Q, kNoTrans, 0.0);
1681  KALDI_LOG << "Non-unit-ness of R after QR is " << NonUnitness(R);
1682  KALDI_ASSERT(R.IsUnit(0.001)); // Check Q is orthogonal.
1683  AssertEqual(T.Trace(), T2.Trace());
1684  KALDI_ASSERT(T2.IsDiagonal());
1685  AssertEqual(T.LogDet(), T2.LogDet());
1686  S4.AddMat2Sp(1.0, Q, kTrans, T2, 0.0);
1687  //KALDI_LOG << "S4 (should be like S) is " << S4;
1688  AssertEqual(S, S4);
1689  }
1690 }
Packed symetric matrix class.
Definition: matrix-common.h:62
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static Real NonUnitness(const SpMatrix< Real > &S)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
void cblas_Xspmv(const float alpha, const int num_rows, const float *Mdata, const float *v, const int v_inc, const float beta, float *y, const int y_inc)
static void InitRandNonsingular(SpMatrix< Real > *M)
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestTriVecSolver()

static void kaldi::UnitTestTriVecSolver ( )
static

Definition at line 4563 of file matrix-lib-test.cc.

References VectorBase< Real >::AddTpVec(), AssertEqual(), rnnlm::i, KALDI_LOG, kNoTrans, kTrans, Rand(), VectorBase< Real >::SetRandn(), PackedMatrix< Real >::SetRandn(), and VectorBase< Real >::Solve().

4563  {
4564  for (MatrixIndexT iter = 0; iter < 100; iter++) {
4565  int32 dim = 1 + Rand() % 20;
4566  Vector<Real> b(dim);
4567  b.SetRandn();
4568  TpMatrix<Real> T(dim);
4569  T.SetRandn();
4570 
4571  bool bad = false;
4572  for (int32 i = 0; i < dim; i++) {
4573  if (fabs(T(i, i)) < 0.2)
4574  bad = true;
4575  }
4576  if (bad) {
4577  // Test may fail due to almost-singular matrix.
4578  continue;
4579  }
4580 
4581  Vector<Real> x(b);
4582  MatrixTransposeType trans = (iter % 2 == 0 ? kTrans : kNoTrans);
4583  x.Solve(T, trans); // solve for T x = b
4584  Vector<Real> b2(dim);
4585  b2.AddTpVec((Real)1.0, T, trans, x, (Real)0.0);
4586  KALDI_LOG << "b is " << b << ", b2 is " << b2;
4587  AssertEqual(b, b2, 0.01);
4588  }
4589 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
Packed symetric matrix class.
Definition: matrix-common.h:63
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ UnitTestVecMatVec()

void kaldi::UnitTestVecMatVec ( )

Definition at line 234 of file cu-vector-test.cc.

References AssertEqual(), rnnlm::i, rnnlm::j, Rand(), CuVectorBase< Real >::SetRandn(), CuMatrixBase< Real >::SetRandn(), and VecMatVec().

234  {
235  int32 NR = 10 + Rand() % 100, NC = 20 + Rand() % 100;
236  CuVector<Real> v1(NR), v2(NC);
237  v1.SetRandn();
238  v2.SetRandn();
239  CuMatrix<Real> M(NR, NC);
240  M.SetRandn();
241  Real sum = 0;
242  for (int32 i = 0; i < NR; i++)
243  for (int32 j = 0; j < NC; j++)
244  sum += v1(i) * M(i, j) * v2(j);
245  Real result = VecMatVec(v1, M, v2);
246  AssertEqual(sum, result);
247 }
kaldi::int32 int32
Real VecMatVec(const VectorBase< Real > &v1, const MatrixBase< Real > &M, const VectorBase< Real > &v2)
Returns .
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestVecmul()

static void kaldi::UnitTestVecmul ( )
static

Definition at line 1770 of file matrix-lib-test.cc.

References VectorBase< Real >::AddMatSvec(), AssertEqual(), rnnlm::i, rnnlm::j, KALDI_ASSERT, kNoTrans, kTrans, Rand(), VectorBase< Real >::SetRandn(), MatrixBase< Real >::SetRandn(), and Matrix< Real >::Transpose().

1770  {
1771  for (MatrixIndexT iter = 0;iter < 5;iter++) {
1772  MatrixTransposeType trans = (iter % 2 == 0 ? kTrans : kNoTrans);
1773  MatrixIndexT dimM = 20 + Rand()%10, dimN = 20 + Rand()%10; // dims between 10 and 20.
1774  Real alpha = 0.333, beta = 0.5;
1775  Matrix<Real> A(dimM, dimN);
1776  if (trans == kTrans) A.Transpose();
1777  A.SetRandn();
1778  Vector<Real> x(dimM), y(dimN);
1779  //x.SetRandn();
1780  y.SetRandn();
1781  Vector<Real> orig_x(x), x2(x);
1782 
1783  x.AddMatVec(alpha, A, trans, y, beta); // x = A * y + beta*x.
1784  x2.AddMatSvec(alpha, A, trans, y, beta); // x = A * y + beta*x
1785 
1786  for (MatrixIndexT i = 0; i < dimM; i++) {
1787  double sum = beta * orig_x(i);
1788  for (MatrixIndexT j = 0; j < dimN; j++) {
1789  if (trans == kNoTrans) {
1790  sum += alpha * A(i, j) * y(j);
1791  } else {
1792  sum += alpha * A(j, i) * y(j);
1793  }
1794  }
1795  KALDI_ASSERT(std::abs(sum - x(i)) < 0.0001);
1796  }
1797  AssertEqual(x, x2);
1798  }
1799 
1800 }
A class for storing matrices.
Definition: kaldi-matrix.h:823
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestVector()

static void kaldi::UnitTestVector ( )
static

Definition at line 406 of file cu-test.cc.

References AssertEqual(), CuVectorBase< Real >::CopyToVec(), CuVectorBase< Real >::MulElements(), VectorBase< Real >::MulElements(), Rand(), CuVectorBase< Real >::Scale(), VectorBase< Real >::Scale(), VectorBase< Real >::SetRandn(), and CuVectorBase< Real >::SetRandn().

406  {
407  // Scale
408  for (MatrixIndexT iter = 0; iter < 10; iter++) {
409  int32 dim = 24 + Rand() % 10;
410  Vector<Real> A(dim);
411  A.SetRandn();
412  CuVector<Real> B(A);
413  Vector<Real> C(dim);
414  Real r = 1.43;
415  B.Scale(r);
416  B.CopyToVec(&C);
417  A.Scale(r);
418  //KALDI_LOG << A;
419  //KALDI_LOG << (A.Scale(r));
420  //KALDI_LOG << C;
421  AssertEqual(A, C);
422  }
423 
424  for (MatrixIndexT iter = 0; iter < 10; iter++) {
425  int32 dim = 15 + Rand() % 10;
426  CuVector<Real> A(dim);
427  CuVector<Real> B(dim);
428  Vector<Real> A1(dim);
429  Vector<Real> B1(dim);
430  A.SetRandn();
431  B.SetRandn();
432  A.CopyToVec(&A1);
433  B.CopyToVec(&B1);
434  A.MulElements(B);
435  A1.MulElements(B1);
436  Vector<Real> A2(dim);
437  A.CopyToVec(&A2);
438  AssertEqual(A1,A2);
439  }
440  /*
441  for (MatrixIndexT iter = 0; iter < 10; iter++) {
442  int32 dim = 72;
443  CuVector<Real> A(dim);
444  Vector<Real> A1(dim);
445  CuMatrix<Real> B(9,8);
446  Matrix<Real> B1(9,8);
447  B.SetRandn();
448  B.CopyToMat(&B1);
449  A.CopyRowsFromMat(B);
450  A1.CopyRowsFromMat(B1);
451  Vector<Real> A2(dim);
452  A.CopyToVec(&A2);
453  AssertEqual(A1,A2);
454  }
455 
456  for (MatrixIndexT iter = 0; iter < 10; iter++) {
457  int32 dim = 15 + Rand() % 10;
458  CuVector<Real> A(dim);
459  A.SetRandn();
460  Vector<Real> A1(dim);
461  A.CopyToVec(&A1);
462  KALDI_LOG << "cpu min is : " << A1.Min();
463  KALDI_LOG << "gpu min is : " << A.Min();
464  }
465 
466  for (MatrixIndexT iter = 0; iter < 10; iter++) {
467  int32 dim = 15 + Rand() % 10;
468  CuVector<Real> A(dim);
469  A.SetRandn();
470  Vector<Real> A1(dim);
471  A.CopyToVec(&A1);
472  CuVector<Real> B(dim);
473  B.SetRandn();
474  Vector<Real> B1(dim);
475  B.CopyToVec(&B1);
476  CuVector<Real> C(dim);
477  C.SetRandn();
478  Vector<Real> C1(dim);
479  C.CopyToVec(&C1);
480  Real alpha = 2;
481  Real beta = 3;
482  A.AddVecVec(alpha, B, C, beta);
483  A1.AddVecVec(alpha,B1,C1,beta);
484  Vector<Real> D(dim);
485  A.CopyToVec(&D);
486  AssertEqual(D,A1);
487  }
488 
489  for (MatrixIndexT iter = 0; iter < 10; iter++) {
490  int32 dim1 = 15 + Rand() % 10;
491  int32 dim2 = 10 + Rand() % 10;
492  Matrix<Real> A(dim1,dim2);
493  for (MatrixIndexT i = 0; i < dim1; i++) {
494  for (MatrixIndexT j = 0; j < dim2; j++)
495  A(i,j) = i + 2 * j + 1;
496  }
497  KALDI_LOG << A;
498  CuMatrix<Real> B(dim1,dim2);
499  B.CopyFromMat(A);
500  CuVector<Real> C(dim1);
501  C.SetZero();
502  Real alpha = 1;
503  Real beta = 1;
504  C.AddDiagMat2(alpha, B, kNoTrans, beta);
505  Vector<Real> D(dim1);
506  C.CopyToVec(&D);
507  KALDI_LOG << D;
508  Vector<Real> E(dim1);
509  E.AddDiagMat2(alpha, A, kNoTrans, beta);
510  KALDI_LOG << E;
511  AssertEqual(D,E);
512  }
513 
514  for (MatrixIndexT iter = 0; iter < 10; iter++) {
515  int32 dim1 = 15 + Rand() % 10;
516  int32 dim2 = 10 + Rand() % 10;
517  Matrix<Real> A(dim1,dim2);
518  for (MatrixIndexT i = 0; i < dim1; i++) {
519  for (MatrixIndexT j = 0; j < dim2; j++)
520  A(i,j) = i + 2 * j + 1;
521  }
522  KALDI_LOG << A;
523  CuMatrix<Real> B(dim1,dim2);
524  B.CopyFromMat(A);
525  CuSubVector<Real> C(B,1);
526  Vector<Real> D(dim2);
527  C.CopyToVec(&D);
528  KALDI_LOG << D;
529  }
530 
531  for (MatrixIndexT iter = 0; iter < 10; iter++) {
532  int32 dim = 15 + Rand() % 10;
533  CuVector<Real> A(dim);
534  A.SetRandn();
535  Vector<Real> A1(dim);
536  A.CopyToVec(&A1);
537  CuVector<Real> B(dim);
538  B.SetRandn();
539  Vector<Real> B1(dim);
540  B.CopyToVec(&B1);
541  Real dot = VecVec(A,B);
542  KALDI_LOG << "dot product in gpu: " << dot;
543  dot = VecVec(A1,B1);
544  KALDI_LOG << "dot product in cpu: " << dot;
545  }
546 
547  for (MatrixIndexT iter = 0; iter < 10; iter++) {
548  int32 dim = 15 + Rand() % 10;
549  CuVector<Real> A(dim);
550  Vector<Real> A1(dim);
551  for (MatrixIndexT i = 0; i < dim; i++)
552  A1(i) = i;
553  A.CopyFromVec(A1);
554  KALDI_LOG << A(dim-2);
555  KALDI_LOG << A1(dim-2);
556  }
557  */
558 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
static void AssertEqual(float a, float b, float relative_tolerance=0.001)
assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
Definition: kaldi-math.h:276

◆ UnitTestVectorMax()

static void kaldi::UnitTestVectorMax ( )
static

Definition at line 631 of file matrix-lib-test.cc.

References rnnlm::i, KALDI_ASSERT, VectorBase< Real >::Max(), Rand(), and VectorBase< Real >::SetRandn().

631  {
632  int32 dimM = 1 + Rand() % 10;
633  Vector<Real> V(dimM);
634  V.SetRandn();
635  Real m = V(0);
636  for (int32 i = 1; i < dimM; i++) m = std::max(m, V(i));
637  KALDI_ASSERT(m == V.Max());
638  MatrixIndexT i;
639  KALDI_ASSERT(m == V.Max(&i));
640  KALDI_ASSERT(m == V(i));
641 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTestVectorMin()

static void kaldi::UnitTestVectorMin ( )
static

Definition at line 644 of file matrix-lib-test.cc.

References rnnlm::i, KALDI_ASSERT, VectorBase< Real >::Min(), Rand(), and VectorBase< Real >::SetRandn().

644  {
645  int32 dimM = 1 + Rand() % 10;
646  Vector<Real> V(dimM);
647  V.SetRandn();
648  Real m = V(0);
649  for (int32 i = 1; i < dimM; i++) m = std::min(m, V(i));
650  KALDI_ASSERT(m == V.Min());
651  MatrixIndexT i;
652  KALDI_ASSERT(m == V.Min(&i));
653  KALDI_ASSERT(m == V(i));
654 }
kaldi::int32 int32
int32 MatrixIndexT
Definition: matrix-common.h:98
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UnitTextCuMatrixAddMatSmat()

static void kaldi::UnitTextCuMatrixAddMatSmat ( )
static

Definition at line 810 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddMatSmat(), MatrixBase< Real >::AddMatSmat(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, rnnlm::n, Rand(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), and swap().

810  {
811  for (int i = 0; i < 2; ++i) {
812  int m = 10 + Rand() % 40;
813  int k = 10 + Rand() % 60;
814  int n = 10 + Rand() % 50;
815  int srows = k;
816  int scols = n;
817 
818  MatrixTransposeType trans = (i % 2 == 0) ? kNoTrans : kTrans;
819  if (trans == kTrans) {
820  std::swap(srows, scols);
821  }
822 
823  Real alpha = 0.345;
824  Real beta = 0.567;
825 
826  Matrix<Real> mat(m, k);
827  mat.SetRandn();
828  CuMatrix<Real> cumat(mat);
829 
830  Matrix<Real> result(m, n);
831  result.SetRandn();
832  CuMatrix<Real> curesult(result);
833 
834  SparseMatrix<Real> smat(srows, scols);
835  smat.SetRandn(0.8);
836  CuSparseMatrix<Real> cusmat(smat);
837 
838  result.AddMatSmat(alpha, mat, smat, trans, beta);
839  curesult.AddMatSmat(alpha, cumat, cusmat, trans, beta);
840 
841  Matrix<Real> result2(curesult);
842 
843  KALDI_ASSERT(ApproxEqual(result, result2));
844  }
845 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTextCuMatrixAddSmat()

static void kaldi::UnitTextCuMatrixAddSmat ( )
static

Definition at line 778 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddSmat(), MatrixBase< Real >::AddSmat(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, Rand(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), and swap().

778  {
779  for (int i = 0; i < 2; ++i) {
780  int rows = 10 + Rand() % 40;
781  int cols = 10 + Rand() % 50;
782  int srows = rows;
783  int scols = cols;
784 
785  MatrixTransposeType trans = (i % 2 == 0) ? kNoTrans : kTrans;
786  if (trans == kTrans) {
787  std::swap(srows, scols);
788  }
789 
790  Real alpha = 0.345;
791 
792  Matrix<Real> mat(rows, cols);
793  mat.SetRandn();
794  CuMatrix<Real> cumat(mat);
795 
796  SparseMatrix<Real> smat(srows, scols);
797  smat.SetRandn(0.5);
798  CuSparseMatrix<Real> cusmat(smat);
799 
800  mat.AddSmat(alpha, smat, trans);
801  cumat.AddSmat(alpha, cusmat, trans);
802 
803  Matrix<Real> mat2(cumat);
804 
805  KALDI_ASSERT(ApproxEqual(mat, mat2));
806  }
807 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UnitTextCuMatrixAddSmatMat()

static void kaldi::UnitTextCuMatrixAddSmatMat ( )
static

Definition at line 848 of file cu-matrix-test.cc.

References CuMatrixBase< Real >::AddSmatMat(), MatrixBase< Real >::AddSmatMat(), ApproxEqual(), rnnlm::i, KALDI_ASSERT, kNoTrans, kTrans, rnnlm::n, Rand(), MatrixBase< Real >::SetRandn(), SparseMatrix< Real >::SetRandn(), and swap().

848  {
849  for (int i = 0; i < 2; ++i) {
850  int m = 10 + Rand() % 40;
851  int k = 10 + Rand() % 60;
852  int n = 10 + Rand() % 50;
853  int srows = m;
854  int scols = k;
855 
856  MatrixTransposeType trans = (i % 2 == 0) ? kNoTrans : kTrans;
857  if (trans == kTrans) {
858  std::swap(srows, scols);
859  }
860 
861  Real alpha = 0.345;
862  Real beta = 0.567;
863 
864  SparseMatrix<Real> smat(srows, scols);
865  smat.SetRandn(0.8);
866  CuSparseMatrix<Real> cusmat(smat);
867 
868  Matrix<Real> mat(k, n);
869  mat.SetRandn();
870  CuMatrix<Real> cumat(mat);
871 
872  Matrix<Real> result(m, n);
873  result.SetRandn();
874  CuMatrix<Real> curesult(result);
875 
876  result.AddSmatMat(alpha, smat, trans, mat, beta);
877  curesult.AddSmatMat(alpha, cusmat, trans, cumat, beta);
878 
879  Matrix<Real> result2(curesult);
880 
881  KALDI_ASSERT(ApproxEqual(result, result2));
882  }
883 }
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
A class for storing matrices.
Definition: kaldi-matrix.h:823
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
struct rnnlm::@11::@12 n
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixTransposeType
Definition: matrix-common.h:32
static bool ApproxEqual(float a, float b, float relative_tolerance=0.001)
return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
Definition: kaldi-math.h:265

◆ UpdateEbwAmDiagGmm()

void UpdateEbwAmDiagGmm ( const AccumAmDiagGmm num_stats,
const AccumAmDiagGmm den_stats,
GmmFlagsType  flags,
const EbwOptions opts,
AmDiagGmm am_gmm,
BaseFloat auxf_change_out,
BaseFloat count_out,
int32 num_floored_out 
)

Definition at line 278 of file ebw-diag-gmm.cc.

References AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), KALDI_ASSERT, AccumAmDiagGmm::NumAccs(), AmDiagGmm::NumPdfs(), and UpdateEbwDiagGmm().

Referenced by main(), and EbwWeightOptions::Register().

285  {
286  KALDI_ASSERT(num_stats.NumAccs() == den_stats.NumAccs()
287  && num_stats.NumAccs() == am_gmm->NumPdfs());
288 
289  if (auxf_change_out) *auxf_change_out = 0.0;
290  if (count_out) *count_out = 0.0;
291  if (num_floored_out) *num_floored_out = 0.0;
292 
293  for (int32 pdf = 0; pdf < num_stats.NumAccs(); pdf++)
294  UpdateEbwDiagGmm(num_stats.GetAcc(pdf), den_stats.GetAcc(pdf), flags,
295  opts, &(am_gmm->GetPdf(pdf)), auxf_change_out,
296  count_out, num_floored_out);
297 }
kaldi::int32 int32
void UpdateEbwDiagGmm(const AccumDiagGmm &num_stats, const AccumDiagGmm &den_stats, GmmFlagsType flags, const EbwOptions &opts, DiagGmm *gmm, BaseFloat *auxf_change_out, BaseFloat *count_out, int32 *num_floored_out)
Definition: ebw-diag-gmm.cc:94
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UpdateEbwDiagGmm()

void UpdateEbwDiagGmm ( const AccumDiagGmm num_stats,
const AccumDiagGmm den_stats,
GmmFlagsType  flags,
const EbwOptions opts,
DiagGmm gmm,
BaseFloat auxf_change_out,
BaseFloat count_out,
int32 num_floored_out 
)

Definition at line 94 of file ebw-diag-gmm.cc.

References VectorBase< Real >::AddVec(), DiagGmm::ComputeGconsts(), DiagGmmNormal::CopyFromDiagGmm(), VectorBase< Real >::CopyFromVec(), MatrixBase< Real >::CopyRowFromVec(), DiagGmmNormal::CopyToDiagGmm(), DiagGmm::Dim(), AccumDiagGmm::Dim(), EbwOptions::E, EBWUpdateGaussian(), AccumDiagGmm::Flags(), GmmFlagsToString(), KALDI_ASSERT, KALDI_ERR, KALDI_VLOG, KALDI_WARN, kGmmMeans, kGmmVariances, kGmmWeights, AccumDiagGmm::mean_accumulator(), DiagGmmNormal::means_, DiagGmm::NumGauss(), AccumDiagGmm::NumGauss(), AccumDiagGmm::occupancy(), MatrixBase< Real >::Row(), EbwOptions::tau, AccumDiagGmm::variance_accumulator(), and DiagGmmNormal::vars_.

Referenced by EbwWeightOptions::Register(), UnitTestEstimateMmieDiagGmm(), and UpdateEbwAmDiagGmm().

101  {
102  GmmFlagsType acc_flags = num_stats.Flags();
103  if (flags & ~acc_flags)
104  KALDI_ERR << "Incompatible flags: you requested to update flags \""
105  << GmmFlagsToString(flags) << "\" but accumulators have only \""
106  << GmmFlagsToString(acc_flags) << '"';
107 
108  // It could be that the num stats actually contain the difference between
109  // num and den (for mean and var stats), and den stats only have the weights.
110  bool den_has_stats;
111  if (den_stats.Flags() != acc_flags) {
112  den_has_stats = false;
113  if (den_stats.Flags() != kGmmWeights)
114  KALDI_ERR << "Incompatible flags: num stats have flags \""
115  << GmmFlagsToString(acc_flags) << "\" vs. den stats \""
116  << GmmFlagsToString(den_stats.Flags()) << '"';
117  } else {
118  den_has_stats = true;
119  }
120  int32 num_comp = num_stats.NumGauss();
121  int32 dim = num_stats.Dim();
122  KALDI_ASSERT(num_stats.NumGauss() == den_stats.NumGauss());
123  KALDI_ASSERT(num_stats.Dim() == gmm->Dim());
124  KALDI_ASSERT(gmm->NumGauss() == num_comp);
125 
126  if ( !(flags & (kGmmMeans | kGmmVariances)) ) {
127  return; // Nothing to update.
128  }
129 
130  // copy DiagGMM model and transform this to the normal case
131  DiagGmmNormal diaggmmnormal;
132  gmm->ComputeGconsts();
133  diaggmmnormal.CopyFromDiagGmm(*gmm);
134 
135  // go over all components
136  Vector<double> mean(dim), var(dim), mean_stats(dim), var_stats(dim);
137 
138  for (int32 g = 0; g < num_comp; g++) {
139  BaseFloat num_count = num_stats.occupancy()(g),
140  den_count = den_stats.occupancy()(g);
141  if (num_count == 0.0 && den_count == 0.0) {
142  KALDI_VLOG(2) << "Not updating Gaussian " << g << " since counts are zero";
143  continue;
144  }
145  mean_stats.CopyFromVec(num_stats.mean_accumulator().Row(g));
146  if (den_has_stats)
147  mean_stats.AddVec(-1.0, den_stats.mean_accumulator().Row(g));
148  if (flags & kGmmVariances) {
149  var_stats.CopyFromVec(num_stats.variance_accumulator().Row(g));
150  if (den_has_stats)
151  var_stats.AddVec(-1.0, den_stats.variance_accumulator().Row(g));
152  }
153  double D = (opts.tau + opts.E * den_count) / 2;
154  if (D+num_count-den_count <= 0.0) {
155  // ensure +ve-- can be problem if num count == 0 and E=2.
156  D = -1.0001*(num_count-den_count) + 1.0e-10;
157  KALDI_ASSERT(D+num_count-den_count > 0.0);
158  }
159  // We initialize to half the value of D that would be dictated by E (and
160  // tau); this is part of the strategy used to ensure that the value of D we
161  // use is at least twice the value that would ensure positive variances.
162 
163  int32 iter, max_iter = 100;
164  for (iter = 0; iter < max_iter; iter++) { // will normally break from the loop
165  // the first time.
166  if (EBWUpdateGaussian(D, flags,
167  diaggmmnormal.means_.Row(g),
168  diaggmmnormal.vars_.Row(g),
169  mean_stats, var_stats, num_count-den_count,
170  &mean, &var, NULL)) {
171  // Succeeded in getting all +ve vars at this value of D.
172  // So double D and commit changes.
173  D *= 2.0;
174  double auxf_impr = 0.0;
175  bool ans = EBWUpdateGaussian(D, flags,
176  diaggmmnormal.means_.Row(g),
177  diaggmmnormal.vars_.Row(g),
178  mean_stats, var_stats, num_count-den_count,
179  &mean, &var, &auxf_impr);
180  if (!ans) {
181  KALDI_WARN << "Something went wrong in the EBW update. Check that your"
182  "previous update phase looks reasonable, probably your model is "
183  "already ruined. Reverting to the old values";
184  } else {
185  if (auxf_change_out) *auxf_change_out += auxf_impr;
186  if (count_out) *count_out += den_count; // The idea is that for MMI, this will
187  // reflect the actual #frames trained on (the numerator one would be I-smoothed).
188  // In general (e.g. for MPE), we won't know the #frames.
189  diaggmmnormal.means_.CopyRowFromVec(mean, g);
190  diaggmmnormal.vars_.CopyRowFromVec(var, g);
191  }
192  break;
193  } else {
194  // small step
195  D *= 1.1;
196  }
197  }
198  if (iter > 0 && num_floored_out != NULL) (*num_floored_out)++;
199  if (iter == max_iter) KALDI_WARN << "Dropped off end of loop, recomputing D. (unexpected.)";
200  }
201  // copy to natural representation according to flags.
202  diaggmmnormal.CopyToDiagGmm(gmm, flags);
203  gmm->ComputeGconsts();
204 }
kaldi::int32 int32
uint16 GmmFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:35
float BaseFloat
Definition: kaldi-types.h:29
static bool EBWUpdateGaussian(BaseFloat D, GmmFlagsType flags, const VectorBase< double > &orig_mean, const VectorBase< double > &orig_var, const VectorBase< double > &x_stats, const VectorBase< double > &x2_stats, double occ, VectorBase< double > *mean, VectorBase< double > *var, double *auxf_impr)
Definition: ebw-diag-gmm.cc:31
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
std::string GmmFlagsToString(GmmFlagsType flags)
Convert GMM flags to string.
Definition: model-common.cc:43

◆ UpdateEbwWeightsAmDiagGmm()

void UpdateEbwWeightsAmDiagGmm ( const AccumAmDiagGmm num_stats,
const AccumAmDiagGmm den_stats,
const EbwWeightOptions opts,
AmDiagGmm am_gmm,
BaseFloat auxf_change_out,
BaseFloat count_out 
)

Definition at line 300 of file ebw-diag-gmm.cc.

References AccumAmDiagGmm::GetAcc(), AmDiagGmm::GetPdf(), KALDI_ASSERT, AccumAmDiagGmm::NumAccs(), AmDiagGmm::NumPdfs(), and UpdateEbwWeightsDiagGmm().

Referenced by main(), and EbwWeightOptions::Register().

305  {
306  KALDI_ASSERT(num_stats.NumAccs() == den_stats.NumAccs()
307  && num_stats.NumAccs() == am_gmm->NumPdfs());
308 
309  if (auxf_change_out) *auxf_change_out = 0.0;
310  if (count_out) *count_out = 0.0;
311 
312  for (int32 pdf = 0; pdf < num_stats.NumAccs(); pdf++)
313  UpdateEbwWeightsDiagGmm(num_stats.GetAcc(pdf), den_stats.GetAcc(pdf),
314  opts, &(am_gmm->GetPdf(pdf)), auxf_change_out,
315  count_out);
316 }
void UpdateEbwWeightsDiagGmm(const AccumDiagGmm &num_stats, const AccumDiagGmm &den_stats, const EbwWeightOptions &opts, DiagGmm *gmm, BaseFloat *auxf_change_out, BaseFloat *count_out)
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ UpdateEbwWeightsDiagGmm()

void UpdateEbwWeightsDiagGmm ( const AccumDiagGmm num_stats,
const AccumDiagGmm den_stats,
const EbwWeightOptions opts,
DiagGmm gmm,
BaseFloat auxf_change_out,
BaseFloat count_out 
)

Definition at line 207 of file ebw-diag-gmm.cc.

References DiagGmm::ComputeGconsts(), DiagGmmNormal::CopyFromDiagGmm(), VectorBase< Real >::CopyFromVec(), DiagGmmNormal::CopyToDiagGmm(), KALDI_ASSERT, KALDI_LOG, kGmmAll, EbwWeightOptions::min_gaussian_weight, EbwWeightOptions::min_num_count_weight_update, AccumDiagGmm::occupancy(), VectorBase< Real >::Sum(), EbwWeightOptions::tau, and DiagGmmNormal::weights_.

Referenced by EbwWeightOptions::Register(), UnitTestEstimateMmieDiagGmm(), and UpdateEbwWeightsAmDiagGmm().

212  {
213 
214  DiagGmmNormal diaggmmnormal;
215  gmm->ComputeGconsts();
216  diaggmmnormal.CopyFromDiagGmm(*gmm);
217 
218  Vector<double> weights(diaggmmnormal.weights_),
219  num_occs(num_stats.occupancy()),
220  den_occs(den_stats.occupancy());
221  if (opts.tau == 0.0 &&
222  num_occs.Sum() + den_occs.Sum() < opts.min_num_count_weight_update) {
223  KALDI_LOG << "Not updating weights for this state because total count is "
224  << num_occs.Sum() + den_occs.Sum() << " < "
225  << opts.min_num_count_weight_update;
226  if (count_out)
227  *count_out += num_occs.Sum();
228  return;
229  }
230  num_occs.AddVec(opts.tau, weights);
231  KALDI_ASSERT(weights.Dim() == num_occs.Dim() && num_occs.Dim() == den_occs.Dim());
232  if (weights.Dim() == 1) return; // Nothing to do: only one mixture.
233  double weight_auxf_at_start = 0.0, weight_auxf_at_end = 0.0;
234 
235  int32 num_comp = weights.Dim();
236  for (int32 g = 0; g < num_comp; g++) { // c.f. eq. 4.32 in Dan Povey's thesis.
237  weight_auxf_at_start +=
238  num_occs(g) * log (weights(g))
239  - den_occs(g) * weights(g) / diaggmmnormal.weights_(g);
240  }
241  for (int32 iter = 0; iter < 50; iter++) {
242  Vector<double> k_jm(num_comp); // c.f. eq. 4.35
243  double max_m = 0.0;
244  for (int32 g = 0; g < num_comp; g++)
245  max_m = std::max(max_m, den_occs(g)/diaggmmnormal.weights_(g));
246  for (int32 g = 0; g < num_comp; g++)
247  k_jm(g) = max_m - den_occs(g)/diaggmmnormal.weights_(g);
248  for (int32 g = 0; g < num_comp; g++) // c.f. eq. 4.34
249  weights(g) = num_occs(g) + k_jm(g)*weights(g);
250  weights.Scale(1.0 / weights.Sum()); // c.f. eq. 4.34 (denominator)
251  }
252  for (int32 g = 0; g < num_comp; g++) { // weight flooring.
253  if (weights(g) < opts.min_gaussian_weight)
254  weights(g) = opts.min_gaussian_weight;
255  }
256  weights.Scale(1.0 / weights.Sum()); // renormalize after flooring..
257  // floor won't be exact now but doesn't really matter.
258 
259  for (int32 g = 0; g < num_comp; g++) { // c.f. eq. 4.32 in Dan Povey's thesis.
260  weight_auxf_at_end +=
261  num_occs(g) * log (weights(g))
262  - den_occs(g) * weights(g) / diaggmmnormal.weights_(g);
263  }
264 
265  if (auxf_change_out)
266  *auxf_change_out += weight_auxf_at_end - weight_auxf_at_start;
267  if (count_out)
268  *count_out += num_occs.Sum(); // only really valid for MMI [not MPE, or MMI
269  // with canceled stats]
270 
271  diaggmmnormal.weights_.CopyFromVec(weights);
272 
273  // copy to natural representation
274  diaggmmnormal.CopyToDiagGmm(gmm, kGmmAll);
275  gmm->ComputeGconsts();
276 }
kaldi::int32 int32
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_LOG
Definition: kaldi-error.h:153

◆ VecMatVec() [1/5]

Real VecMatVec ( const CuVectorBase< Real > &  v1,
const CuMatrixBase< Real > &  M,
const CuVectorBase< Real > &  v2 
)

Returns $ v_1^T M v_2 $ .

Definition at line 83 of file cu-vector.cc.

References CuVectorBase< Real >::AddMatVec(), CuVectorBase< Real >::Dim(), KALDI_ASSERT, kNoTrans, kTrans, CuMatrixBase< Real >::NumCols(), CuMatrixBase< Real >::NumRows(), VecMatVec(), and VecVec().

84  {
85  KALDI_ASSERT(v1.Dim() == M.NumRows() && M.NumCols() == v2.Dim());
86  if (v1.Dim() > v2.Dim()) { // do v2*M first
87  CuVector<Real> v2M(v1.Dim());
88  v2M.AddMatVec(1.0, M, kNoTrans, v2, 0.0);
89  return VecVec(v2M, v1);
90  } else { // do v1*M first
91  CuVector<Real> v1M(v2.Dim());
92  v1M.AddMatVec(1.0, M, kTrans, v1, 0.0);
93  return VecVec(v1M, v2);
94  }
95 }
template double VecVec(const CuVectorBase< double > &A, const CuVectorBase< float > &B)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ VecMatVec() [2/5]

template float kaldi::VecMatVec ( const CuVectorBase< float > &  v1,
const CuMatrixBase< float > &  M,
const CuVectorBase< float > &  v2 
)

◆ VecMatVec() [3/5]

template double kaldi::VecMatVec ( const CuVectorBase< double > &  v1,
const CuMatrixBase< double > &  M,
const CuVectorBase< double > &  v2 
)

◆ VecMatVec() [4/5]

template float kaldi::VecMatVec ( const VectorBase< float > &  v1,
const MatrixBase< float > &  M,
const VectorBase< float > &  v2 
)

◆ VecMatVec() [5/5]

template double kaldi::VecMatVec ( const VectorBase< double > &  v1,
const MatrixBase< double > &  M,
const VectorBase< double > &  v2 
)

Referenced by VecMatVec().

◆ VecSpVec() [1/2]

template float kaldi::VecSpVec ( const VectorBase< float > &  v1,
const SpMatrix< float > &  M,
const VectorBase< float > &  v2 
)

◆ VecSpVec() [2/2]

template double kaldi::VecSpVec ( const VectorBase< double > &  v1,
const SpMatrix< double > &  M,
const VectorBase< double > &  v2 
)

◆ VecSvec() [1/2]

template float kaldi::VecSvec ( const VectorBase< float > &  vec,
const SparseVector< float > &  svec 
)

◆ VecSvec() [2/2]

template double kaldi::VecSvec ( const VectorBase< double > &  vec,
const SparseVector< double > &  svec 
)

Referenced by TraceMatSmat().

◆ VecVec() [1/10]

template float kaldi::VecVec ( const VectorBase< float > &  a,
const VectorBase< float > &  b 
)

◆ VecVec() [2/10]

Real VecVec ( const CuVectorBase< Real > &  a,
const CuVectorBase< Real > &  b 
)

Definition at line 47 of file cu-vector.cc.

References CuVectorBase< Real >::Data(), CuVectorBase< Real >::Dim(), KALDI_ASSERT, CuVectorBase< Real >::Vec(), and VecVec().

48  {
49  //MatrixIndexT a_dim = a.Dim();
50  KALDI_ASSERT(a.Dim() == b.Dim());
51  Real result = 0;
52 #if HAVE_CUDA == 1
53  if (CuDevice::Instantiate().Enabled()) {
54  CuTimer tim;
55  CUBLAS_SAFE_CALL(cublas_dot(GetCublasHandle(), a.Dim(), a.Data(), 1, b.Data(),
56  1, &result));
57  CuDevice::Instantiate().AccuProfile(__func__, tim);
58 } else
59 #endif
60  {
61  result = VecVec(a.Vec(), b.Vec());
62  }
63  return result;
64 }
template double VecVec(const CuVectorBase< double > &A, const CuVectorBase< float > &B)
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185

◆ VecVec() [3/10]

template double kaldi::VecVec ( const VectorBase< double > &  a,
const VectorBase< double > &  b 
)

◆ VecVec() [4/10]

template float kaldi::VecVec ( const VectorBase< float > &  ra,
const VectorBase< double > &  rb 
)

◆ VecVec() [5/10]

template float kaldi::VecVec ( const CuVectorBase< float > &  a,
const CuVectorBase< float > &  b 
)

◆ VecVec() [6/10]

template double kaldi::VecVec ( const CuVectorBase< double > &  a,
const CuVectorBase< double > &  b 
)

◆ VecVec() [7/10]

template double kaldi::VecVec ( const VectorBase< double > &  ra,
const VectorBase< float > &  rb 
)

Referenced by VecMatVec().

◆ VecVec() [8/10]

Real VecVec ( const CuVectorBase< Real > &  A,
const CuVectorBase< OtherReal > &  B 
)

Definition at line 73 of file cu-vector.cc.

References VecVec().

73  {
74  CuVector<Real> B2(B);
75  return VecVec(A, B2); // This will call the single-parameter template.
76 }
template double VecVec(const CuVectorBase< double > &A, const CuVectorBase< float > &B)

◆ VecVec() [9/10]

template float kaldi::VecVec ( const CuVectorBase< float > &  A,
const CuVectorBase< double > &  B 
)

◆ VecVec() [10/10]

template double kaldi::VecVec ( const CuVectorBase< double > &  A,
const CuVectorBase< float > &  B 
)

◆ VerifySymbolRange()

void kaldi::VerifySymbolRange ( const std::string &  trace,
const bool  want_found,
const std::string &  want_symbol 
)

Definition at line 36 of file kaldi-error-test.cc.

References KALDI_ERR, and kaldi::internal::LocateSymbolRange().

Referenced by TestLocateSymbolRange().

37  {
38  size_t begin, end;
39  const bool found = internal::LocateSymbolRange(trace, &begin, &end);
40  if (found != want_found) {
41  KALDI_ERR << "Found mismatch, got " << found << " want " << want_found;
42  }
43  if (!found) {
44  return;
45  }
46  const std::string symbol = trace.substr(begin, end - begin);
47  if (symbol != want_symbol) {
48  KALDI_ERR << "Symbol mismatch, got " << symbol << " want " << want_symbol;
49  }
50 }
#define KALDI_ERR
Definition: kaldi-error.h:147
bool LocateSymbolRange(const std::string &trace_name, size_t *begin, size_t *end)
Definition: kaldi-error.cc:79

◆ WithProb()

bool WithProb ( BaseFloat  prob,
struct RandomState state 
)

Definition at line 72 of file kaldi-math.cc.

References KALDI_ASSERT, KALDI_COMPILE_TIME_ASSERT, and Rand().

Referenced by GetCount(), kaldi::nnet2::GetCount(), kaldi::nnet3::GetCount(), SpecAugmentTimeMaskComponent::GetMemo(), main(), kaldi::nnet3::PerturbImage(), RescoreCompactLatticeInternal(), SparseVector< Real >::SetRandn(), UnitTestCuMatrixAddToElements(), and UnitTestRand().

72  {
73  KALDI_ASSERT(prob >= 0 && prob <= 1.1); // prob should be <= 1.0,
74  // but we allow slightly larger values that could arise from roundoff in
75  // previous calculations.
76  KALDI_COMPILE_TIME_ASSERT(RAND_MAX > 128 * 128);
77  if (prob == 0) return false;
78  else if (prob == 1.0) return true;
79  else if (prob * RAND_MAX < 128.0) {
80  // prob is very small but nonzero, and the "main algorithm"
81  // wouldn't work that well. So: with probability 1/128, we
82  // return WithProb (prob * 128), else return false.
83  if (Rand(state) < RAND_MAX / 128) { // with probability 128...
84  // Note: we know that prob * 128.0 < 1.0, because
85  // we asserted RAND_MAX > 128 * 128.
86  return WithProb(prob * 128.0);
87  } else {
88  return false;
89  }
90  } else {
91  return (Rand(state) < ((RAND_MAX + static_cast<BaseFloat>(1.0)) * prob));
92  }
93 }
bool WithProb(BaseFloat prob, struct RandomState *state)
Definition: kaldi-math.cc:72
int Rand(struct RandomState *state)
Definition: kaldi-math.cc:45
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
#define KALDI_COMPILE_TIME_ASSERT(b)
Definition: kaldi-utils.h:131

◆ WordAlignLattice()

bool WordAlignLattice ( const CompactLattice lat,
const TransitionModel tmodel,
const WordBoundaryInfo info,
int32  max_states,
CompactLattice lat_out 
)

Align lattice so that each arc has the transition-ids on it that correspond to the word that is on that arc.

[May also have epsilon arcs for optional silences.] Returns true if everything was OK, false if some kind of error was detected (e.g. the words didn't have the kinds of sequences we would expect if the WordBoundaryInfo was correct). Note: we don't expect silence inside words, or empty words (words with no phones), and we expect the word to start with a wbegin_phone, to end with a wend_phone, and to possibly have winternal_phones inside (or to consist of just one wbegin_and_end_phone). Note: if it returns false, it doesn't mean the lattice that the output is necessarily bad: it might just be that the lattice was "forced out" as the end-state was not reached during decoding, and in this case the output might be usable. If max_states > 0, if this code detects that the #states of the output will be greater than max_states, it will abort the computation, return false and produce an empty lattice out.

Definition at line 723 of file word-align-lattice.cc.

References LatticeWordAligner::AlignLattice().

Referenced by main().

727  {
728  LatticeWordAligner aligner(lat, tmodel, info, max_states, lat_out);
729  return aligner.AlignLattice();
730 }

◆ WordAlignLatticeLexicon()

bool WordAlignLatticeLexicon ( const CompactLattice lat,
const TransitionModel tmodel,
const WordAlignLatticeLexiconInfo lexicon_info,
const WordAlignLatticeLexiconOpts opts,
CompactLattice lat_out 
)

Align lattice so that each arc has the transition-ids on it that correspond to the word that is on that arc.

[May also have epsilon arcs for optional silences.] Returns true if everything was OK, false if there was any kind of error including when the the lattice seems to have been "forced out" (did not reach end state, resulting in partial word at end).

Definition at line 1001 of file word-align-lattice-lexicon.cc.

References LatticeLexiconWordAligner::AlignLattice(), WordAlignLatticeLexiconOpts::allow_duplicate_paths, KALDI_WARN, WordAlignLatticeLexiconOpts::max_expand, WordAlignLatticeLexiconOpts::partial_word_label, PhoneAlignLattice(), PhoneAlignLatticeOptions::remove_epsilon, PhoneAlignLatticeOptions::reorder, WordAlignLatticeLexiconOpts::reorder, PhoneAlignLatticeOptions::replace_output_symbols, WordAlignLatticeLexiconOpts::test, and TestWordAlignedLattice().

Referenced by main(), WordAlignLatticeLexiconOpts::Register(), and TestWordAlignLatticeLexicon().

1005  {
1006  PhoneAlignLatticeOptions phone_align_opts;
1007  phone_align_opts.reorder = opts.reorder;
1008  phone_align_opts.replace_output_symbols = false;
1009  phone_align_opts.remove_epsilon = false;
1010 
1011  // Input Lattice should be deterministic and w/o epsilons.
1012  bool test = true;
1013  uint64 props = lat.Properties(fst::kIDeterministic|fst::kIEpsilons, test);
1014  if (props != fst::kIDeterministic) {
1015  KALDI_WARN << "[Lattice has input epsilons and/or is not input-deterministic "
1016  << "(in Mohri sense)]-- i.e. lattice is not deterministic. "
1017  << "Word-alignment may be slow and-or blow up in memory.";
1018  }
1019 
1020  CompactLattice phone_aligned_lat;
1021  bool ans = PhoneAlignLattice(lat, tmodel, phone_align_opts,
1022  &phone_aligned_lat);
1023  // 'phone_aligned_lat' is no longer deterministic and contains epsilons.
1024 
1025  int32 max_states;
1026  if (opts.max_expand <= 0) {
1027  max_states = -1;
1028  } else {
1029  // The 1000 is a fixed offset to give it more wiggle room for very
1030  // small inputs.
1031  max_states = kNumStatesOffset + opts.max_expand * phone_aligned_lat.NumStates();
1032  }
1033 
1034  // If ans == false, we hope this is due to a forced-out lattice, and we try to
1035  // continue.
1036  LatticeLexiconWordAligner aligner(phone_aligned_lat, tmodel, lexicon_info,
1037  max_states, opts.partial_word_label, lat_out);
1038  // We'll let the calling code warn if this is false; it will know the utterance-id.
1039  ans = aligner.AlignLattice() && ans;
1040  if (ans && opts.test) { // We only test if it succeeded.
1041  if (!TestWordAlignedLattice(lexicon_info, tmodel, lat, *lat_out,
1042  opts.allow_duplicate_paths)) {
1043  KALDI_WARN << "Lattice failed test (activated because --test=true). "
1044  << "Probable code error, please contact Kaldi maintainers.";
1045  ans = false;
1046  }
1047  }
1048  return ans;
1049 }
kaldi::int32 int32
static bool TestWordAlignedLattice(const WordAlignLatticeLexiconInfo &lexicon_info, const TransitionModel &tmodel, CompactLattice clat, CompactLattice aligned_clat, bool allow_duplicate_paths)
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
bool PhoneAlignLattice(const CompactLattice &lat, const TransitionModel &tmodel, const PhoneAlignLatticeOptions &opts, CompactLattice *lat_out)
Outputs a lattice in which the arcs correspond exactly to sequences of phones, so the boundaries betw...
const int kNumStatesOffset

◆ WriteAsKaldiVector()

void kaldi::WriteAsKaldiVector ( const std::vector< double > &  counts,
std::string &  wxfilename,
bool  binary 
)

Definition at line 53 of file compare-int-vector.cc.

References rnnlm::i, and WriteKaldiObject().

Referenced by main().

55  {
56  Vector<BaseFloat> counts_vec(counts.size());
57  for (size_t i = 0; i < counts.size(); i++)
58  counts_vec(i) = counts[i];
59  WriteKaldiObject(counts_vec, wxfilename, binary);
60 }
A class representing a vector.
Definition: kaldi-vector.h:406
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257

◆ WriteCompactLattice()

bool WriteCompactLattice ( std::ostream &  os,
bool  binary,
const CompactLattice t 
)

Definition at line 62 of file kaldi-lattice.cc.

References KALDI_WARN.

Referenced by TestWordAlignLatticeLexicon(), CompactLatticeHolder::Write(), and DiscriminativeNnetExample::Write().

63  {
64  if (binary) {
65  fst::FstWriteOptions opts;
66  // Leave all the options default. Normally these lattices wouldn't have any
67  // osymbols/isymbols so no point directing it not to write them (who knows what
68  // we'd want to if we had them).
69  return t.Write(os, opts);
70  } else {
71  // Text-mode output. Note: we expect that t.InputSymbols() and
72  // t.OutputSymbols() would always return NULL. The corresponding input
73  // routine would not work if the FST actually had symbols attached.
74  // Write a newline after the key, so the first line of the FST appears
75  // on its own line.
76  os << '\n';
77  bool acceptor = true, write_one = false;
78  fst::FstPrinter<CompactLatticeArc> printer(t, t.InputSymbols(),
79  t.OutputSymbols(),
80  NULL, acceptor, write_one, "\t");
81  printer.Print(&os, "<unknown>");
82  if (os.fail())
83  KALDI_WARN << "Stream failure detected.";
84  // Write another newline as a terminating character. The read routine will
85  // detect this [this is a Kaldi mechanism, not somethig in the original
86  // OpenFst code].
87  os << '\n';
88  return os.good();
89  }
90 }
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ WriteEventType()

void WriteEventType ( std::ostream &  os,
bool  binary,
const EventType evec 
)

Definition at line 228 of file event-map.cc.

References rnnlm::i, WriteBasicType(), and WriteToken().

Referenced by MakeEventPair(), TestEventTypeIo(), and WriteBuildTreeStats().

228  {
229  WriteToken(os, binary, "EV");
230  uint32 size = evec.size();
231  WriteBasicType(os, binary, size);
232  for (size_t i = 0; i < size; i++) {
233  WriteBasicType(os, binary, evec[i].first);
234  WriteBasicType(os, binary, evec[i].second);
235  }
236  if (!binary) os << '\n';
237 }
void WriteToken(std::ostream &os, bool binary, const char *token)
The WriteToken functions are for writing nonempty sequences of non-space characters.
Definition: io-funcs.cc:134
void WriteBasicType(std::ostream &os, bool binary, T t)
WriteBasicType is the name of the write function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:34

◆ WriteFull()

bool WriteFull ( int32  desc,
char *  data,
int32  size 
)

Definition at line 340 of file online-audio-client.cc.

Referenced by main().

340  {
341  int32 to_write = size;
342  int32 wrote = 0;
343  while (to_write > 0) {
344  int32 ret = write(desc, data + wrote, to_write);
345  if (ret <= 0)
346  return false;
347 
348  to_write -= ret;
349  wrote += ret;
350  }
351 
352  return true;
353 }
kaldi::int32 int32

◆ WriteHtk() [1/2]

template bool kaldi::WriteHtk ( std::ostream &  os,
const MatrixBase< float > &  M,
HtkHeader  htk_hdr 
)

◆ WriteHtk() [2/2]

template bool kaldi::WriteHtk ( std::ostream &  os,
const MatrixBase< double > &  M,
HtkHeader  htk_hdr 
)

Referenced by WriteHtk().

◆ WriteIntegerVectorSimple()

bool WriteIntegerVectorSimple ( const std::string &  wxfilename,
const std::vector< int32 > &  v 
)

WriteToList attempts to write this list of integers, one per line, to the given file, in text format.

returns true if succeeded.

Definition at line 24 of file simple-io-funcs.cc.

References Output::Close(), rnnlm::i, Output::Open(), and Output::Stream().

Referenced by main().

25  {
26  kaldi::Output ko;
27  // false, false is: text-mode, no Kaldi header.
28  if (!ko.Open(wxfilename, false, false)) return false;
29  for (size_t i = 0; i < list.size(); i++) ko.Stream() << list[i] << '\n';
30  return ko.Close();
31 }
std::ostream & Stream()
Definition: kaldi-io.cc:701
bool Open(const std::string &wxfilename, bool binary, bool write_header)
This opens the stream, with the given mode (binary or text).
Definition: kaldi-io.cc:707
bool Close()
Definition: kaldi-io.cc:677

◆ WriteIntegerVectorVectorSimple()

bool WriteIntegerVectorVectorSimple ( const std::string &  wxfilename,
const std::vector< std::vector< int32 > > &  list 
)

Definition at line 46 of file simple-io-funcs.cc.

References Output::Close(), rnnlm::i, rnnlm::j, Output::Open(), and Output::Stream().

Referenced by main().

47  {
48  kaldi::Output ko;
49  // false, false is: text-mode, no Kaldi header.
50  if (!ko.Open(wxfilename, false, false)) return false;
51  std::ostream &os = ko.Stream();
52  for (size_t i = 0; i < list.size(); i++) {
53  for (size_t j = 0; j < list[i].size(); j++) {
54  os << list[i][j];
55  if (j+1 < list[i].size()) os << ' ';
56  }
57  os << '\n';
58  }
59  return ko.Close();
60 }
std::ostream & Stream()
Definition: kaldi-io.cc:701
bool Open(const std::string &wxfilename, bool binary, bool write_header)
This opens the stream, with the given mode (binary or text).
Definition: kaldi-io.cc:707
bool Close()
Definition: kaldi-io.cc:677

◆ WriteLattice()

bool WriteLattice ( std::ostream &  os,
bool  binary,
const Lattice t 
)

Definition at line 388 of file kaldi-lattice.cc.

References KALDI_WARN.

Referenced by LatticeHolder::Write(), and DiscriminativeSupervision::Write().

388  {
389  if (binary) {
390  fst::FstWriteOptions opts;
391  // Leave all the options default. Normally these lattices wouldn't have any
392  // osymbols/isymbols so no point directing it not to write them (who knows what
393  // we'd want to do if we had them).
394  return t.Write(os, opts);
395  } else {
396  // Text-mode output. Note: we expect that t.InputSymbols() and
397  // t.OutputSymbols() would always return NULL. The corresponding input
398  // routine would not work if the FST actually had symbols attached.
399  // Write a newline after the key, so the first line of the FST appears
400  // on its own line.
401  os << '\n';
402  bool acceptor = false, write_one = false;
403  fst::FstPrinter<LatticeArc> printer(t, t.InputSymbols(),
404  t.OutputSymbols(),
405  NULL, acceptor, write_one, "\t");
406  printer.Print(&os, "<unknown>");
407  if (os.fail())
408  KALDI_WARN << "Stream failure detected.";
409  // Write another newline as a terminating character. The read routine will
410  // detect this [this is a Kaldi mechanism, not somethig in the original
411  // OpenFst code].
412  os << '\n';
413  return os.good();
414  }
415 }
#define KALDI_WARN
Definition: kaldi-error.h:150

◆ WriteLine()

bool WriteLine ( int32  socket,
std::string  line 
)

Definition at line 406 of file online-audio-server-decode-faster.cc.

Referenced by main().

406  {
407  line = line + "\n";
408 
409  const char* p = line.c_str();
410  int32 to_write = line.size();
411  int32 wrote = 0;
412  while (to_write > 0) {
413  int32 ret = write(socket, p + wrote, to_write);
414  if (ret <= 0)
415  return false;
416 
417  to_write -= ret;
418  wrote += ret;
419  }
420 
421  return true;
422 }
kaldi::int32 int32

◆ WriteSphinx() [1/2]

template bool kaldi::WriteSphinx ( std::ostream &  os,
const MatrixBase< float > &  M 
)

◆ WriteSphinx() [2/2]

template bool kaldi::WriteSphinx ( std::ostream &  os,
const MatrixBase< double > &  M 
)

Referenced by WriteSphinx().

◆ WriteUint16()

static void kaldi::WriteUint16 ( std::ostream &  os,
int16  i 
)
static

Definition at line 100 of file wave-reader.cc.

References rnnlm::i, KALDI_ERR, and KALDI_SWAP2.

Referenced by WaveData::Write().

100  {
101  union {
102  char buf[2];
103  int16 i;
104  } u;
105  u.i = i;
106 #ifdef __BIG_ENDIAN__
107  KALDI_SWAP2(u.buf);
108 #endif
109  os.write(u.buf, 2);
110  if (os.fail())
111  KALDI_ERR << "WaveData: error writing to stream.";
112 }
#define KALDI_SWAP2(a)
Definition: kaldi-utils.h:114
#define KALDI_ERR
Definition: kaldi-error.h:147

◆ WriteUint32()

static void kaldi::WriteUint32 ( std::ostream &  os,
int32  i 
)
static

Definition at line 86 of file wave-reader.cc.

References rnnlm::i, KALDI_ERR, and KALDI_SWAP4.

Referenced by WaveData::Write().

86  {
87  union {
88  char buf[4];
89  int i;
90  } u;
91  u.i = i;
92 #ifdef __BIG_ENDIAN__
93  KALDI_SWAP4(u.buf);
94 #endif
95  os.write(u.buf, 4);
96  if (os.fail())
97  KALDI_ERR << "WaveData: error writing to stream.";
98 }
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_SWAP4(a)
Definition: kaldi-utils.h:107

◆ Xgemv_sparsevec()

void kaldi::Xgemv_sparsevec ( MatrixTransposeType  trans,
MatrixIndexT  num_rows,
MatrixIndexT  num_cols,
Real  alpha,
const Real *  Mdata,
MatrixIndexT  stride,
const Real *  xdata,
MatrixIndexT  incX,
Real  beta,
Real *  ydata,
MatrixIndexT  incY 
)
inline

Definition at line 199 of file cblas-wrappers.h.

References cblas_Xaxpy(), cblas_Xscal(), rnnlm::i, and kNoTrans.

Referenced by MatrixBase< float >::AddMatSmat(), VectorBase< float >::AddMatSvec(), SpMatrix< float >::AddSmat2Sp(), and MatrixBase< float >::AddSmatMat().

203  {
204  if (trans == kNoTrans) {
205  if (beta != 1.0) cblas_Xscal(num_rows, beta, ydata, incY);
206  for (MatrixIndexT i = 0; i < num_cols; i++) {
207  Real x_i = xdata[i * incX];
208  if (x_i == 0.0) continue;
209  // Add to ydata, the i'th column of M, times alpha * x_i
210  cblas_Xaxpy(num_rows, x_i * alpha, Mdata + i, stride, ydata, incY);
211  }
212  } else {
213  if (beta != 1.0) cblas_Xscal(num_cols, beta, ydata, incY);
214  for (MatrixIndexT i = 0; i < num_rows; i++) {
215  Real x_i = xdata[i * incX];
216  if (x_i == 0.0) continue;
217  // Add to ydata, the i'th row of M, times alpha * x_i
218  cblas_Xaxpy(num_cols, x_i * alpha,
219  Mdata + (i * stride), 1, ydata, incY);
220  }
221  }
222 }
void cblas_Xaxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY)
int32 MatrixIndexT
Definition: matrix-common.h:98
void cblas_Xscal(const int N, const double alpha, double *data, const int inc)

Variable Documentation

◆ _RandMutex

std::mutex _RandMutex
static

Definition at line 43 of file kaldi-math.cc.

◆ buffer_fill

int32 buffer_fill = 0

Definition at line 356 of file online-audio-client.cc.

Referenced by ReadLine().

◆ buffer_offset

int32 buffer_offset = 0

Definition at line 355 of file online-audio-client.cc.

Referenced by ReadLine().

◆ g_allocator_options

CuAllocatorOptions g_allocator_options

Definition at line 644 of file cu-allocator.cc.

Referenced by CuAllocatorOptions::Check().

◆ g_num_threads

◆ g_profile_stats

ProfileStats g_profile_stats

Definition at line 79 of file timer.cc.

◆ kFramesPerSecond

const float kFramesPerSecond = 100.0f

Definition at line 65 of file online-audio-server-decode-faster.cc.

Referenced by main().

◆ kLogZeroBaseFloat

const BaseFloat kLogZeroBaseFloat = -std::numeric_limits<BaseFloat>::infinity()

Definition at line 130 of file kaldi-math.h.

◆ kLogZeroDouble

◆ kLogZeroFloat

const float kLogZeroFloat = -std::numeric_limits<float>::infinity()

◆ kMaxVal

const int32 kMaxVal = 20

Definition at line 143 of file event-map-test.cc.

Referenced by RandomEventMap(), and TestEventMapMapValues().

◆ kMinLogDiffDouble

const double kMinLogDiffDouble = Log(DBL_EPSILON)
static

Definition at line 124 of file kaldi-math.h.

Referenced by VectorBase< float >::LogSumExp(), and MatrixBase< float >::LogSumExp().

◆ kMinLogDiffFloat

const float kMinLogDiffFloat = Log(FLT_EPSILON)
static

Definition at line 125 of file kaldi-math.h.

Referenced by VectorBase< float >::LogSumExp(), and MatrixBase< float >::LogSumExp().

◆ kNumStatesOffset

const int kNumStatesOffset = 1000

Definition at line 31 of file word-align-lattice-lexicon.cc.

◆ kPdfClass

◆ kRandomSentences

const int kRandomSentences = 50
static

Definition at line 40 of file arpa-lm-compiler-test.cc.

Referenced by CoverageTest().

◆ kShellType

ShellType kShellType = kBash
static

Definition at line 214 of file parse-options.cc.

◆ kTemporaryEpsilon

const int kTemporaryEpsilon = -2

◆ kWaveSampleMax

const BaseFloat kWaveSampleMax = 32768.0

For historical reasons, we scale waveforms to the range (2^15-1)*[-1, 1], not the usual default DSP range [-1, 1].

Definition at line 62 of file wave-reader.h.

◆ log_handler

LogHandler log_handler = NULL
static

Definition at line 48 of file kaldi-error.cc.

Referenced by MessageLogger::LogMessage(), and SetLogHandler().

◆ pitch_use_naive_search

bool pitch_use_naive_search = false

Definition at line 292 of file pitch-functions.cc.

Referenced by UnitTestDelay().

◆ program_name

std::string program_name
static

Definition at line 47 of file kaldi-error.cc.

◆ read_buffer

char read_buffer[1025]

Definition at line 357 of file online-audio-client.cc.

◆ ws_delim

const char* ws_delim = " \t\n\r"

Definition at line 32 of file text-utils-test.cc.