diff --git a/BrainScript/BrainScriptEvaluator.cpp b/BrainScript/BrainScriptEvaluator.cpp index 35dd18570..f2c157f8a 100644 --- a/BrainScript/BrainScriptEvaluator.cpp +++ b/BrainScript/BrainScriptEvaluator.cpp @@ -42,9 +42,9 @@ #ifndef let #define let const auto #endif - -namespace Microsoft { namespace MSR { namespace BS { - + +namespace Microsoft { namespace MSR { namespace BS { + using namespace std; using namespace msra::strfun; using namespace Microsoft::MSR::CNTK; @@ -145,79 +145,79 @@ namespace Microsoft { namespace MSR { namespace BS { // other wstring m_nodeName; // node name in the graph static wstring TidyName(wstring name) - { -#if 0 - // clean out the intermediate name, e.g. A._b.C -> A.C for pretty printing of names, towards dictionary access - // BUGBUG: anonymous ComputationNodes will get a non-unique name this way - if (!name.empty()) - { - let pos = name.find(exprPathSeparator); - let left = pos == wstring::npos ? name : name.substr(0, pos); - let right = pos == wstring::npos ? L"" : TidyName(name.substr(pos + 1)); - if (left.empty() || left[0] == '_') - name = right; - else if (right.empty()) - name = left; - else - name = left + exprPathSeparator + right; - } -#endif - return name; - } - wstring NodeName() const { return m_nodeName; } // TODO: should really be named GetNodeName() + { +#if 0 + // clean out the intermediate name, e.g. A._b.C -> A.C for pretty printing of names, towards dictionary access + // BUGBUG: anonymous ComputationNodes will get a non-unique name this way + if (!name.empty()) + { + let pos = name.find(exprPathSeparator); + let left = pos == wstring::npos ? name : name.substr(0, pos); + let right = pos == wstring::npos ? L"" : TidyName(name.substr(pos + 1)); + if (left.empty() || left[0] == '_') + name = right; + else if (right.empty()) + name = left; + else + name = left + exprPathSeparator + right; + } +#endif + return name; + } + wstring NodeName() const { return m_nodeName; } // TODO: should really be named GetNodeName() /*HasName::*/ void SetName(const wstring & name) { m_nodeName = name; } wstring m_tag; void SetTag(const wstring & tag) { m_tag = tag; } const wstring & GetTag() const { return m_tag; } - - virtual const wchar_t * OperationName() const = 0; - - ComputationNode() - { - // node nmaes are not implemented yet; use a unique node name instead - static int nodeIndex = 1; - m_nodeName = wstrprintf(L"anonymousNode%d", nodeIndex); - nodeIndex++; - } - - virtual void AttachInputs(ComputationNodePtr arg) - { - m_children.resize(1); - m_children[0] = arg; - } - virtual void AttachInputs(ComputationNodePtr leftNode, ComputationNodePtr rightNode) - { - m_children.resize(2); - m_children[0] = leftNode; - m_children[1] = rightNode; - } - virtual void AttachInputs(ComputationNodePtr arg1, ComputationNodePtr arg2, ComputationNodePtr arg3) - { - m_children.resize(3); - m_children[0] = arg1; - m_children[1] = arg2; - m_children[2] = arg3; - } - void AttachInputs(vector && inputs, size_t num = 0/*0 means all OK*/) - { - if (num != 0 && inputs.size() != num) - LogicError("AttachInputs: called with incorrect number of arguments"); - m_children = inputs; - } - const std::vector & GetChildren() const { return m_children; } - - /*HasToString::*/ wstring ToString() const - { - // we format it like "[TYPE] ( args )" - wstring result = TidyName(NodeName()) + L" : " + wstring(OperationName()); - if (!m_tag.empty()) - result += L" {tag: " + m_tag + L"}"; - if (m_children.empty()) result.append(L"()"); - else - { - wstring args; - bool first = true; + + virtual const wchar_t * OperationName() const = 0; + + ComputationNode() + { + // node nmaes are not implemented yet; use a unique node name instead + static int nodeIndex = 1; + m_nodeName = wstrprintf(L"anonymousNode%d", nodeIndex); + nodeIndex++; + } + + virtual void AttachInputs(ComputationNodePtr arg) + { + m_children.resize(1); + m_children[0] = arg; + } + virtual void AttachInputs(ComputationNodePtr leftNode, ComputationNodePtr rightNode) + { + m_children.resize(2); + m_children[0] = leftNode; + m_children[1] = rightNode; + } + virtual void AttachInputs(ComputationNodePtr arg1, ComputationNodePtr arg2, ComputationNodePtr arg3) + { + m_children.resize(3); + m_children[0] = arg1; + m_children[1] = arg2; + m_children[2] = arg3; + } + void AttachInputs(vector && inputs, size_t num = 0/*0 means all OK*/) + { + if (num != 0 && inputs.size() != num) + LogicError("AttachInputs: called with incorrect number of arguments"); + m_children = inputs; + } + const std::vector & GetChildren() const { return m_children; } + + /*HasToString::*/ wstring ToString() const + { + // we format it like "[TYPE] ( args )" + wstring result = TidyName(NodeName()) + L" : " + wstring(OperationName()); + if (!m_tag.empty()) + result += L" {tag: " + m_tag + L"}"; + if (m_children.empty()) result.append(L"()"); + else + { + wstring args; + bool first = true; for (auto & child : m_children) { if (first) @@ -227,9 +227,9 @@ namespace Microsoft { namespace MSR { namespace BS { args.append(TidyName(child->NodeName())); } result += L" " + NestString(args, L'(', true, ')'); - } - return result; - } + } + return result; + } }; typedef ComputationNode::ComputationNodePtr ComputationNodePtr; struct UnaryComputationNode : public ComputationNode @@ -249,7 +249,7 @@ namespace Microsoft { namespace MSR { namespace BS { struct T##Node : public C##ComputationNode \ { \ T##Node(vector && inputs, const wstring & tag) : C##ComputationNode(move(inputs), tag) { } \ - /*ComputationNode::*/ const wchar_t * OperationName() const { return L#T; } \ + /*ComputationNode::*/ const wchar_t * OperationName() const { return L#T; } \ }; #define DefineUnaryComputationNode(T) DefineComputationNode(T,Unary) #define DefineBinaryComputationNode(T) DefineComputationNode(T,Binary) @@ -273,7 +273,7 @@ namespace Microsoft { namespace MSR { namespace BS { double factor; public: PlusNode(vector && inputs, const wstring & tag) : BinaryComputationNode(move(inputs), tag) { } - /*implement*/ const wchar_t * OperationName() const { return L"Scale"; } + /*implement*/ const wchar_t * OperationName() const { return L"Scale"; } }; #endif struct RowSliceNode : public UnaryComputationNode @@ -281,7 +281,7 @@ namespace Microsoft { namespace MSR { namespace BS { size_t firstRow, numRows; public: RowSliceNode(vector && inputs, size_t firstRow, size_t numRows, const wstring & tag) : UnaryComputationNode(move(inputs), tag), firstRow(firstRow), numRows(numRows) { } - /*ComputationNode::*/ const wchar_t * OperationName() const { return L"RowSlice"; } + /*ComputationNode::*/ const wchar_t * OperationName() const { return L"RowSlice"; } }; // Nodes deriving from RecurrentComputationNode are special in that it may involve cycles. // Specifically, to break circular references, RecurrentComputationNode does not resolve its inputs arg (ComputationNodes), @@ -310,7 +310,7 @@ namespace Microsoft { namespace MSR { namespace BS { int deltaT; public: DelayNode(function()> GetInputsLambda, int deltaT, const wstring & tag) : RecurrentComputationNode(GetInputsLambda), deltaT(deltaT) { SetTag(tag); } - /*ComputationNode::*/ const wchar_t * OperationName() const { return L"Delay"; } + /*ComputationNode::*/ const wchar_t * OperationName() const { return L"Delay"; } }; class InputValue : public ComputationNode { @@ -319,18 +319,18 @@ namespace Microsoft { namespace MSR { namespace BS { { config; } - /*ComputationNode::*/ const wchar_t * OperationName() const { return L"InputValue"; } + /*ComputationNode::*/ const wchar_t * OperationName() const { return L"InputValue"; } }; class LearnableParameter : public ComputationNode { size_t outDim, inDim; public: LearnableParameter(size_t outDim, size_t inDim, const wstring & tag) : outDim(outDim), inDim(inDim) { SetTag(tag); } - /*ComputationNode::*/ const wchar_t * OperationName() const { return L"LearnableParameter"; } - /*HasToString::*/ wstring ToString() const - { - return wstrprintf(L"%ls : %ls {tag: %s} (%d, %d)", TidyName(NodeName()).c_str(), OperationName(), GetTag().c_str(), (int)outDim, (int)inDim); - } + /*ComputationNode::*/ const wchar_t * OperationName() const { return L"LearnableParameter"; } + /*HasToString::*/ wstring ToString() const + { + return wstrprintf(L"%ls : %ls {tag: %s} (%d, %d)", TidyName(NodeName()).c_str(), OperationName(), GetTag().c_str(), (int)outDim, (int)inDim); + } }; // helper for the factory function for ComputationNodes static vector GetInputs(const IConfigRecord & config, size_t expectedNumInputs, const wstring & classId/*for error msg*/) @@ -347,7 +347,7 @@ namespace Microsoft { namespace MSR { namespace BS { inputs.push_back(inputsArray->At(i, inputsArg.GetLocation())); } if (inputs.size() != expectedNumInputs) - throw EvaluationError(L"unexpected number of inputs to ComputationNode class " + classId, inputsArg.GetLocation()); + EvaluationError(L"unexpected number of inputs to ComputationNode class " + classId, inputsArg.GetLocation()); return inputs; } // factory function for ComputationNodes @@ -390,7 +390,7 @@ namespace Microsoft { namespace MSR { namespace BS { else if (classId == L"ErrorPrediction") return make_shared(GetInputs(config, 2, L"ErrorPrediction"), tag); else - throw EvaluationError(L"unknown ComputationNode class " + classId, classIdParam.GetLocation()); + EvaluationError(L"unknown ComputationNode class " + classId, classIdParam.GetLocation()); } // factory function for RecurrentComputationNodes // The difference to the above is that the children are not resolved immediately but later during network connection. @@ -407,7 +407,7 @@ namespace Microsoft { namespace MSR { namespace BS { if (classId == L"Delay") return make_shared([configp](){ return GetInputs(*configp, 1, L"Delay"); }, config[L"deltaT"], tag); else - throw EvaluationError(L"unknown ComputationNode class " + classId, classIdParam.GetLocation()); + EvaluationError(L"unknown ComputationNode class " + classId, classIdParam.GetLocation()); } // ======================================================================= @@ -501,10 +501,10 @@ namespace Microsoft { namespace MSR { namespace BS { } m_namesToNodeMap; } - /*HasToString::*/ wstring ToString() const - { - wstring args; - bool first = true; + /*HasToString::*/ wstring ToString() const + { + wstring args; + bool first = true; for (auto & iter : m_namesToNodeMap) { let node = iter.second; @@ -515,7 +515,7 @@ namespace Microsoft { namespace MSR { namespace BS { args.append(node->ToString()); } return L"NDLComputationNetwork " + NestString(args, L'[', true, ']'); - } + } }; #if 0 @@ -678,14 +678,20 @@ namespace Microsoft { namespace MSR { namespace BS { // error object - class EvaluationError : public ConfigError + class EvaluationException : public ConfigException { public: - EvaluationError(const wstring & msg, TextLocation where) : ConfigError(msg, where) { } + EvaluationException(const wstring & msg, TextLocation where) : ConfigException(msg, where) { } /*Configerror::*/ const wchar_t * kind() const { return L"evaluating"; } }; - __declspec_noreturn static void Fail(const wstring & msg, TextLocation where) { throw EvaluationError(msg, where); } + __declspec_noreturn static inline void EvaluationError(const wstring & msg, TextLocation where) + { + Microsoft::MSR::CNTK::DebugUtil::PrintCallStack(); + throw EvaluationException(msg, where); + } + + __declspec_noreturn static void Fail(const wstring & msg, TextLocation where) { EvaluationError(msg, where); } __declspec_noreturn static void TypeExpected(const wstring & what, ExpressionPtr e) { Fail(L"expected expression of type '" + what + L"'", e->location); } __declspec_noreturn static void UnknownIdentifier(const wstring & id, TextLocation where) { Fail(L"unknown identifier '" + id + L"'", where); } @@ -809,22 +815,22 @@ namespace Microsoft { namespace MSR { namespace BS { // ----------------------------------------------------------------------- // name lookup // ----------------------------------------------------------------------- - + static ConfigValuePtr Evaluate(const ExpressionPtr & e, const IConfigRecordPtr & scope, wstring exprPath, const wstring & exprId); // forward declare - // look up a member by id in the search scope - // If it is not found, it tries all lexically enclosing scopes inside out. This is handled by the ConfigRecord itself. - static const ConfigValuePtr & ResolveIdentifier(const wstring & id, const TextLocation & idLocation, const IConfigRecordPtr & scope) - { - auto p = scope->Find(id); // look up the name - // Note: We could also just use scope->operator[] here, like any C++ consumer, but then we'd not be able to print an error with a proper text location (that of the offending field). - if (!p) - UnknownIdentifier(id, idLocation); - // found it: resolve the value lazily (the value will hold a Thunk to compute its value upon first use) - p->EnsureIsResolved(); // if this is the first access, then the value must have executed its Thunk - // now the value is available - return *p; - } + // look up a member by id in the search scope + // If it is not found, it tries all lexically enclosing scopes inside out. This is handled by the ConfigRecord itself. + static const ConfigValuePtr & ResolveIdentifier(const wstring & id, const TextLocation & idLocation, const IConfigRecordPtr & scope) + { + auto p = scope->Find(id); // look up the name + // Note: We could also just use scope->operator[] here, like any C++ consumer, but then we'd not be able to print an error with a proper text location (that of the offending field). + if (!p) + UnknownIdentifier(id, idLocation); + // found it: resolve the value lazily (the value will hold a Thunk to compute its value upon first use) + p->EnsureIsResolved(); // if this is the first access, then the value must have executed its Thunk + // now the value is available + return *p; + } // look up an identifier in an expression that is a ConfigRecord static ConfigValuePtr RecordLookup(const ExpressionPtr & recordExpr, const wstring & id, const TextLocation & idLocation, const IConfigRecordPtr & scope, const wstring & exprPath) @@ -870,12 +876,12 @@ namespace Microsoft { namespace MSR { namespace BS { : NumbersOp(NumbersOp), StringsOp(StringsOp), BoolOp(BoolOp), ComputeNodeOp(ComputeNodeOp), DictOp(DictOp) { } }; - // functions that implement infix operations + // functions that implement infix operations __declspec_noreturn static void InvalidInfixOpTypes(ExpressionPtr e) { Fail(L"operator " + e->op + L" cannot be applied to these operands", e->location); } - template - static ConfigValuePtr CompOp(const ExpressionPtr & e, const T & left, const T & right, const IConfigRecordPtr &, const wstring & exprPath) - { + template + static ConfigValuePtr CompOp(const ExpressionPtr & e, const T & left, const T & right, const IConfigRecordPtr &, const wstring & exprPath) + { if (e->op == L"==") return MakePrimitiveConfigValuePtr(left == right, MakeFailFn(e->location), exprPath); else if (e->op == L"!=") return MakePrimitiveConfigValuePtr(left != right, MakeFailFn(e->location), exprPath); else if (e->op == L"<") return MakePrimitiveConfigValuePtr(left < right, MakeFailFn(e->location), exprPath); @@ -883,8 +889,8 @@ namespace Microsoft { namespace MSR { namespace BS { else if (e->op == L"<=") return MakePrimitiveConfigValuePtr(left <= right, MakeFailFn(e->location), exprPath); else if (e->op == L">=") return MakePrimitiveConfigValuePtr(left >= right, MakeFailFn(e->location), exprPath); else LogicError("unexpected infix op"); - } - static ConfigValuePtr NumOp(const ExpressionPtr & e, ConfigValuePtr leftVal, ConfigValuePtr rightVal, const IConfigRecordPtr & scope, const wstring & exprPath) + } + static ConfigValuePtr NumOp(const ExpressionPtr & e, ConfigValuePtr leftVal, ConfigValuePtr rightVal, const IConfigRecordPtr & scope, const wstring & exprPath) { let left = leftVal.AsRef(); let right = rightVal.AsRef(); @@ -896,14 +902,14 @@ namespace Microsoft { namespace MSR { namespace BS { else if (e->op == L"**") return MakePrimitiveConfigValuePtr(pow(left, right), MakeFailFn(e->location), exprPath); else return CompOp(e, left, right, scope, exprPath); }; - static ConfigValuePtr StrOp(const ExpressionPtr & e, ConfigValuePtr leftVal, ConfigValuePtr rightVal, const IConfigRecordPtr & scope, const wstring & exprPath) + static ConfigValuePtr StrOp(const ExpressionPtr & e, ConfigValuePtr leftVal, ConfigValuePtr rightVal, const IConfigRecordPtr & scope, const wstring & exprPath) { let left = leftVal.AsRef(); let right = rightVal.AsRef(); if (e->op == L"+") return ConfigValuePtr(make_shared(left + right), MakeFailFn(e->location), exprPath); else return CompOp(e, left, right, scope, exprPath); }; - static ConfigValuePtr BoolOp(const ExpressionPtr & e, ConfigValuePtr leftVal, ConfigValuePtr rightVal, const IConfigRecordPtr & scope, const wstring & exprPath) + static ConfigValuePtr BoolOp(const ExpressionPtr & e, ConfigValuePtr leftVal, ConfigValuePtr rightVal, const IConfigRecordPtr & scope, const wstring & exprPath) { let left = leftVal.AsRef(); //let right = rightVal.AsRef(); // we do this inline, as to get the same short-circuit semantics as C++ (if rightVal is thunked, it will remain so unless required for this operation) @@ -940,12 +946,12 @@ namespace Microsoft { namespace MSR { namespace BS { else if (e->op == L".*") operationName = L"ElementTimes"; else LogicError("unexpected infix op"); } - // directly instantiate a ComputationNode for the magic operators * + and - that are automatically translated. - // find creation lambda - let rtInfo = FindRuntimeTypeInfo(L"ComputationNode"); - if (!rtInfo) + // directly instantiate a ComputationNode for the magic operators * + and - that are automatically translated. + // find creation lambda + let rtInfo = FindRuntimeTypeInfo(L"ComputationNode"); + if (!rtInfo) LogicError("unknown magic runtime-object class"); - // form the ConfigRecord for the ComputeNode that corresponds to the operation + // form the ConfigRecord for the ComputeNode that corresponds to the operation auto config = make_shared(scope, MakeFailFn(e->location)); // Note on scope: This config holds the arguments of the XXXNode runtime-object instantiations. // When they fetch their parameters, they should only look in this record, not in any parent scope (if they don't find what they are looking for, it's a bug in this routine here). @@ -981,7 +987,7 @@ namespace Microsoft { namespace MSR { namespace BS { return value; }; static ConfigValuePtr BadOp(const ExpressionPtr & e, ConfigValuePtr, ConfigValuePtr, const IConfigRecordPtr &, const wstring &) { InvalidInfixOpTypes(e); }; - + // lookup table for infix operators // This lists all infix operators with lambdas for evaluating them. static map infixOps = @@ -1338,37 +1344,37 @@ namespace Microsoft { namespace MSR { namespace BS { } //LogicError("should not get here"); } - catch (ConfigError & err) + catch (ConfigException & err) { // in case of an error, we keep track of all parent locations in the parse as well, to make it easier for the user to spot the error err.AddLocation(e->location); throw; } } - - static ConfigValuePtr EvaluateParse(ExpressionPtr e) - { - return Evaluate(e, IConfigRecordPtr(nullptr)/*top scope*/, L"", L"$"); - } - + + static ConfigValuePtr EvaluateParse(ExpressionPtr e) + { + return Evaluate(e, IConfigRecordPtr(nullptr)/*top scope*/, L"", L"$"); + } + // ----------------------------------------------------------------------- // external entry points // ----------------------------------------------------------------------- - - // top-level entry + + // top-level entry // A config sequence X=A;Y=B;do=(A,B) is really parsed as [X=A;Y=B].do. That's the tree we get. I.e. we try to compute the 'do' member. - void Do(ExpressionPtr e) - { - RecordLookup(e, L"do", e->location, nullptr, L"$"); // we evaluate the member 'do' - } - - shared_ptr EvaluateField(ExpressionPtr e, const wstring & id) - { + void Do(ExpressionPtr e) + { + RecordLookup(e, L"do", e->location, nullptr, L"$"); // we evaluate the member 'do' + } + + shared_ptr EvaluateField(ExpressionPtr e, const wstring & id) + { //let record = AsPtr(Evaluate(recordExpr, scope, exprPath, L""), recordExpr, L"record"); //return ResolveIdentifier(id, idLocation, MakeScope(record, nullptr/*no up scope*/)); - return RecordLookup(e, id, e->location, nullptr/*scope for evaluating 'e'*/, L"$"); // we evaluate the member 'do' - } - + return RecordLookup(e, id, e->location, nullptr/*scope for evaluating 'e'*/, L"$"); // we evaluate the member 'do' + } + ConfigValuePtr Evaluate(ExpressionPtr e) { return /*Evaluator().*/EvaluateParse(e); diff --git a/BrainScript/BrainScriptParser.cpp b/BrainScript/BrainScriptParser.cpp index b07f647f3..1987e99a5 100644 --- a/BrainScript/BrainScriptParser.cpp +++ b/BrainScript/BrainScriptParser.cpp @@ -151,14 +151,18 @@ protected: CacheCurrentLine(); // re-cache current line } public: - class CodeSourceError : public ConfigError + class CodeSourceException : public ConfigException { public: - CodeSourceError(const wstring & msg, TextLocation where) : ConfigError(msg, where) { } - /*ConfigError::*/ const wchar_t * kind() const { return L"reading source"; } + CodeSourceException(const wstring & msg, TextLocation where) : ConfigException(msg, where) { } + /*ConfigException::*/ const wchar_t * kind() const { return L"reading source"; } }; - __declspec_noreturn static void Fail(wstring msg, TextLocation where) { throw CodeSourceError(msg, where); } + __declspec_noreturn static void Fail(wstring msg, TextLocation where) + { + Microsoft::MSR::CNTK::DebugUtil::PrintCallStack(); + throw CodeSourceException(msg, where); + } // enter a source file, at start or as a result of an include statement void PushSourceFile(SourceFile && sourceFile) @@ -293,15 +297,19 @@ public: } }; - class LexerError : public ConfigError + class LexerException : public ConfigException { public: - LexerError(const wstring & msg, TextLocation where) : ConfigError(msg, where) { } - /*ConfigError::*/ const wchar_t * kind() const { return L"tokenizing"; } + LexerException(const wstring & msg, TextLocation where) : ConfigException(msg, where) { } + /*ConfigException::*/ const wchar_t * kind() const { return L"tokenizing"; } }; private: - __declspec_noreturn static void Fail(wstring msg, Token where) { throw LexerError(msg, where.beginLocation); } + __declspec_noreturn static void Fail(wstring msg, Token where) + { + Microsoft::MSR::CNTK::DebugUtil::PrintCallStack(); + throw LexerException(msg, where.beginLocation); + } Token currentToken; // consume input characters to form a next token @@ -472,14 +480,18 @@ void Expression::Dump(int indent) const class Parser : public Lexer { // errors - class ParseError : public ConfigError + class ParseException : public ConfigException { public: - ParseError(const wstring & msg, TextLocation where) : ConfigError(msg, where) { } - /*ConfigError::*/ const wchar_t * kind() const { return L"parsing"; } + ParseException(const wstring & msg, TextLocation where) : ConfigException(msg, where) { } + /*ConfigException::*/ const wchar_t * kind() const { return L"parsing"; } }; - __declspec_noreturn static void Fail(const wstring & msg, Token where) { throw ParseError(msg, where.beginLocation); } + __declspec_noreturn static void Fail(const wstring & msg, Token where) + { + Microsoft::MSR::CNTK::DebugUtil::PrintCallStack(); + throw ParseException(msg, where.beginLocation); + } //void Expected(const wstring & what) { Fail(strprintf("%ls expected", what.c_str()), GotToken().beginLocation); } // I don't know why this does not work void Expected(const wstring & what) { Fail(what + L" expected", GotToken().beginLocation); } diff --git a/BrainScript/BrainScriptParser.h b/BrainScript/BrainScriptParser.h index aa51114a0..4279e9aed 100644 --- a/BrainScript/BrainScriptParser.h +++ b/BrainScript/BrainScriptParser.h @@ -50,22 +50,22 @@ namespace Microsoft { namespace MSR { namespace BS { }; // --------------------------------------------------------------------------- - // ConfigError -- all errors from processing the config files are reported as ConfigError + // ConfigException -- all errors from processing the config files are reported as ConfigException // --------------------------------------------------------------------------- - class ConfigError : public Microsoft::MSR::ScriptableObjects::ScriptingError + class ConfigException : public Microsoft::MSR::ScriptableObjects::ScriptingException { vector locations; // error location (front()) and evaluation parents (upper) public: // Note: All our Error objects use wide strings, which we round-trip through runtime_error as utf8. - ConfigError(const wstring & msg, TextLocation where) : Microsoft::MSR::ScriptableObjects::ScriptingError(msra::strfun::utf8(msg)) { locations.push_back(where); } + ConfigException(const wstring & msg, TextLocation where) : Microsoft::MSR::ScriptableObjects::ScriptingException(msra::strfun::utf8(msg)) { locations.push_back(where); } // these are used in pretty-printing TextLocation where() const { return locations.front(); } // where the error happened virtual const wchar_t * kind() const = 0; // e.g. "warning" or "error" // pretty-print this as an error message - void /*ScriptingError::*/PrintError() const { TextLocation::PrintIssue(locations, L"error", kind(), msra::strfun::utf16(what()).c_str()); } + void /*ScriptingException::*/PrintError() const { TextLocation::PrintIssue(locations, L"error", kind(), msra::strfun::utf16(what()).c_str()); } void AddLocation(TextLocation where) { locations.push_back(where); } }; diff --git a/BrainScript/BrainScriptTest.cpp b/BrainScript/BrainScriptTest.cpp index e25c3df27..da490ab80 100644 --- a/BrainScript/BrainScriptTest.cpp +++ b/BrainScript/BrainScriptTest.cpp @@ -208,7 +208,7 @@ namespace Microsoft { namespace MSR { namespace BS { break; } } - catch (const ConfigError & err) + catch (const ConfigException & err) { err.PrintError(); } diff --git a/Common/BestGpu.cpp b/Common/BestGpu.cpp index 75c944065..e7d7bde31 100644 --- a/Common/BestGpu.cpp +++ b/Common/BestGpu.cpp @@ -471,7 +471,7 @@ std::vector BestGpu::GetDevices(int number, BestGpuFlags p_bestFlags) CrossProcessMutex deviceAllocationLock("DBN.exe GPGPU querying lock"); if (!deviceAllocationLock.Acquire((bestFlags & bestGpuExclusiveLock) != 0)) // failure --this should not really happen - throw std::runtime_error("DeviceFromConfig: unexpected failure"); + RuntimeError("DeviceFromConfig: unexpected failure"); { // even if user do not want to lock the GPU, we still need to check whether a particular GPU is locked or not, diff --git a/Common/Eval.cpp b/Common/Eval.cpp index 1f3b5be66..fd0393228 100644 --- a/Common/Eval.cpp +++ b/Common/Eval.cpp @@ -25,7 +25,7 @@ template<> std::string GetEvalName(double) {std::string name = "GetEvalD"; retur template void Eval::Init(const std::string& /*config*/) { - throw std::logic_error("Init shouldn't be called, use constructor"); + LogicError("Init shouldn't be called, use constructor"); // not implemented, calls the underlying class instead } diff --git a/Common/Include/Basics.h b/Common/Include/Basics.h index 21e64215a..8f47d6e36 100644 --- a/Common/Include/Basics.h +++ b/Common/Include/Basics.h @@ -10,6 +10,7 @@ #include "Platform.h" #include "DebugUtil.h" #include +#include #define TWO_PI 6.283185307f // TODO: find the official standards-confirming definition of this and use it instead @@ -17,7 +18,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { using namespace std; - // if it receives a lonely std::string then throw that directly + template + __declspec_noreturn static inline void ThrowFormatted() + { + Microsoft::MSR::CNTK::DebugUtil::PrintCallStack(); + throw E(); + } + template __declspec_noreturn static inline void ThrowFormatted(const string & message) { @@ -36,7 +43,8 @@ namespace Microsoft { namespace MSR { namespace CNTK { va_start(args, format); vsprintf(buffer, format, args); - ThrowFormatted(std::string(buffer)); + Microsoft::MSR::CNTK::DebugUtil::PrintCallStack(); + throw E(buffer); }; #pragma warning(pop) @@ -47,6 +55,8 @@ namespace Microsoft { namespace MSR { namespace CNTK { __declspec_noreturn static inline void LogicError(_Types&&... _Args) { ThrowFormatted(forward<_Types>(_Args)...); } template __declspec_noreturn static inline void InvalidArgument(_Types&&... _Args) { ThrowFormatted(forward<_Types>(_Args)...); } + template + __declspec_noreturn static inline void BadExceptionError(_Types&&... _Args) { ThrowFormatted(forward<_Types>(_Args)...); } // Warning - warn with a formatted error string #pragma warning(push) @@ -63,6 +73,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { static inline void Warning(const string & message) { Warning("%s", message.c_str()); } }}} +using Microsoft::MSR::CNTK::RuntimeError; +using Microsoft::MSR::CNTK::LogicError; +using Microsoft::MSR::CNTK::InvalidArgument; +using Microsoft::MSR::CNTK::BadExceptionError; #include "basetypes.h" // TODO: gradually move over here all that's needed of basetypes.h, then remove basetypes.h. diff --git a/Common/Include/MPIWrapper.h b/Common/Include/MPIWrapper.h index 4bf811325..3f4c08ae7 100644 --- a/Common/Include/MPIWrapper.h +++ b/Common/Include/MPIWrapper.h @@ -46,7 +46,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { // TODO: or does that only signal an issue, and we should still terminate ourselves? // BUGBUG: We'd also need to Abort through the other sub-set communicator } - throw std::runtime_error(what); + RuntimeError(what); } class MPIWrapper @@ -86,7 +86,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { static bool initialized = false; if (initialized) { - throw std::logic_error("MPIWrapper: this is a singleton class that can only be instantiated once per process"); + LogicError("MPIWrapper: this is a singleton class that can only be instantiated once per process"); } initialized = true; diff --git a/Common/Include/ScriptableObjects.h b/Common/Include/ScriptableObjects.h index f86d58398..0eac505cf 100644 --- a/Common/Include/ScriptableObjects.h +++ b/Common/Include/ScriptableObjects.h @@ -14,15 +14,15 @@ namespace Microsoft { namespace MSR { namespace ScriptableObjects { using namespace Microsoft::MSR::CNTK; // for stuff from Basics.h // ----------------------------------------------------------------------- - // ScriptingError -- base class for any errors thrown by scripting + // ScriptingException -- base class for any errors thrown by scripting // It's a runtime_error with an additional virtual function PrintError(). // ----------------------------------------------------------------------- - class ScriptingError : public runtime_error + class ScriptingException : public runtime_error { public: template - ScriptingError(const M & msg) : runtime_error(msg) { } + ScriptingException(const M & msg) : runtime_error(msg) { } virtual void PrintError() const = 0; }; diff --git a/Common/Include/basetypes.h b/Common/Include/basetypes.h index 2a1aa8f78..322e5f716 100644 --- a/Common/Include/basetypes.h +++ b/Common/Include/basetypes.h @@ -275,7 +275,7 @@ namespace msra { namespace basetypes { { #ifdef _WIN32 if (!QueryPerformanceFrequency (&freq)) // count ticks per second - throw std::runtime_error ("auto_timer: QueryPerformanceFrequency failure"); + RuntimeError("auto_timer: QueryPerformanceFrequency failure"); QueryPerformanceCounter (&start); #endif #ifdef __unix__ @@ -585,7 +585,7 @@ struct utf8 : std::string { utf8 (const std::wstring & p) // utf-16 to -8 std::fill (buf.begin (), buf.end (), 0); int rc = WideCharToMultiByte (CP_UTF8, 0, p.c_str(), (int) len, &buf[0], (int) buf.size(), NULL, NULL); - if (rc == 0) throw std::runtime_error ("WideCharToMultiByte"); + if (rc == 0) RuntimeError("WideCharToMultiByte"); (*(std::string*)this) = &buf[0]; }}; struct utf16 : std::wstring { utf16 (const std::string & p) // utf-8 to -16 @@ -597,7 +597,7 @@ struct utf16 : std::wstring { utf16 (const std::string & p) // utf-8 to -16 std::fill (buf.begin (), buf.end (), (wchar_t) 0); int rc = MultiByteToWideChar (CP_UTF8, 0, p.c_str(), (int) len, &buf[0], (int) buf.size()); - if (rc == 0) throw std::runtime_error ("MultiByteToWideChar"); + if (rc == 0) RuntimeError("MultiByteToWideChar"); ASSERT (rc < buf.size ()); (*(std::wstring*)this) = &buf[0]; }}; @@ -685,7 +685,7 @@ static inline double todouble (const char * s) char * ep; // will be set to point to first character that failed parsing double value = strtod (s, &ep); if (*s == 0 || *ep != 0) - throw std::runtime_error ("todouble: invalid input string"); + RuntimeError("todouble: invalid input string"); return value; } @@ -701,7 +701,7 @@ static inline double todouble (const std::string & s) #if _MSC_VER > 1400 // VS 2010+ size_t * idx = 0; value = std::stod (s, idx); - if (idx) throw std::runtime_error ("todouble: invalid input string"); + if (idx) RuntimeError("todouble: invalid input string"); #else char *ep = 0; // will be updated by strtod to point to first character that failed parsing value = strtod (s.c_str(), &ep); @@ -709,7 +709,7 @@ static inline double todouble (const std::string & s) // strtod documentation says ep points to first unconverted character OR // return value will be +/- HUGE_VAL for overflow/underflow if (ep != s.c_str() + s.length() || value == HUGE_VAL || value == -HUGE_VAL) - throw std::runtime_error ("todouble: invalid input string"); + RuntimeError("todouble: invalid input string"); #endif return value; @@ -719,7 +719,7 @@ static inline double todouble (const std::wstring & s) { wchar_t * endptr; double value = wcstod (s.c_str(), &endptr); - if (*endptr) throw std::runtime_error ("todouble: invalid input string"); + if (*endptr) RuntimeError("todouble: invalid input string"); return value; } @@ -770,7 +770,7 @@ class auto_file_ptr void close() throw() { if (f) try { if (f != stdin && f != stdout && f != stderr) ::fclose (f); } catch (...) { } f = NULL; } #pragma warning(push) #pragma warning(disable : 4996) - void openfailed (const std::string & path) { throw std::runtime_error ("auto_file_ptr: error opening file '" + path + "': " + strerror (errno)); } + void openfailed (const std::string & path) { RuntimeError("auto_file_ptr: error opening file '" + path + "': " + strerror (errno)); } #pragma warning(pop) protected: friend int fclose (auto_file_ptr&); // explicit close (note: may fail) @@ -853,7 +853,7 @@ public: operator bool() const { return ch != EOF; } // true if still a line to read std::string getline() // get and consume the next line { - if (ch == EOF) throw std::logic_error ("textreader: attempted to read beyond EOF"); + if (ch == EOF) LogicError("textreader: attempted to read beyond EOF"); assert (buf.empty()); // get all line's characters --we recognize UNIX (LF), DOS (CRLF), and Mac (CR) convention while (ch != EOF && ch != '\n' && ch != '\r') buf.push_back (getch()); diff --git a/Common/Include/fileutil.h b/Common/Include/fileutil.h index f8fe66ac0..8cb3984a7 100644 --- a/Common/Include/fileutil.h +++ b/Common/Include/fileutil.h @@ -414,9 +414,9 @@ void fgetText(FILE * f, T& v) { int rc = ftrygetText(f, v); if (rc == 0) - throw std::runtime_error("error reading value from file (invalid format)"); + RuntimeError("error reading value from file (invalid format)"); else if (rc == EOF) - throw std::runtime_error(std::string("error reading from file: ") + strerror(errno)); + RuntimeError(std::string("error reading from file: ") + strerror(errno)); assert(rc == 1); } @@ -447,9 +447,9 @@ void fputText(FILE * f, T v) const wchar_t* formatString = GetFormatString(v); int rc = fwprintf(f, formatString, v); if (rc == 0) - throw std::runtime_error("error writing value to file, no values written"); + RuntimeError("error writing value to file, no values written"); else if (rc < 0) - throw std::runtime_error(std::string("error writing to file: ") + strerror(errno)); + RuntimeError(std::string("error writing to file: ") + strerror(errno)); } // ---------------------------------------------------------------------------- diff --git a/Common/Include/latticearchive.h b/Common/Include/latticearchive.h index 9444e0bbb..d003ab06c 100644 --- a/Common/Include/latticearchive.h +++ b/Common/Include/latticearchive.h @@ -84,7 +84,7 @@ class lattice // - sortbyfinalsp = true: use in sorting (the longer edge with /sp/ will go FIRST so that it is the one to survive uniq-ing) // - sortbyfinalsp = false: use in uniq-ing; the edges will just be reported as identical if (edges[j1].implysp || edges[j2].implysp) - throw std::logic_error ("comparealign: must not operate on edges with implysp flag set"); + LogicError("comparealign: must not operate on edges with implysp flag set"); const auto a1 = getaligninfo (j1); const auto a2 = getaligninfo (j2); // sort by unit sequence first @@ -173,7 +173,7 @@ class lattice std::vector edges2; // TODO: rename these std::vector uniquededgedatatokens; // [-1]: LM score; [-2]: ac score; [0..]: actual aligninfo records float & uniqueedgelmscore (size_t firstalign) { return *(float*) &uniquededgedatatokens.data()[firstalign-1]; } - float & uniqueedgeacscore (size_t firstalign) { if (info.hasacscores) return *(float*) &uniquededgedatatokens.data()[firstalign-2]; else throw std::logic_error ("uniqueedgeacscore: no ac scores stored in this lattice"); } + float & uniqueedgeacscore (size_t firstalign) { if (info.hasacscores) return *(float*) &uniquededgedatatokens.data()[firstalign-2]; else LogicError("uniqueedgeacscore: no ac scores stored in this lattice"); } public: // TODO: make private again once // construct from edges/align // This is also used for merging, where the edges[] array is not correctly sorted. So don't assume this here. @@ -202,7 +202,7 @@ public: // TODO: make private again once foreach_index (j, edges) { if (edges[j].implysp) - throw std::logic_error ("builduniquealignments: original edges[] array must not have implied /sp/"); + LogicError("builduniquealignments: original edges[] array must not have implied /sp/"); edges2[j].S = edges[j].S; edges2[j].E = edges[j].E; edges2[j].unused = 0; @@ -257,7 +257,7 @@ public: // TODO: make private again once const auto ai = getaligninfo (j); size_t nalign = ai.size(); if (nalign == 0 && (size_t) j2 != edges.size() -1) - throw std::runtime_error ("builduniquealignments: !NULL edges forbidden except for the very last edge"); + RuntimeError("builduniquealignments: !NULL edges forbidden except for the very last edge"); // special optimization: we do not store the /sp/ unit at the end if (nalign > 1/*be robust against 1-unit edges that consist of spunit*/ && ai[nalign-1].unit == spunit) { @@ -272,7 +272,7 @@ public: // TODO: make private again once { auto a = ai[k]; if (a.last) - throw std::logic_error ("builduniquealignments: unexpected 'last' flag already set in input aligns (numeric overflow in old format?)"); + LogicError("builduniquealignments: unexpected 'last' flag already set in input aligns (numeric overflow in old format?)"); if (k == nalign -1) a.last = 1; uniquededgedatatokens.push_back (a); @@ -355,7 +355,7 @@ public: sile.a = LOGZERO; // must not have this anyway sile.firstalign = newalign.size(); // we create a new entry for this if (sile.firstalign != newalign.size()) - throw std::runtime_error ("hackinsilencesubstitutionedges: numeric bit-field overflow of .firstalign"); + RuntimeError("hackinsilencesubstitutionedges: numeric bit-field overflow of .firstalign"); newedges.push_back (sile); // create a new align entry aligninfo asil (silunit, numframes); @@ -365,7 +365,7 @@ public: edgeinfowithscores spe = sile; spe.firstalign = newalign.size(); if (spe.firstalign != newalign.size()) - throw std::runtime_error ("hackinsilencesubstitutionedges: numeric bit-field overflow of .firstalign"); + RuntimeError("hackinsilencesubstitutionedges: numeric bit-field overflow of .firstalign"); newedges.push_back (spe); aligninfo asp (spunit, numframes); newalign.push_back (asp); @@ -382,7 +382,7 @@ public: // copy the edge e.firstalign = newalign.size(); if (e.firstalign != newalign.size()) - throw std::runtime_error ("hackinsilencesubstitutionedges: numeric bit-field overflow of .firstalign"); + RuntimeError("hackinsilencesubstitutionedges: numeric bit-field overflow of .firstalign"); newedges.push_back (e); // copy the align records auto a = getaligninfo (j); @@ -443,31 +443,31 @@ public: const size_t edgedur = nodes[edges2[j].E].t - nodes[edges2[j].S].t; // for checking and back-filling the implied /sp/ size_t aligndur = 0; if (firstalign == uniquededgedatatokens.size() && (size_t) j != edges.size() -1) - throw std::runtime_error ("rebuildedges: !NULL edges forbidden except for the last edge"); + RuntimeError("rebuildedges: !NULL edges forbidden except for the last edge"); for (size_t k = firstalign; k < uniquededgedatatokens.size(); k++) { if (!isendworkaround.empty() && isendworkaround[k]) // secondary criterion to detect ends in broken lattices break; aligninfo ai = uniquededgedatatokens[k]; if (ai.unused != 0) - throw std::runtime_error ("rebuildedges: mal-formed uniquededgedatatokens[] array: 'unused' field must be 0"); + RuntimeError("rebuildedges: mal-formed uniquededgedatatokens[] array: 'unused' field must be 0"); bool islast = ai.last != 0; ai.last = 0; // old format does not support this align.push_back (ai); aligndur += ai.frames; if (aligndur > edgedur) - throw std::runtime_error ("rebuildedges: mal-formed uniquededgedatatokens[] array: aligment longer than edge"); + RuntimeError("rebuildedges: mal-formed uniquededgedatatokens[] array: aligment longer than edge"); if (islast) break; if (k == uniquededgedatatokens.size() -1) - throw std::runtime_error ("rebuildedges: mal-formed uniquededgedatatokens[] array: missing 'last' flag in last entry"); + RuntimeError("rebuildedges: mal-formed uniquededgedatatokens[] array: missing 'last' flag in last entry"); } if (edges2[j].implysp) { if (info.impliedspunitid == SIZE_MAX) - throw std::runtime_error ("rebuildedges: edge requests implied /sp/ but none specified in lattice header"); + RuntimeError("rebuildedges: edge requests implied /sp/ but none specified in lattice header"); if (aligndur > edgedur) - throw std::runtime_error ("rebuildedges: edge alignment longer than edge duration"); + RuntimeError("rebuildedges: edge alignment longer than edge duration"); aligninfo ai (info.impliedspunitid, edgedur - aligndur/*frames: remaining frames are /sp/ */); align.push_back (ai); } @@ -501,11 +501,11 @@ public: firstframe = (unsigned int) ts; firstalign = (unsigned int) as; if (wordindex != wid) - throw std::runtime_error ("htkmlfwordentry: vocabulary size too large for bit field 'wordindex'"); + RuntimeError("htkmlfwordentry: vocabulary size too large for bit field 'wordindex'"); if (firstframe != ts) - throw std::runtime_error ("htkmlfwordentry: start frame too large for bit field 'firstframe'"); + RuntimeError("htkmlfwordentry: start frame too large for bit field 'firstframe'"); if (firstalign != as) - throw std::runtime_error ("htkmlfwordentry: first-align index too large for bit field 'firstframe'"); + RuntimeError("htkmlfwordentry: first-align index too large for bit field 'firstframe'"); } }; @@ -708,21 +708,21 @@ public: { const auto & e = edges[j]; if (e.E <= e.S) - throw std::runtime_error ("checklattice: lattice is not topologically sorted"); + RuntimeError("checklattice: lattice is not topologically sorted"); if (nodes[e.E].t < nodes[e.S].t) - throw std::runtime_error ("checklattice: lattice edge has negative time range"); + RuntimeError("checklattice: lattice edge has negative time range"); if (nodes[e.E].t == nodes[e.S].t && j < info.numedges-1) - throw std::runtime_error ("checklattice: 0-frame edges forbidden except for very last edge"); + RuntimeError("checklattice: 0-frame edges forbidden except for very last edge"); if (j != (info.numedges - 1) && nodes[e.E].t == nodes[e.S].t)// last arc can be zero time range - throw std::runtime_error ("checklattice: lattice edge has zero time range"); + RuntimeError("checklattice: lattice edge has zero time range"); if (j > 0 && e.E < edges[j-1].E) - throw std::runtime_error ("checklattice: lattice is not sorted by end node"); + RuntimeError("checklattice: lattice is not sorted by end node"); if (j > 0 && e.E == edges[j-1].E && e.S < edges[j-1].S) // == also not allowed except for terminal edges - throw std::runtime_error ("checklattice: lattice is not sorted by start node within the same end node"); + RuntimeError("checklattice: lattice is not sorted by start node within the same end node"); if (j > 0 && e.E == edges[j-1].E && e.S == edges[j-1].S) { // Note: same E means identical word on the edge, due to word id stored on node. Thus, the edge is redundant = forbidden. if (e.E != info.numnodes-1) - throw std::runtime_error ("checklattice: lattice has duplicate edges"); + RuntimeError("checklattice: lattice has duplicate edges"); else // Exception: end of lattice, which happens rarely (2 examples found) and won't cause dramatic error, none in typical cases. fprintf (stderr, "checklattice: WARNING: duplicate edge J=%d (S=%d -> E=%d) at end of lattice\n", (int) j, (int) e.S, (int) e.E); } @@ -731,15 +731,15 @@ public: } // check nodes and in/out counts if (nodes[0].t != 0.0f) - throw std::runtime_error ("checklattice: lattice does not begin with time 0"); + RuntimeError("checklattice: lattice does not begin with time 0"); for (size_t i = 0; i < info.numnodes; i++) { if (i > 0 && nodes[i].t < nodes[i-1].t) - throw std::runtime_error ("checklattice: lattice nodes not sorted by time"); + RuntimeError("checklattice: lattice nodes not sorted by time"); if ((numin[i] > 0) ^ (i > 0)) - throw std::runtime_error ("checklattice: found an orphaned start node"); + RuntimeError("checklattice: found an orphaned start node"); if ((numout[i] > 0) ^ (i < info.numnodes-1)) - throw std::runtime_error ("checklattice: found an orphaned end node"); + RuntimeError("checklattice: found an orphaned end node"); } } @@ -851,7 +851,7 @@ public: { const size_t sz = freadtag (f, tag); if (expectedsize != SIZE_MAX && sz != expectedsize) - throw std::runtime_error (std::string ("freadvector: malformed file, number of vector elements differs from head, for tag ") + tag); + RuntimeError(std::string ("freadvector: malformed file, number of vector elements differs from head, for tag ") + tag); freadOrDie (v, sz, f); } @@ -870,7 +870,7 @@ public: freadOrDie (&info, sizeof (info), 1, f); freadvector (f, "NODE", nodes, info.numnodes); if (nodes.back().t != info.numframes) - throw std::runtime_error ("fread: mismatch between info.numframes and last node's time"); + RuntimeError("fread: mismatch between info.numframes and last node's time"); freadvector (f, "EDGE", edges, info.numedges); freadvector (f, "ALIG", align); fcheckTag (f, "END "); @@ -889,7 +889,7 @@ public: freadOrDie (&info, sizeof (info), 1, f); freadvector (f, "NODS", nodes, info.numnodes); if (nodes.back().t != info.numframes) - throw std::runtime_error ("fread: mismatch between info.numframes and last node's time"); + RuntimeError("fread: mismatch between info.numframes and last node's time"); freadvector (f, "EDGS", edges2, info.numedges); // uniqued edges freadvector (f, "ALNS", uniquededgedatatokens); // uniqued alignments fcheckTag (f, "END "); @@ -898,7 +898,7 @@ public: if (info.impliedspunitid != SIZE_MAX && info.impliedspunitid >= idmap.size()) // we have buggy lattices like that--what do they mean?? { fprintf (stderr, "fread: detected buggy spunit id %d which is out of range (%d entries in map)\n", (int)info.impliedspunitid, (int)idmap.size()); - throw std::runtime_error ("fread: out of bounds spunitid"); + RuntimeError("fread: out of bounds spunitid"); } #endif // This is critical--we have a buggy lattice set that requires no mapping where mapping would fail @@ -942,7 +942,7 @@ public: // this is a regular token: update it in-place auto & ai = uniquededgedatatokens[k]; if (ai.unit >= idmap.size()) - throw std::runtime_error ("fread: broken-file heuristics failed"); + RuntimeError("fread: broken-file heuristics failed"); ai.updateunit (idmap); // updates itself if (!ai.last) continue; @@ -957,13 +957,13 @@ public: { // fprintf (stderr, "fread: inconsistent spunit id in file %d vs. expected %d; due to erroneous heuristic\n", info.impliedspunitid, spunit); // [v-hansu] comment out becaues it takes up most of the log // it's actually OK, we can live with this, since we only decompress and then move on without any assumptions - //throw std::runtime_error ("fread: mismatching /sp/ units"); + //RuntimeError("fread: mismatching /sp/ units"); } // reconstruct old lattice format from this --TODO: remove once we change to new data representation rebuildedges (info.impliedspunitid != spunit/*to be able to read somewhat broken V2 lattice archives*/); } else - throw std::runtime_error ("fread: unsupported lattice format version"); + RuntimeError("fread: unsupported lattice format version"); } // parallel versions (defined in parallelforwardbackward.cpp) @@ -1032,7 +1032,7 @@ class archive { auto iter = symmap.find (key); if (iter == symmap.end()) - throw std::runtime_error (std::string ("getcachedidmap: symbol not found in user-supplied symbol map: ") + key); + RuntimeError(std::string ("getcachedidmap: symbol not found in user-supplied symbol map: ") + key); return iter->second; } template const symbolidmapping & getcachedidmap (size_t archiveindex, const SYMMAP & symmap/*[string] -> numeric id*/) const @@ -1062,12 +1062,12 @@ class archive symstring = sym; // (reusing existing object to avoid malloc) tosymstring = tosym; if (getid (symmap, symstring) != getid (symmap, tosymstring)) - throw std::runtime_error (std::string ("getcachedidmap: mismatching symbol id for ") + sym + " vs. " + tosym); + RuntimeError(std::string ("getcachedidmap: mismatching symbol id for ") + sym + " vs. " + tosym); } else { if ((size_t) i != idmap.size()) // non-mappings must come first (this is to ensure compatibility with pre-mapping files) - throw std::runtime_error ("getcachedidmap: mixed up symlist file"); + RuntimeError("getcachedidmap: mixed up symlist file"); symstring = sym; // (reusing existing object to avoid malloc) idmap.push_back ((unsigned int) getid (symmap, symstring)); } @@ -1127,12 +1127,12 @@ public: const char * line = toclines[i]; const char * p = strchr (line, '='); if (p == NULL) - throw std::runtime_error ("open: invalid TOC line (no = sign): " + std::string (line)); + RuntimeError("open: invalid TOC line (no = sign): " + std::string (line)); const std::wstring key = msra::strfun::utf16 (std::string (line, p - line)); p++; const char * q = strchr (p, '['); if (q == NULL) - throw std::runtime_error ("open: invalid TOC line (no [): " + std::string (line)); + RuntimeError("open: invalid TOC line (no [): " + std::string (line)); if (q != p) { const std::wstring archivepath = msra::strfun::utf16 (std::string (p, q - p)); @@ -1140,7 +1140,7 @@ public: archiveindex = getarchiveindex (archivepath); } if (archiveindex == SIZE_MAX) - throw std::runtime_error ("open: invalid TOC line (empty archive pathname): " + std::string (line)); + RuntimeError("open: invalid TOC line (empty archive pathname): " + std::string (line)); char c; uint64_t offset; #ifdef _WIN32 @@ -1149,9 +1149,9 @@ public: if (sscanf (q, "[%" PRIu64 "]%c", &offset, &c) != 1) #endif - throw std::runtime_error ("open: invalid TOC line (bad [] expression): " + std::string (line)); + RuntimeError("open: invalid TOC line (bad [] expression): " + std::string (line)); if (!toc.insert (make_pair (key, latticeref (offset, archiveindex))).second) - throw std::runtime_error ("open: TOC entry leads to duplicate key: " + std::string (line)); + RuntimeError("open: TOC entry leads to duplicate key: " + std::string (line)); } // initialize symmaps --alloc the array, but actually read the symmap on demand @@ -1183,7 +1183,7 @@ public: { auto iter = toc.find (key); if (iter == toc.end()) - throw std::logic_error ("getlattice: requested lattice for non-existent key; haslattice() should have been used to check availability"); + LogicError("getlattice: requested lattice for non-existent key; haslattice() should have been used to check availability"); // get the archive that the lattice lives in and its byte offset const size_t archiveindex = iter->second.archiveindex; const auto offset = iter->second.offset; @@ -1193,7 +1193,7 @@ public: #if 1 // prep for fixing the pushing of /sp/ at the end --we actually can just look it up! Duh const size_t spunit2 = getid (modelsymmap, "sp"); if (spunit2 != spunit) - throw std::logic_error ("getlattice: huh? same lookup of /sp/ gives different result?"); + LogicError("getlattice: huh? same lookup of /sp/ gives different result?"); #endif // open archive file in case it is not the current one if (archiveindex != currentarchiveindex) @@ -1221,7 +1221,7 @@ public: } // check if number of frames is as expected if (expectedframes != SIZE_MAX && L.getnumframes() != expectedframes) - throw std::logic_error ("getlattice: number of frames mismatch between numerator lattice and features"); + LogicError("getlattice: number of frames mismatch between numerator lattice and features"); // remember the latice key for diagnostics messages L.key = key; }; diff --git a/Common/Include/latticesource.h b/Common/Include/latticesource.h index b7e7ccf8d..2979e8a85 100644 --- a/Common/Include/latticesource.h +++ b/Common/Include/latticesource.h @@ -20,7 +20,7 @@ public: { #ifndef NONUMLATTICEMMI // TODO:set NUM lattice to null so as to save memory if (numlattices.empty() ^ denlattices.empty()) - throw std::runtime_error("latticesource: numerator and denominator lattices must be either both empty or both not empty"); + RuntimeError("latticesource: numerator and denominator lattices must be either both empty or both not empty"); #endif return denlattices.empty(); } diff --git a/Common/Include/latticestorage.h b/Common/Include/latticestorage.h index 25872a12e..f94e6537b 100644 --- a/Common/Include/latticestorage.h +++ b/Common/Include/latticestorage.h @@ -6,10 +6,9 @@ // latticestorage.h -- basic data structures for storing lattices -#if 0 // [v-hansu] separate code with history -#endif - #pragma once + +#include "Basics.h" #include // for the error message in checkoverflow() only #include #include @@ -32,7 +31,7 @@ static void checkoverflow (size_t fieldval, size_t targetval, const char * field std::snprintf #endif (buf, sizeof(buf), "lattice: bit field %s too small for value 0x%x (cut from 0x%x)", fieldname, (unsigned int)targetval, (unsigned int)fieldval); - throw std::runtime_error (buf); + RuntimeError(buf); } } diff --git a/Common/Include/minibatchsourcehelpers.h b/Common/Include/minibatchsourcehelpers.h index 0a9d30583..f58d9ad43 100644 --- a/Common/Include/minibatchsourcehelpers.h +++ b/Common/Include/minibatchsourcehelpers.h @@ -57,12 +57,12 @@ public: { // test for numeric overflow if (map.size()-1 != (INDEXTYPE) (map.size()-1)) - throw std::runtime_error ("randomordering: INDEXTYPE has too few bits for this corpus"); + RuntimeError("randomordering: INDEXTYPE has too few bits for this corpus"); // 0, 1, 2... foreach_index (t, map) map[t] = (INDEXTYPE) t; if (map.size() > RAND_MAX * (size_t) RAND_MAX) - throw std::runtime_error ("randomordering: too large training set: need to change to different random generator!"); + RuntimeError("randomordering: too large training set: need to change to different random generator!"); srand ((unsigned int) seed); size_t retries = 0; foreach_index (t, map) @@ -96,7 +96,7 @@ public: foreach_index (t, map) if (!((size_t) t <= map[t] + randomizationrange/2 && map[t] < (size_t) t + randomizationrange/2)) { fprintf (stderr, "randomordering: windowing condition violated %d -> %d\n", t, map[t]); - throw std::logic_error ("randomordering: windowing condition violated"); + LogicError("randomordering: windowing condition violated"); } #endif #if 0 // test whether it is indeed a unique complete sequence diff --git a/Common/Include/numahelpers.h b/Common/Include/numahelpers.h index 38f4aff88..e92445fc2 100644 --- a/Common/Include/numahelpers.h +++ b/Common/Include/numahelpers.h @@ -48,7 +48,7 @@ template void parallel_for_on_each_numa_node (bool multistep // now run on many threads, hoping to hit all NUMA nodes, until we are done hardcoded_array nextstepcounters; // next block to run for a NUMA node if (nodes > nextstepcounters.size()) - throw std::logic_error ("parallel_for_on_each_numa_node: nextstepcounters buffer too small, need to increase hard-coded size"); + LogicError("parallel_for_on_each_numa_node: nextstepcounters buffer too small, need to increase hard-coded size"); for (size_t k = 0; k < nodes; k++) nextstepcounters[k] = 0; overridenode(); //unsigned int totalloops = 0; // for debugging only, can be removed later @@ -69,7 +69,7 @@ template void parallel_for_on_each_numa_node (bool multistep return; // done } // oops?? - throw std::logic_error ("parallel_for_on_each_numa_node: no left-over block found--should not get here!!"); + LogicError("parallel_for_on_each_numa_node: no left-over block found--should not get here!!"); }); //assert (totalloops == nodes * steps); } @@ -100,7 +100,7 @@ static inline size_t getcurrentnode() UCHAR n; if (!GetNumaProcessorNode ((UCHAR) i, &n)) return 0; if (n == 0xff) - throw std::logic_error ("GetNumaProcessorNode() failed to determine NUMA node for GetCurrentProcessorNumber()??"); + LogicError("GetNumaProcessorNode() failed to determine NUMA node for GetCurrentProcessorNumber()??"); return n; } @@ -135,7 +135,7 @@ static inline void * malloc (size_t n, size_t align) if (p == NULL) fprintf (stderr, "numa::malloc: failed allocating %d bytes with alignment %d\n", n, align); if (((size_t) p) % align != 0) - throw std::logic_error ("VirtualAllocExNuma() returned an address that does not match the alignment requirement"); + LogicError("VirtualAllocExNuma() returned an address that does not match the alignment requirement"); return p; } @@ -144,7 +144,7 @@ static inline void free (void * p) { assert (p != NULL); if (!VirtualFree (p, 0, MEM_RELEASE)) - throw std::logic_error ("VirtualFreeEx failure"); + LogicError("VirtualFreeEx failure"); } // dump memory allocation diff --git a/Common/Include/simplesenonehmm.h b/Common/Include/simplesenonehmm.h index 19ddadef1..e62000f88 100644 --- a/Common/Include/simplesenonehmm.h +++ b/Common/Include/simplesenonehmm.h @@ -37,7 +37,7 @@ public: // (TODO: better encapsulation) unsigned short senoneids[MAXSTATES]; // [0..numstates-1] senone indices const char * getname() const { return name; } // (should be used for diagnostics only) - size_t getsenoneid (size_t i) const { if (i < numstates) return (size_t) senoneids[i]; throw std::logic_error ("getsenoneid: out of bounds access"); } + size_t getsenoneid (size_t i) const { if (i < numstates) return (size_t) senoneids[i]; LogicError("getsenoneid: out of bounds access"); } size_t getnumstates() const { return (size_t) numstates; } unsigned char gettransPindex() const { return transPindex;} const struct transP & gettransP() const { return *transP; } @@ -54,9 +54,9 @@ public: // (TODO: better encapsulation) private: size_t numstates; float loga[MAXSTATES+1][MAXSTATES+1]; - void check (int from, size_t to) const { if (from < -1 || from >= (int) numstates || to > numstates) throw std::logic_error ("transP: index out of bounds"); } + void check (int from, size_t to) const { if (from < -1 || from >= (int) numstates || to > numstates) LogicError("transP: index out of bounds"); } public: - void resize (size_t n) { if (n > MAXSTATES) throw std::runtime_error ("resize: requested transP that exceeds MAXSTATES"); numstates = n; } + void resize (size_t n) { if (n > MAXSTATES) RuntimeError("resize: requested transP that exceeds MAXSTATES"); numstates = n; } size_t getnumstates() const { return numstates; } // from = -1 and to = numstates are allowed, but we also allow 'from' to be size_t to avoid silly typecasts float & operator() (int from, size_t to) { check (from, to); return loga[from+1][to]; } // from >= -1 @@ -75,7 +75,7 @@ public: { auto iter = symmap.find (name); if (iter == symmap.end()) - throw std::logic_error ("gethmm: unknown unit name: " + name); + LogicError("gethmm: unknown unit name: " + name); return iter->second; } @@ -113,19 +113,19 @@ public: { toks = transPlines[i]; if (toks.size() < 3) - throw std::runtime_error ("simplesenonehmm: too few tokens in transP line: " + string (transPlines[i])); + RuntimeError("simplesenonehmm: too few tokens in transP line: " + string (transPlines[i])); key = toks[0]; // transPname --using existing object to avoid malloc transPmap[key] = i; size_t numstates = msra::strfun::toint (toks[1]); if (numstates == 0) - throw std::runtime_error ("simplesenonehmm: invalid numstates: " + string (transPlines[i])); + RuntimeError("simplesenonehmm: invalid numstates: " + string (transPlines[i])); auto & transP = transPs[i]; transP.resize (numstates); size_t k = 2; // index into tokens; transP values start at toks[2] for (int from = -1; from < (int) numstates; from++) for (size_t to = 0; to <= numstates; to++) { if (k >= toks.size()) - throw std::runtime_error ("simplesenonehmm: not enough tokens on transP line: " + string (transPlines[i])); + RuntimeError("simplesenonehmm: not enough tokens on transP line: " + string (transPlines[i])); const char * sval = toks[k++]; const double aij = msra::strfun::todouble (sval); if (aij > 1e-10) // non-0 @@ -134,7 +134,7 @@ public: transP(from,to) = -1e30f; } if (toks.size() > k) - throw std::runtime_error ("simplesenonehmm: unexpected garbage at endof transP line: " + string (transPlines[i])); + RuntimeError("simplesenonehmm: unexpected garbage at endof transP line: " + string (transPlines[i])); } // allocate inverse lookup senoneid2transPindex.resize (readstatenames.size(), -2); @@ -151,7 +151,7 @@ public: { toks = lines[i]; if (toks.size() < 3) - throw std::runtime_error ("simplesenonehmm: too few tokens in line: " + string (lines[i])); + RuntimeError("simplesenonehmm: too few tokens in line: " + string (lines[i])); const char * hmmname = toks[0]; const char * transPname = toks[1]; // build the HMM structure @@ -162,28 +162,28 @@ public: key = transPname; // (reuse existing memory) auto iter = transPmap.find (key); if (iter == transPmap.end()) - throw std::runtime_error ("simplesenonehmm: unknown transP name: " + string (lines[i])); + RuntimeError("simplesenonehmm: unknown transP name: " + string (lines[i])); size_t transPindex = iter->second; hmm.transPindex = (unsigned char) transPindex; hmm.transP = &transPs[transPindex]; if (hmm.transPindex != transPindex) - throw std::runtime_error ("simplesenonehmm: numeric overflow for transPindex field"); + RuntimeError("simplesenonehmm: numeric overflow for transPindex field"); // get the senones hmm.numstates = (unsigned char) (toks.size() - 2); // remaining tokens if (hmm.numstates != transPs[transPindex].getnumstates()) - throw std::runtime_error ("simplesenonehmm: number of states mismatches that of transP: " + string (lines[i])); + RuntimeError("simplesenonehmm: number of states mismatches that of transP: " + string (lines[i])); if (hmm.numstates > _countof (hmm.senoneids)) - throw std::runtime_error ("simplesenonehmm: hmm.senoneids[MAXSTATES] is too small in line: " + string (lines[i])); + RuntimeError("simplesenonehmm: hmm.senoneids[MAXSTATES] is too small in line: " + string (lines[i])); for (size_t s = 0; s < hmm.numstates; s++) { const char * senonename = toks[s+2]; key = senonename; // (reuse existing memory) auto iter = statemap.find (key); if (iter == statemap.end()) - throw std::runtime_error ("simplesenonehmm: unrecognized senone name in line: " + string (lines[i])); + RuntimeError("simplesenonehmm: unrecognized senone name in line: " + string (lines[i])); hmm.senoneids[s] = (unsigned short) iter->second; if (hmm.getsenoneid(s) != iter->second) - throw std::runtime_error ("simplesenonehmm: not enough bits to store senone index in line: " + string (lines[i])); + RuntimeError("simplesenonehmm: not enough bits to store senone index in line: " + string (lines[i])); // inverse lookup if (senoneid2transPindex[hmm.senoneids[s]] == -2) // no value yet senoneid2transPindex[hmm.senoneids[s]] = hmm.transPindex; @@ -199,7 +199,7 @@ public: // add to name-to-HMM hash auto ir = name2hmm.insert (std::make_pair (hmmname, hmm)); // insert into hash table if (!ir.second) // not inserted - throw std::runtime_error ("simplesenonehmm: duplicate unit name in line: " + string (lines[i])); + RuntimeError("simplesenonehmm: duplicate unit name in line: " + string (lines[i])); // add to hmm-to-index hash // and update the actual lookup table size_t hmmindex = hmms.size(); // (assume it's a new entry) diff --git a/Common/Include/ssematrix.h b/Common/Include/ssematrix.h index 80c39b341..e4ecbc2da 100644 --- a/Common/Include/ssematrix.h +++ b/Common/Include/ssematrix.h @@ -66,7 +66,7 @@ protected: colstride = (n + 3) & ~3; // pad to multiples of four floats (required SSE alignment) const size_t totalelem = colstride * m; if (totalelem + 3 > _countof (buffer)) // +3 for alignment, as buffer may live on the stack and would thus be unaligned - throw std::logic_error ("ssematrixbase from vector buffer: buffer too small"); + LogicError("ssematrixbase from vector buffer: buffer too small"); p = &buffer[0]; // align to 4-float boundary (required for SSE) // x64 stack is aligned to 16 bytes, but x86 is not. Also, float[] would not be guaranteed. @@ -81,11 +81,11 @@ protected: p = &buffer[0]; size_t offelem = (((size_t)p) / sizeof (float)) % 4; if (offelem != 0) - throw std::logic_error ("ssematrixbase from vector buffer: must be SSE-aligned"); + LogicError("ssematrixbase from vector buffer: must be SSE-aligned"); colstride = (n + 3) & ~3; // pad to multiples of four floats (required SSE alignment) const size_t totalelem = colstride * m; if (totalelem != buffer.size()) - throw std::logic_error ("ssematrixbase from vector buffer: incorrect buffer size"); + LogicError("ssematrixbase from vector buffer: incorrect buffer size"); // align to 4-float boundary (required for SSE) // x64 stack is aligned to 16 bytes, but x86 is not. Also, float[] would not be guaranteed. numrows = n; numcols = m; @@ -930,7 +930,7 @@ public: auto & us = *this; foreach_coord (ii, jj, us) if (us(ii,jj) != to(jj,ii)) - throw std::logic_error ("parallel_transpose: post-condition check failed--you got it wrong, man!"); + LogicError("parallel_transpose: post-condition check failed--you got it wrong, man!"); #endif } #endif @@ -1015,7 +1015,7 @@ public: for (size_t jj = 0; jj < j1; jj++) foreach_row (ii, us) if (us(ii,jj) != to(jj,ii)) - throw std::logic_error ("transpose: post-condition check failed--you got it wrong, man!"); + LogicError("transpose: post-condition check failed--you got it wrong, man!"); #endif } @@ -1026,7 +1026,7 @@ public: assert (U.cols() == V.rows() && U.rows() == V.cols()); foreach_coord (i, j, U) if (U(i,j) != V(j,i)) - throw std::logic_error ("checktranspose: post-condition check failed--you got it wrong, man!"); + LogicError("checktranspose: post-condition check failed--you got it wrong, man!"); } #endif #else // futile attempts to speed it up --the imul don't matter (is SSE so slow?) @@ -1104,7 +1104,7 @@ public: #if 0 // double-check foreach_coord (ii, jj, us) if (us(ii,jj) != to(jj,ii)) - throw std::logic_error ("transpose: post-condition check failed--you got it wrong, man!"); + LogicError("transpose: post-condition check failed--you got it wrong, man!"); #endif } #endif @@ -1186,10 +1186,10 @@ public: { const auto & us = *this; if (us.cols() != other.cols() || us.rows() != other.rows()) - throw std::logic_error ("checkequal: post-condition check failed (dim)--you got it wrong, man!"); + LogicError("checkequal: post-condition check failed (dim)--you got it wrong, man!"); foreach_coord (i, j, us) if (us(i,j) != other(i,j)) - throw std::logic_error ("checkequal: post-condition check failed (values)--you got it wrong, man!"); + LogicError("checkequal: post-condition check failed (values)--you got it wrong, man!"); } void dump(char * name) const @@ -1249,7 +1249,7 @@ public: { assert (other.empty() || j0 + m <= other.cols()); if (!other.empty() && j0 + m > other.cols()) // (runtime check to be sure--we use this all the time) - throw std::logic_error ("ssematrixstriperef: stripe outside original matrix' dimension"); + LogicError("ssematrixstriperef: stripe outside original matrix' dimension"); this->p = other.empty() ? NULL : &other(0,j0); this->numrows = other.rows(); this->numcols = m; @@ -1276,12 +1276,7 @@ public: template class ssematrix : public ssematrixbase { // helpers for SSE-compatible memory allocation -#ifdef _MSC_VER - static __declspec_noreturn void failed(size_t nbytes) { static/*not thread-safe--for diagnostics only*/ char buf[80] = { 0 }; sprintf_s(buf, "allocation of SSE vector failed (%d bytes)", nbytes); throw std::bad_exception(buf); } -#endif -#ifdef __unix__ - static void failed (size_t nbytes) { static/*not thread-safe--for diagnostics only*/ char buf[80] = { 0 }; sprintf_s (buf, sizeof(buf), "allocation of SSE vector failed (%d bytes)", (int)nbytes); throw std::bad_exception (); } -#endif + static __declspec_noreturn void failed(size_t nbytes) { BadExceptionError("allocation of SSE vector failed (%d bytes)", nbytes); } #ifdef _WIN32 template static T * new_sse (size_t nbytes) { T * pv = (T *) _aligned_malloc (nbytes * sizeof (T), 16); if (pv) return pv; failed (nbytes * sizeof (T)); } static void delete_sse (void * p) { if (p) _aligned_free (p); } @@ -1369,7 +1364,7 @@ public: if (empty()) resize (n, m); else if (n != numrows || m != numcols) - throw std::logic_error ("resizeonce: attempted to resize a second time to different dimensions"); + LogicError("resizeonce: attempted to resize a second time to different dimensions"); #endif } @@ -1377,7 +1372,7 @@ public: void shrink(size_t newrows, size_t newcols) { if (newrows > this->numrows || newcols > this->numcols) - throw std::logic_error ("shrink: attempted to grow the matrix"); + LogicError("shrink: attempted to grow the matrix"); this->numrows = newrows; this->numcols = newcols; } @@ -1420,7 +1415,7 @@ public: char namebuf[80]; const char * nameread = fgetstring (f, namebuf); if (strcmp (name, nameread) != 0) - throw std::runtime_error (string ("unexpected matrix name tag '") + nameread + "', expected '" + name + "'"); + RuntimeError(string ("unexpected matrix name tag '") + nameread + "', expected '" + name + "'"); size_t n = fgetint (f); size_t m = fgetint (f); resize (n, m); @@ -1439,7 +1434,7 @@ public: char namebuf[80]; const char * nameread = fgetstring (f, namebuf); if (strcmp (name, nameread) != 0) - throw std::runtime_error (string ("unexpected matrix name tag '") + nameread + "', expected '" + name + "'"); + RuntimeError(string ("unexpected matrix name tag '") + nameread + "', expected '" + name + "'"); size_t n = fgetint (f); size_t m = fgetint (f); resize (n, m); diff --git a/DataReader/BinaryReader/BinaryFile.cpp b/DataReader/BinaryReader/BinaryFile.cpp index 53a97293b..413d5272e 100644 --- a/DataReader/BinaryReader/BinaryFile.cpp +++ b/DataReader/BinaryReader/BinaryFile.cpp @@ -39,7 +39,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Unable to Open/Create file %ls, error %x", fileName.c_str(), GetLastError()); - throw runtime_error(message); + RuntimeError(message); } // code to detect type of file (network/local) @@ -67,7 +67,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Unable to map file %ls, error 0x%x", fileName.c_str(), GetLastError()); - throw runtime_error(message); + RuntimeError(message); } m_mappedSize = size; @@ -104,7 +104,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[128]; sprintf_s(message, "Setting max position larger than mapped file size: %ld > %ld", m_filePositionMax, m_mappedSize); - throw runtime_error(message); + RuntimeError(message); } } @@ -210,7 +210,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[128]; sprintf_s(message, "Unable to map file %ls @ %lld, error %x", m_name.c_str(), filePosition, GetLastError()); - throw runtime_error(message); + RuntimeError(message); } m_views.push_back(ViewPosition(pBuf, filePosition, size)); @@ -346,7 +346,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[128]; sprintf_s(message, "Invalid File format for binary file %ls", fileName.c_str()); - throw runtime_error(message); + RuntimeError(message); } } @@ -452,7 +452,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { // check for valid index if (m_sections.size() <= index) { - throw runtime_error("ReadSection:Invalid index"); + RuntimeError("ReadSection:Invalid index"); } // already loaded, so return @@ -495,7 +495,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Invalid header in file %ls, in header %s\n", m_file->GetName(), section->GetName()); - throw runtime_error(message); + RuntimeError(message); } @@ -535,7 +535,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Element out of range, error accesing element %lld, size=%lld\n", element, bytesRequested); - throw runtime_error(message); + RuntimeError(message); } // make sure we have the buffer in the range to handle the request @@ -558,7 +558,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Element out of range, error accesing element %lld, max element=%lld\n", element, GetElementCount()); - throw runtime_error(message); + RuntimeError(message); } // section is mapped as a whole, so no separate mapping for element buffer @@ -652,7 +652,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { int64_t offset = section->m_filePosition - filePosition; if (offset < 0) - throw runtime_error("RemapHeader:Invalid mapping, children must follow parent in mapping space"); + RuntimeError("RemapHeader:Invalid mapping, children must follow parent in mapping space"); // update our header location SectionHeader* header = section->m_sectionHeader = (SectionHeader*)((char*)view + offset); @@ -721,7 +721,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { auto sectionOwner = SectionMappingOwner(); if (filePosition < sectionOwner->GetFilePosition()) - throw runtime_error("invalid fileposition, cannot be earlier in the file than mapping parent"); + RuntimeError("invalid fileposition, cannot be earlier in the file than mapping parent"); size_t offset = filePosition-sectionOwner->GetFilePosition(); size_t totalSize = offset + max(size,sectionHeaderMin); @@ -746,7 +746,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } case mappingFile: if (filePosition != 0) - throw runtime_error("invalid fileposition, file mapping sections must start at filePostion zero"); + RuntimeError("invalid fileposition, file mapping sections must start at filePostion zero"); // intentional fall-through - same case, just at beginning of file case mappingSectionAll: sectionHeader = m_file->GetSection(filePosition, size); @@ -902,7 +902,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { m_mappingType = mappingType; if (size < sectionHeaderMin && file->Writing()) - throw runtime_error("Insufficient size requested for section in write mode"); + RuntimeError("Insufficient size requested for section in write mode"); // clear out element window mapping variables m_elementView = NULL; // pointer to beginning of the valid view @@ -946,7 +946,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { SectionHeader* header = section->GetHeader(); header->sectionFilePosition[header->dataSections++] = filePosition; if (header->dataSections && header->sectionFilePosition[header->dataSections-1] < filePosition) - throw runtime_error("invalid fileposition for section, subsection cannot start earlier in the file than parent section"); + RuntimeError("invalid fileposition for section, subsection cannot start earlier in the file than parent section"); // now update size for all pervious ancestor sections do @@ -1004,7 +1004,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else { // hum, is this allowable? - throw runtime_error("Invalid size in Binary Writer, variable sized data with no length"); + RuntimeError("Invalid size in Binary Writer, variable sized data with no length"); } char* data = section->EnsureElements(index, size); @@ -1048,9 +1048,9 @@ namespace Microsoft { namespace MSR { namespace CNTK { { Section* section = this; if (labelMapping.size() != GetElementCount()) - throw runtime_error("SetLabelMapping called with mapping table that doesn't match file defined element count"); + RuntimeError("SetLabelMapping called with mapping table that doesn't match file defined element count"); if (GetSectionType() != sectionTypeLabelMapping) - throw runtime_error("label type invalid"); + RuntimeError("label type invalid"); // free the old mapping tables m_mapLabelToId.clear(); @@ -1067,7 +1067,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Mapping table doesn't contain an entry for label Id#%d\n", i); - throw runtime_error(message); + RuntimeError(message); } // add to reverse mapping table @@ -1079,7 +1079,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Not enough room in mapping buffer, %lld bytes insufficient for string %d - %s\n", originalSize, i, str.c_str()); - throw runtime_error(message); + RuntimeError(message); } size_t len = str.length()+1; // don't forget the null size -= len; @@ -1101,7 +1101,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "GetElement: invalid index, %lld requested when there are only %lld elements\n", index, GetElementCount()); - throw runtime_error(message); + RuntimeError(message); } // now skip all the strings before the one that we want @@ -1127,7 +1127,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { char message[256]; sprintf_s(message, "Element out of range, error accesing element %lld, size=%lld\n", element, bytesRequested); - throw runtime_error(message); + RuntimeError(message); } // make sure we have the buffer in the range to handle the request diff --git a/DataReader/BinaryReader/BinaryReader.cpp b/DataReader/BinaryReader/BinaryReader.cpp index fa486a64d..674e593ae 100644 --- a/DataReader/BinaryReader/BinaryReader.cpp +++ b/DataReader/BinaryReader/BinaryReader.cpp @@ -98,7 +98,7 @@ void BinaryReader::Init(const ConfigParameters& readerConfig) else // otherwise we want to check to make sure it's the same { if (records != m_totalSamples && !(flags&flagAuxilarySection)) - throw runtime_error("multiple files have different record counts, cannot be used together!"); + RuntimeError("multiple files have different record counts, cannot be used together!"); } m_secFiles.push_back(secFile); @@ -187,7 +187,7 @@ void BinaryReader::StartMinibatchLoop(size_t mbSize, size_t epoch, siz { // if they want the dataset size, get the first file, and return the dataset size if (m_totalSamples == 0) - throw runtime_error("no section files contain total samples, can't determine dataset size"); + RuntimeError("no section files contain total samples, can't determine dataset size"); requestedEpochSamples = m_totalSamples; } m_epochSize = requestedEpochSamples; @@ -292,7 +292,7 @@ bool BinaryReader::GetMinibatch(std::map::GetMinibatch(std::map::LabelIdType, typename BinaryRead auto iter = m_sections.find(sectionName); if (iter == m_sections.end()) { - throw runtime_error("GetLabelMapping: requested section name not found\n"); + RuntimeError("GetLabelMapping: requested section name not found\n"); } Section* section = iter->second; if (section->GetSectionType() != sectionTypeLabelMapping) { - throw runtime_error("section specified is not label mapping section.\n"); + RuntimeError("section specified is not label mapping section.\n"); } // get it from the correct section @@ -368,7 +368,7 @@ const std::map::LabelIdType, typename BinaryRead template void BinaryReader::SetLabelMapping(const std::wstring& /*sectionName*/, const std::map::LabelIdType, typename BinaryReader::LabelType>& /*labelMapping*/) { - throw runtime_error("Binary reader does not support setting the mapping table.\n"); + RuntimeError("Binary reader does not support setting the mapping table.\n"); } // GetData - Gets metadata from the specified section (into CPU memory) @@ -385,13 +385,13 @@ bool BinaryReader::GetData(const std::wstring& sectionName, size_t num auto iter = m_sections.find(sectionName); if (iter == m_sections.end()) { - throw runtime_error("GetData: requested section name not found\n"); + RuntimeError("GetData: requested section name not found\n"); } Section* section = iter->second; size_t sizeData = section->GetElementsPerRecord()*section->GetElementSize(); if ((numRecords+recordStart)*section->GetElementsPerRecord() > section->GetElementCount()) { - throw runtime_error("GetData: requested invalid record number\n"); + RuntimeError("GetData: requested invalid record number\n"); } sizeData *= numRecords; // of buffer isn't large enough, or they didn't pass one diff --git a/DataReader/BinaryReader/BinaryWriter.cpp b/DataReader/BinaryReader/BinaryWriter.cpp index e77ec2437..90cc7721e 100644 --- a/DataReader/BinaryReader/BinaryWriter.cpp +++ b/DataReader/BinaryReader/BinaryWriter.cpp @@ -110,7 +110,7 @@ Section* BinaryWriter::CreateSection(const ConfigParameters& config, S if (records == 0) { std::string message = "Required config variable (wrecords) missing from " + config.ConfigPath(); - throw runtime_error(message); + RuntimeError(message); } size_t dim=1; // default dimension (single item) @@ -138,7 +138,7 @@ Section* BinaryWriter::CreateSection(const ConfigParameters& config, S if (foundType == sectionTypeNull) { std::string message = "Invalid type (sectionType) in " + config.ConfigPath(); - throw runtime_error(message); + RuntimeError(message); } sectionType = foundType; } @@ -181,7 +181,7 @@ Section* BinaryWriter::CreateSection(const ConfigParameters& config, S else if (sectionType != sectionTypeNull) { std::string message = "No filename (wfile) defined in " + config.ConfigPath(); - throw runtime_error(message); + RuntimeError(message); } } @@ -255,7 +255,7 @@ Section* BinaryWriter::CreateSection(const ConfigParameters& config, S else { std::string message = "Invalid type (labelType) or missing in " + config.ConfigPath(); - throw runtime_error(message); + RuntimeError(message); } // initialize the section header diff --git a/DataReader/DSSMReader/DSSMReader.cpp b/DataReader/DSSMReader/DSSMReader.cpp index dee6c8ee8..abcbfcc6a 100644 --- a/DataReader/DSSMReader/DSSMReader.cpp +++ b/DataReader/DSSMReader/DSSMReader.cpp @@ -435,7 +435,7 @@ void DSSMReader::SetLabelMapping(const std::wstring& /*sectionName*/, { if (m_cachingReader) { - throw runtime_error("Cannot set mapping table when the caching reader is being used"); + RuntimeError("Cannot set mapping table when the caching reader is being used"); } m_mapIdToLabel = labelMapping; m_mapLabelToId.clear(); @@ -490,7 +490,7 @@ void DSSM_BinaryInput::Init(wstring fileName, size_t dim){ { char message[256]; sprintf_s(message, "Unable to Open/Create file %ls, error %x", fileName.c_str(), GetLastError()); - throw runtime_error(message); + RuntimeError(message); } m_filemap = CreateFileMapping(m_hndl, NULL, PAGE_READONLY, 0, 0, NULL); @@ -674,7 +674,7 @@ bool DSSMReader::GetData(const std::wstring& sectionName, size_t numRe { return m_cachingReader->GetData(sectionName, numRecords, data, dataBufferSize, recordStart); } - throw runtime_error("GetData not supported in DSSMReader"); + RuntimeError("GetData not supported in DSSMReader"); } // instantiate all the combinations we expect to be used diff --git a/DataReader/HTKMLFReader/HTKMLFReader.cpp b/DataReader/HTKMLFReader/HTKMLFReader.cpp index 21dec4e98..f52f9280b 100644 --- a/DataReader/HTKMLFReader/HTKMLFReader.cpp +++ b/DataReader/HTKMLFReader/HTKMLFReader.cpp @@ -296,7 +296,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (cdphonetyingpaths.size() > 0 && statelistpaths.size() > 0 && transPspaths.size() > 0) m_hset.loadfromfile(cdphonetyingpaths[0], statelistpaths[0], transPspaths[0]); if (iFeat!=scriptpaths.size() || iLabel!=mlfpathsmulti.size()) - throw std::runtime_error(msra::strfun::strprintf ("# of inputs files vs. # of inputs or # of output files vs # of outputs inconsistent\n")); + RuntimeError(msra::strfun::strprintf ("# of inputs files vs. # of inputs or # of output files vs # of outputs inconsistent\n")); if (readerConfig.Exists("randomize")) { @@ -357,7 +357,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { numFiles=n; else if (n!=numFiles) - throw std::runtime_error (msra::strfun::strprintf ("number of files in each scriptfile inconsistent (%d vs. %d)", numFiles,n)); + RuntimeError(msra::strfun::strprintf ("number of files in each scriptfile inconsistent (%d vs. %d)", numFiles,n)); /* do "..." expansion if SCP uses relative path names @@ -458,13 +458,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { // verify path exists DWORD attrib = GetFileAttributes(pageFilePath.c_str()); if (attrib==INVALID_FILE_ATTRIBUTES || !(attrib & FILE_ATTRIBUTE_DIRECTORY)) - throw std::runtime_error ("pageFilePath does not exist"); + RuntimeError("pageFilePath does not exist"); #endif #ifdef __unix__ struct stat statbuf; if (stat(pageFilePath.c_str(), &statbuf)==-1) { - throw std::runtime_error ("pageFilePath does not exist"); + RuntimeError("pageFilePath does not exist"); } #endif @@ -483,11 +483,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { #ifdef _WIN32 if (pageFilePath.size()>MAX_PATH-14) // max length of input to GetTempFileName is MAX_PATH-14 - throw std::runtime_error (msra::strfun::strprintf ("pageFilePath must be less than %d characters", MAX_PATH-14)); + RuntimeError(msra::strfun::strprintf ("pageFilePath must be less than %d characters", MAX_PATH-14)); #endif #ifdef __unix__ if (pageFilePath.size()>PATH_MAX-14) // max length of input to GetTempFileName is PATH_MAX-14 - throw std::runtime_error (msra::strfun::strprintf ("pageFilePath must be less than %d characters", PATH_MAX-14)); + RuntimeError(msra::strfun::strprintf ("pageFilePath must be less than %d characters", PATH_MAX-14)); #endif foreach_index(i, infilesmulti) { @@ -613,7 +613,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { numFiles=n; else if (n!=numFiles) - throw std::runtime_error (msra::strfun::strprintf ("HTKMLFReader::InitEvalReader: number of files in each scriptfile inconsistent (%d vs. %d)", numFiles,n)); + RuntimeError(msra::strfun::strprintf ("HTKMLFReader::InitEvalReader: number of files in each scriptfile inconsistent (%d vs. %d)", numFiles,n)); m_inputFilesMultiIO.push_back(filelist); } @@ -1338,14 +1338,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (matrices.find(iter->first)==matrices.end()) { fprintf(stderr,"GetMinibatchToWrite: feature node %ls specified in reader not found in the network\n", iter->first.c_str()); - throw std::runtime_error("GetMinibatchToWrite: feature node specified in reader not found in the network."); + RuntimeError("GetMinibatchToWrite: feature node specified in reader not found in the network."); } } /* for (auto iter=matrices.begin();iter!=matrices.end();iter++) { if (m_featureNameToIdMap.find(iter->first)==m_featureNameToIdMap.end()) - throw std::runtime_error(msra::strfun::strprintf("minibatch requested for input node %ws not found in reader - cannot generate input\n",iter->first.c_str())); + RuntimeError(msra::strfun::strprintf("minibatch requested for input node %ws not found in reader - cannot generate input\n",iter->first.c_str())); } */ m_checkDictionaryKeys=false; @@ -1502,7 +1502,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (m_toProcess[i] != actualmbsizeOri) { - throw std::runtime_error("The multi-IO features has inconsistent number of frames!"); + RuntimeError("The multi-IO features has inconsistent number of frames!"); } } assert (actualmbsizeOri == m_mbiter->currentmbframes()); @@ -1603,7 +1603,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { size_t HTKMLFReader::ReadLabelToTargetMappingFile (const std::wstring& labelToTargetMappingFile, const std::wstring& labelListFile, std::vector>& labelToTargetMap) { if (labelListFile==L"") - throw std::runtime_error("HTKMLFReader::ReadLabelToTargetMappingFile(): cannot read labelToTargetMappingFile without a labelMappingFile!"); + RuntimeError("HTKMLFReader::ReadLabelToTargetMappingFile(): cannot read labelToTargetMappingFile without a labelMappingFile!"); vector labelList; size_t count, numLabels; @@ -1665,7 +1665,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { template bool HTKMLFReader::GetData(const std::wstring& /*sectionName*/, size_t /*numRecords*/, void* /*data*/, size_t& /*dataBufferSize*/, size_t /*recordStart*/) { - throw std::runtime_error("GetData not supported in HTKMLFReader"); + RuntimeError("GetData not supported in HTKMLFReader"); } @@ -1682,7 +1682,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { case endDataNull: case endDataEpoch: case endDataSet: - throw std::logic_error("DataEnd: does not support endDataTypes: endDataNull, endDataEpoch and endDataSet"); + LogicError("DataEnd: does not support endDataTypes: endDataNull, endDataEpoch and endDataSet"); break; case endDataSentence: if (m_truncated) diff --git a/DataReader/HTKMLFReader/HTKMLFWriter.cpp b/DataReader/HTKMLFReader/HTKMLFWriter.cpp index 5b118aba8..755276bd6 100644 --- a/DataReader/HTKMLFReader/HTKMLFWriter.cpp +++ b/DataReader/HTKMLFReader/HTKMLFWriter.cpp @@ -70,7 +70,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error ("HTKMLFWriter::Init: output type for writer output expected to be Real"); + RuntimeError("HTKMLFWriter::Init: output type for writer output expected to be Real"); } } @@ -93,7 +93,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { numFiles=n; else if (n!=numFiles) - throw std::runtime_error (msra::strfun::strprintf ("HTKMLFWriter:Init: number of files in each scriptfile inconsistent (%d vs. %d)", numFiles,n)); + RuntimeError(msra::strfun::strprintf ("HTKMLFWriter:Init: number of files in each scriptfile inconsistent (%d vs. %d)", numFiles,n)); outputFiles.push_back(filelist); } diff --git a/DataReader/HTKMLFReader/biggrowablevectors.h b/DataReader/HTKMLFReader/biggrowablevectors.h index 90b9d1977..3bf08dcbf 100644 --- a/DataReader/HTKMLFReader/biggrowablevectors.h +++ b/DataReader/HTKMLFReader/biggrowablevectors.h @@ -25,7 +25,7 @@ protected: // fix this later size_t n; // number of elements std::vector> blocks; // the data blocks void operator= (const growablevectorbase &); // (non-assignable) - void check (size_t t) const { if (t >= n) throw std::logic_error ("growablevectorbase: out of bounds"); } // bounds check helper + void check (size_t t) const { if (t >= n) LogicError("growablevectorbase: out of bounds"); } // bounds check helper // resize intermediate level, but do not allocate blocks // (may deallocate if shrinking) @@ -66,7 +66,7 @@ protected: // fix this later { // BUGBUG: last block may be shorter than elementsperblock if (end - begin != elementsperblock || getblockt (begin) != 0) - throw std::logic_error ("growablevectorbase: non-block boundaries passed to block-level function"); + LogicError("growablevectorbase: non-block boundaries passed to block-level function"); return getblockptr (begin); } public: diff --git a/DataReader/HTKMLFReader/chunkevalsource.h b/DataReader/HTKMLFReader/chunkevalsource.h index 612aaafd4..06d3380d0 100644 --- a/DataReader/HTKMLFReader/chunkevalsource.h +++ b/DataReader/HTKMLFReader/chunkevalsource.h @@ -93,7 +93,7 @@ namespace msra { namespace dbn { { // append to frames; also expand neighbor frames if (feat.cols() < 2) - throw std::runtime_error ("evaltofile: utterances < 2 frames not supported"); + RuntimeError("evaltofile: utterances < 2 frames not supported"); foreach_column (t, feat) { std::vector v (&feat(0,t), &feat(0,t) + feat.rows()); @@ -220,7 +220,7 @@ namespace msra { namespace dbn { { // append to frames; also expand neighbor frames if (feat.cols() < 2) - throw std::runtime_error ("evaltofile: utterances < 2 frames not supported"); + RuntimeError("evaltofile: utterances < 2 frames not supported"); foreach_column (t, feat) { std::vector v (&feat(0,t), &feat(0,t) + feat.rows()); @@ -318,7 +318,7 @@ namespace msra { namespace dbn { { // append to frames; also expand neighbor frames if (feat.cols() < 2) - throw std::runtime_error ("evaltofile: utterances < 2 frames not supported"); + RuntimeError("evaltofile: utterances < 2 frames not supported"); foreach_column (t, feat) { std::vector v (&feat(0,t), &feat(0,t) + feat.rows()); diff --git a/DataReader/HTKMLFReader/fileutil.cpp b/DataReader/HTKMLFReader/fileutil.cpp index 288cf837f..644e86ebd 100644 --- a/DataReader/HTKMLFReader/fileutil.cpp +++ b/DataReader/HTKMLFReader/fileutil.cpp @@ -34,7 +34,6 @@ #include using namespace std; -using Microsoft::MSR::CNTK::RuntimeError; // ---------------------------------------------------------------------------- // fopenOrDie(): like fopen() but terminate with err msg in case of error. @@ -1659,7 +1658,7 @@ static BOOL ExpandWildcards (wstring path, vector & paths) return FALSE; // another error } size_t pos = path.find_last_of (L"\\"); - if (pos == wstring::npos) throw std::logic_error ("unexpected missing \\ in path"); + if (pos == wstring::npos) LogicError("unexpected missing \\ in path"); wstring parent = path.substr (0, pos); do { diff --git a/DataReader/HTKMLFReader/fileutil.h b/DataReader/HTKMLFReader/fileutil.h index af12433fb..77c28173d 100644 --- a/DataReader/HTKMLFReader/fileutil.h +++ b/DataReader/HTKMLFReader/fileutil.h @@ -471,9 +471,9 @@ void fgetText(FILE * f, T& v) { int rc = ftrygetText(f, v); if (rc == 0) - throw std::runtime_error("error reading value from file (invalid format)"); + RuntimeError("error reading value from file (invalid format)"); else if (rc == EOF) - throw std::runtime_error(std::string("error reading from file: ") + strerror(errno)); + RuntimeError(std::string("error reading from file: ") + strerror(errno)); assert(rc == 1); } @@ -504,9 +504,9 @@ void fputText(FILE * f, T v) const wchar_t* formatString = GetFormatString(v); int rc = fwprintf(f, formatString, v); if (rc == 0) - throw std::runtime_error("error writing value to file, no values written"); + RuntimeError("error writing value to file, no values written"); else if (rc < 0) - throw std::runtime_error(std::string("error writing to file: ") + strerror(errno)); + RuntimeError(std::string("error writing to file: ") + strerror(errno)); } // ---------------------------------------------------------------------------- diff --git a/DataReader/HTKMLFReader/htkfeatio.h b/DataReader/HTKMLFReader/htkfeatio.h index 59526671d..5c347af1f 100644 --- a/DataReader/HTKMLFReader/htkfeatio.h +++ b/DataReader/HTKMLFReader/htkfeatio.h @@ -54,7 +54,7 @@ protected: else // set already: check if consistent { if (featkind != kind || featdim != dim || featperiod != period) - throw std::runtime_error (msra::strfun::strprintf ("setkind: inconsistent feature kind for file '%S'", path.c_str())); + RuntimeError(msra::strfun::strprintf ("setkind: inconsistent feature kind for file '%S'", path.c_str())); } } @@ -88,7 +88,7 @@ protected: { int magic = swapint(fgetint (f)); if (magic != 2051) - throw std::runtime_error ("reading idx feature cache header: invalid magic"); + RuntimeError("reading idx feature cache header: invalid magic"); nsamples = swapint(fgetint(f)); sampperiod = 0; sampkind = (short)9; //user type @@ -145,7 +145,7 @@ public: { vector params = msra::strfun::split (str, ";"); if (params.empty()) - throw std::runtime_error ("parsekind: invalid param kind string"); + RuntimeError("parsekind: invalid param kind string"); vector parts = msra::strfun::split (params[0], "_"); // map base kind short sampkind; @@ -154,13 +154,13 @@ public: else if (basekind == "MFCC") sampkind = MFCC; else if (basekind == "FBANK") sampkind = FBANK; else if (basekind == "USER") sampkind = USER; - else throw std::runtime_error ("parsekind: unsupported param base kind"); + else RuntimeError("parsekind: unsupported param base kind"); // map qualifiers for (size_t i = 1; i < parts.size(); i++) { string opt = parts[i]; if (opt.length() != 1) - throw std::runtime_error ("parsekind: invalid param kind string"); + RuntimeError("parsekind: invalid param kind string"); switch (opt[0]) { case 'E': sampkind |= HASENERGY; break; @@ -170,7 +170,7 @@ public: case 'T': sampkind |= HASTHIRD; break; case 'Z': sampkind |= HASZEROM; break; case '0': sampkind |= HASZEROC; break; - default: throw std::runtime_error ("parsekind: invalid qualifier in param kind string"); + default: RuntimeError("parsekind: invalid qualifier in param kind string"); } } return sampkind; @@ -197,7 +197,7 @@ public: void write (const vector & v) { if (v.size() != featdim) - throw std::logic_error ("htkfeatwriter: inconsistent feature dimension"); + LogicError("htkfeatwriter: inconsistent feature dimension"); if (needbyteswapping) { tmp.resize (v.size()); @@ -216,7 +216,7 @@ public: void close (size_t numframes) { if (curframe != numframes) - throw std::logic_error ("htkfeatwriter: inconsistent number of frames passed to close()"); + LogicError("htkfeatwriter: inconsistent number of frames passed to close()"); fflushOrDie (f); // now implant the length field; it's at offset 0 int nSamplesFile = (int) numframes; @@ -318,7 +318,7 @@ public: wstring logicalpath; // virtual path that this file should be understood to belong to wstring archivepath; // physical path of archive file size_t s, e; // first and last frame inside the archive file; (0, INT_MAX) if not given - void malformed() const { throw std::runtime_error (msra::strfun::strprintf ("parsedpath: malformed path '%S'", xpath.c_str())); } + void malformed() const { RuntimeError(msra::strfun::strprintf ("parsedpath: malformed path '%S'", xpath.c_str())); } // consume and return up to 'delim'; remove from 'input' (we try to avoid C++0x here for VS 2008 compat) wstring consume (wstring & input, const wchar_t * delim) @@ -378,7 +378,7 @@ public: size_t numframes() const { if (!isarchive) - throw runtime_error ("parsedpath: this mode requires an input script with start and end frames given"); + RuntimeError("parsedpath: this mode requires an input script with start and end frames given"); return e - s + 1; } }; @@ -416,7 +416,7 @@ private: case FBANK: kind = "FBANK"; break; case USER: kind = "USER"; break; case FESTREAM: kind = "USER"; break; // we return this as USER type (with guid) - default: throw std::runtime_error ("htkfeatreader:unsupported feature kind"); + default: RuntimeError("htkfeatreader:unsupported feature kind"); } // add qualifiers if (H.sampkind & HASENERGY) kind += "_E"; @@ -428,7 +428,7 @@ private: bool hascrcc = (H.sampkind & HASCRCC) != 0; if (H.sampkind & HASZEROM) kind += "_Z"; if (H.sampkind & HASZEROC) kind += "_0"; - if (H.sampkind & HASVQ) throw std::runtime_error ("htkfeatreader:we do not support VQ"); + if (H.sampkind & HASVQ) RuntimeError("htkfeatreader:we do not support VQ"); // skip additional GUID in FESTREAM features if (H.sampkind == FESTREAM) { // ... note: untested @@ -442,7 +442,7 @@ private: // other checks size_t bytesPerValue = isidxformat ? 1 : (compressed ? sizeof (short) : sizeof (float)); - if (H.sampsize % bytesPerValue != 0) throw std::runtime_error ("htkfeatreader:sample size not multiple of dimension"); + if (H.sampsize % bytesPerValue != 0) RuntimeError("htkfeatreader:sample size not multiple of dimension"); size_t dim = H.sampsize / bytesPerValue; // read the values for decompressing @@ -495,9 +495,9 @@ public: if (ppath.isarchive) // reading a sub-range from an archive { if (ppath.s > ppath.e) - throw std::runtime_error (msra::strfun::strprintf ("open: start frame > end frame in '%S'", ppath.e, physicalframes, ppath.xpath.c_str())); + RuntimeError(msra::strfun::strprintf ("open: start frame > end frame in '%S'", ppath.e, physicalframes, ppath.xpath.c_str())); if (ppath.e >= physicalframes) - throw std::runtime_error (msra::strfun::strprintf ("open: end frame exceeds archive's total number of frames %d in '%S'", physicalframes, ppath.xpath.c_str())); + RuntimeError(msra::strfun::strprintf ("open: end frame exceeds archive's total number of frames %d in '%S'", physicalframes, ppath.xpath.c_str())); int64_t dataoffset = physicaldatastart + ppath.s * vecbytesize; fsetpos (f, dataoffset); // we assume fsetpos(), which is our own, is smart to not flush the read buffer @@ -533,7 +533,7 @@ public: // read a vector from the open file void read (std::vector & v) { - if (curframe >= numframes) throw std::runtime_error ("htkfeatreader:attempted to read beyond end"); + if (curframe >= numframes) RuntimeError("htkfeatreader:attempted to read beyond end"); if (!compressed && !isidxformat) // not compressed--the easy one { freadOrDie (v, featdim, f); @@ -590,9 +590,9 @@ public: // open the file and check dimensions size_t numframes = open (ppath); if (feat.cols() != numframes || feat.rows() != featdim) - throw std::logic_error ("read: stripe read called with wrong dimensions"); + LogicError("read: stripe read called with wrong dimensions"); if (kindstr != featkind || period != featperiod) - throw std::logic_error ("read: attempting to mixing different feature kinds"); + LogicError("read: attempting to mixing different feature kinds"); // read vectors from file and push to our target structure try { read (feat, 0, numframes); } catch (...) { close(); throw; } @@ -620,20 +620,20 @@ struct htkmlfentry unsigned int numframes; //unsigned short classid; // numeric state id unsigned int classid; // numeric state id - mseltzer changed from ushort to uint for untied cd phones > 2^16 - unsigned int phonestart; // numeric phone start time + unsigned int phonestart; // numeric phone start time private: // verify and save data void setdata (size_t ts, size_t te, size_t uid) { - if (te < ts) throw std::runtime_error ("htkmlfentry: end time below start time??"); + if (te < ts) RuntimeError("htkmlfentry: end time below start time??"); // save firstframe = (unsigned int) ts; numframes = (unsigned int) (te - ts); classid = (unsigned int) uid; // check for numeric overflow if (firstframe != ts || firstframe + numframes != te || classid != uid) - throw std::runtime_error ("htkmlfentry: not enough bits for one of the values"); + RuntimeError("htkmlfentry: not enough bits for one of the values"); } // parse the time range @@ -662,28 +662,28 @@ public: // parse format with original HTK state align MLF format and state list void parsewithstatelist (const vector & toks, const unordered_map & statelisthash, const double htkTimeToFrame, - std::unordered_map & hmmnamehash) + std::unordered_map & hmmnamehash) { size_t ts, te; parseframerange (toks, ts, te, htkTimeToFrame); auto iter = statelisthash.find (toks[2]); if (iter == statelisthash.end()) - throw std::runtime_error (msra::strfun::strprintf ("htkmlfentry: state %s not found in statelist", toks[2])); + RuntimeError(msra::strfun::strprintf ("htkmlfentry: state %s not found in statelist", toks[2])); const size_t uid = iter->second; // get state index setdata (ts, te, uid); - //phone boundary - if (hmmnamehash.size() > 0) - { - if (toks.size() > 4) - { - auto hmmiter = hmmnamehash.find(toks[4]); - if (hmmiter == hmmnamehash.end()) - throw std::runtime_error(msra::strfun::strprintf("htkmlfentry: hmm %s not found in hmmlist", toks[4])); - phonestart = (unsigned short)(hmmiter->second + 1); - } - else - phonestart = 0; - } + //phone boundary + if (hmmnamehash.size() > 0) + { + if (toks.size() > 4) + { + auto hmmiter = hmmnamehash.find(toks[4]); + if (hmmiter == hmmnamehash.end()) + RuntimeError(msra::strfun::strprintf("htkmlfentry: hmm %s not found in hmmlist", toks[4])); + phonestart = (unsigned short)(hmmiter->second + 1); + } + else + phonestart = 0; + } } @@ -691,7 +691,7 @@ public: // add support so that it can handle conditions where time instead of frame numer is used. void parse (const vector & toks, const double htkTimeToFrame) { - if (toks.size() != 4) throw std::runtime_error ("htkmlfentry: currently we only support 4-column format"); + if (toks.size() != 4) RuntimeError("htkmlfentry: currently we only support 4-column format"); size_t ts, te; parseframerange (toks, ts, te, htkTimeToFrame); size_t uid = msra::strfun::toint (toks[3]); @@ -705,7 +705,7 @@ class htkmlfreader : public map> // [key][i] the data wstring curpath; // for error messages unordered_map statelistmap; // for state <=> index map wordsequences; // [key] word sequences (if we are building word entries as well, for MMI) - std::unordered_map symmap; + std::unordered_map symmap; void strtok (char * s, const char * delim, vector & toks) { @@ -716,7 +716,7 @@ class htkmlfreader : public map> // [key][i] the data } void malformed (string what) { - throw std::runtime_error (msra::strfun::strprintf ("htkmlfreader: %s in '%S'", what.c_str(), curpath.c_str())); + RuntimeError(msra::strfun::strprintf ("htkmlfreader: %s in '%S'", what.c_str(), curpath.c_str())); } vector readlines (const wstring & path, vector & buffer) @@ -821,12 +821,12 @@ class htkmlfreader : public map> // [key][i] the data const char * u = toks[4]; // the triphone name auto iter = unitmap->find (u); // map to unit id if (iter == unitmap->end()) - throw std::runtime_error (string ("parseentry: unknown unit ") + u + " in utterance " + strfun::utf8 (key)); + RuntimeError(string ("parseentry: unknown unit ") + u + " in utterance " + strfun::utf8 (key)); const size_t uid = iter->second; alignseqbuffer.push_back (typename WORDSEQUENCE::aligninfo (uid, 0/*#frames--we accumulate*/)); } if (alignseqbuffer.empty()) - throw std::runtime_error ("parseentry: lonely senone entry at start without phone/word entry found, for utterance " + strfun::utf8 (key)); + RuntimeError("parseentry: lonely senone entry at start without phone/word entry found, for utterance " + strfun::utf8 (key)); alignseqbuffer.back().frames += entries[i-s].numframes; // (we do not have an overflow check here, but should...) } } @@ -834,7 +834,7 @@ class htkmlfreader : public map> // [key][i] the data if (wordmap) // if reading word sequences as well (for MMI), then record it (in a separate map) { if (!entries.empty() && wordseqbuffer.empty()) - throw std::runtime_error ("parseentry: got state alignment but no word-level info, although being requested, for utterance " + strfun::utf8 (key)); + RuntimeError("parseentry: got state alignment but no word-level info, although being requested, for utterance " + strfun::utf8 (key)); // post-process silence // - first !silence -> !sent_start // - last !silence -> !sent_end @@ -850,7 +850,7 @@ class htkmlfreader : public map> // [key][i] the data wordseqbuffer.back().wordindex = sentend; } //if (sentstart < 0 || sentend < 0 || silence < 0) - // throw std::logic_error ("parseentry: word map must contain !silence, !sent_start, and !sent_end"); + // LogicError("parseentry: word map must contain !silence, !sent_start, and !sent_end"); // implant auto & wordsequence = wordsequences[key]; // this creates the map entry wordsequence.words = wordseqbuffer; // makes a copy @@ -875,7 +875,7 @@ public: return issilstatetable[id]; } - struct nullmap { int operator[] (const char * s) const { throw std::logic_error ("nullmap: should never be used"); } }; // to satisfy a template, never used... :( + struct nullmap { int operator[] (const char * s) const { LogicError("nullmap: should never be used"); } }; // to satisfy a template, never used... :( // constructor reads multiple MLF files htkmlfreader (const vector & paths, const set & restricttokeys, const wstring & stateListPath = L"", const double htkTimeToFrame = 100000.0) @@ -903,17 +903,17 @@ public: read (paths[i], restricttokeys, wordmap, unitmap, htkTimeToFrame); } - //phone boundary - template - htkmlfreader(const vector & paths, const set & restricttokeys, const wstring & stateListPath, const WORDSYMBOLTABLE * wordmap, const UNITSYMBOLTABLE * unitmap, - const double htkTimeToFrame, const msra::asr::simplesenonehmm & hset) - { - if (stateListPath != L"") - readstatelist(stateListPath); - symmap = hset.symmap; - foreach_index(i, paths) - read(paths[i], restricttokeys, wordmap, unitmap, htkTimeToFrame); - } + //phone boundary + template + htkmlfreader(const vector & paths, const set & restricttokeys, const wstring & stateListPath, const WORDSYMBOLTABLE * wordmap, const UNITSYMBOLTABLE * unitmap, + const double htkTimeToFrame, const msra::asr::simplesenonehmm & hset) + { + if (stateListPath != L"") + readstatelist(stateListPath); + symmap = hset.symmap; + foreach_index(i, paths) + read(paths[i], restricttokeys, wordmap, unitmap, htkTimeToFrame); + } // note: this function is not designed to be pretty but to be fast template @@ -956,9 +956,9 @@ public: issilstatetable.push_back (issilstate (lines[index])); } if (index != statelistmap.size()) - throw std::runtime_error (msra::strfun::strprintf ("readstatelist: lines (%d) not equal to statelistmap size (%d)", index, statelistmap.size())); + RuntimeError(msra::strfun::strprintf ("readstatelist: lines (%d) not equal to statelistmap size (%d)", index, statelistmap.size())); if (statelistmap.size() != issilstatetable.size()) - throw std::runtime_error (msra::strfun::strprintf ("readstatelist: size of statelookuparray (%d) not equal to statelistmap size (%d)", issilstatetable.size(), statelistmap.size())); + RuntimeError(msra::strfun::strprintf ("readstatelist: size of statelookuparray (%d) not equal to statelistmap size (%d)", issilstatetable.size(), statelistmap.size())); fprintf (stderr, "total %lu state names in state list %S\n", statelistmap.size(), stateListPath.c_str()); } } diff --git a/DataReader/HTKMLFReader/latticearchive.cpp b/DataReader/HTKMLFReader/latticearchive.cpp index 7484a3a4c..27919eccf 100644 --- a/DataReader/HTKMLFReader/latticearchive.cpp +++ b/DataReader/HTKMLFReader/latticearchive.cpp @@ -52,7 +52,7 @@ static void writeunitmap (const wstring & symlistpath, const UNITMAP & unitmap) foreach_index (k, units) { if (units[k].empty()) - throw std::logic_error ("build: unitmap has gaps"); + LogicError("build: unitmap has gaps"); fprintfOrDie (flist, "%s\n", units[k].c_str()); } // write log-phys mappings @@ -117,7 +117,7 @@ static size_t tryfind (const MAPTYPE & map, const KEYTYPE & key, VALTYPE deflt) key = regex_replace (key, wregex (L".*[\\\\/]"), wstring()); // delete path key = regex_replace (key, wregex (L"\\.[^\\.\\\\/:]*$"), wstring()); // delete extension (or not if none) if (!seenkeys.insert (key).second) - throw std::runtime_error (msra::strfun::strprintf ("build: duplicate key for lattice '%S'", inlatpath.c_str())); + RuntimeError(msra::strfun::strprintf ("build: duplicate key for lattice '%S'", inlatpath.c_str())); // we fail all the time due to totally broken HDecode/copy process, OK if not too many files are missing bool latticeread = false; @@ -185,13 +185,13 @@ vector lattice::determinenodecontexts (const msra::asr::si const size_t E = e.E; auto a = getaligninfo (j); if (a.size() == 0) // !NULL edge - throw std::logic_error ("determinenodecontexts: !NULL edges not allowed in merging, should be removed before"); + LogicError("determinenodecontexts: !NULL edges not allowed in merging, should be removed before"); size_t A = a[0].unit; size_t Z = a[a.size()-1].unit; if (Z == spunit) { if (a.size() < 2) - throw std::runtime_error ("determinenodecontexts: context-free unit (/sp/) found as a single-phone word"); + RuntimeError("determinenodecontexts: context-free unit (/sp/) found as a single-phone word"); else { Z = a[a.size()-2].unit; @@ -204,7 +204,7 @@ vector lattice::determinenodecontexts (const msra::asr::si break; // ends with n = position of furthest non-sp if (n < 0) // only sp? - throw std::runtime_error ("determinenodecontexts: word consists only of /sp/"); + RuntimeError("determinenodecontexts: word consists only of /sp/"); fprintf (stderr, "determinenodecontexts: word with %lu /sp/ at the end found, edge %d\n", a.size() -1 - n, j); multispseen++; Z = a[n].unit; @@ -220,7 +220,7 @@ vector lattice::determinenodecontexts (const msra::asr::si fprintf (stderr, "a[%d] = %d\n", kk, a[kk].unit); dump (stderr, [&] (size_t i) { return hset.gethmm (i).getname(); }); #endif - throw std::runtime_error ("determinenodecontexts: context-free unit (/sp/) found as a start phone or second last phone"); + RuntimeError("determinenodecontexts: context-free unit (/sp/) found as a start phone or second last phone"); } const auto & Ahmm = hset.gethmm (A); const auto & Zhmm = hset.gethmm (Z); @@ -239,11 +239,11 @@ vector lattice::determinenodecontexts (const msra::asr::si { auto & nc = nodecontexts[i]; if ((nc.left == nodecontext::unknown) ^ (nc.right == nodecontext::unknown)) - throw std::runtime_error ("determinenodecontexts: invalid dead-end node in lattice"); + RuntimeError("determinenodecontexts: invalid dead-end node in lattice"); if (nc.left == nodecontext::ambiguous && nc.right != silid && nc.right != nodecontext::end) - throw std::runtime_error ("determinenodecontexts: invalid ambiguous left context (right context is not CI)"); + RuntimeError("determinenodecontexts: invalid ambiguous left context (right context is not CI)"); if (nc.right == nodecontext::ambiguous && nc.left != silid && nc.left != nodecontext::start) - throw std::runtime_error ("determinenodecontexts: invalid ambiguous right context (left context is not CI)"); + RuntimeError("determinenodecontexts: invalid ambiguous right context (left context is not CI)"); nc.t = nodes[i].t; } return nodecontexts; // (will this use a move constructor??) @@ -276,12 +276,12 @@ void lattice::removefinalnull() if (lastedge.firstalign < align.size()) // has alignment records --not !NULL return; if (lastedge.S != nodes.size() -2 || lastedge.E != nodes.size() -1) - throw std::runtime_error ("removefinalnull: malformed final !NULL edge"); + RuntimeError("removefinalnull: malformed final !NULL edge"); edges.resize (edges.size() -1); // remove it nodes.resize (nodes.size() -1); // its start node is now the new end node foreach_index (j, edges) if (edges[j].E >= nodes.size()) - throw std::runtime_error ("removefinalnull: cannot have final !NULL edge and other edges connecting to end node at the same time"); + RuntimeError("removefinalnull: cannot have final !NULL edge and other edges connecting to end node at the same time"); } // merge a secondary lattice into the first @@ -293,9 +293,9 @@ void lattice::removefinalnull() void lattice::merge (const lattice & other, const msra::asr::simplesenonehmm & hset) { if (!edges2.empty() || !other.edges2.empty()) - throw std::logic_error ("merge: lattice(s) must be in non-uniq'ed format (V1)"); + LogicError("merge: lattice(s) must be in non-uniq'ed format (V1)"); if (!info.numframes || !other.info.numframes) - throw std::logic_error ("merge: lattice(s) must have identical number of frames"); + LogicError("merge: lattice(s) must have identical number of frames"); // establish node contexts auto contexts = determinenodecontexts (hset); @@ -368,7 +368,7 @@ void lattice::merge (const lattice & other, const msra::asr::simplesenonehmm & h void lattice::dedup() { if (edges2.empty()) - throw std::logic_error ("dedup: lattice must be in uniq'ed format (V2)"); + LogicError("dedup: lattice must be in uniq'ed format (V2)"); size_t k = 0; foreach_index (j, edges2) @@ -376,7 +376,7 @@ void lattice::dedup() if (k > 0 && edges2[k-1].S == edges2[j].S && edges2[k-1].E == edges2[j].E && edges2[k-1].firstalign == edges2[j].firstalign) { if (edges2[k-1].implysp != edges2[j].implysp) - throw std::logic_error ("dedup: inconsistent 'implysp' flag for otherwise identical edges"); + LogicError("dedup: inconsistent 'implysp' flag for otherwise identical edges"); continue; } edges2[k++] = edges2[j]; @@ -447,7 +447,7 @@ void lattice::dedup() const char * line = toclines[i]; const char * p = strchr (line, '='); if (p == NULL) - throw std::runtime_error ("open: invalid TOC line (no = sign): " + std::string (line)); + RuntimeError("open: invalid TOC line (no = sign): " + std::string (line)); const std::wstring key = msra::strfun::utf16 (std::string (line, p - line)); fprintf (stderr, "convert: processing lattice '%S'\n", key.c_str()); @@ -531,7 +531,7 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_map textbuffer; auto lines = msra::files::fgetfilelines (path, textbuffer); if (lines.empty()) - throw std::runtime_error ("lattice: mal-formed lattice--empty input file (or all-zeroes)"); + RuntimeError("lattice: mal-formed lattice--empty input file (or all-zeroes)"); auto iter = lines.begin(); // parse out LMF and WP char dummychar = 0; // dummy for sscanf() end checking @@ -539,7 +539,7 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_map 0); nodes.reserve (info.numnodes); @@ -561,13 +561,13 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_mapsecond; //const size_t unitid = unitmap.insert (make_pair (label, unitmap.size())).first->second; // may create a new entry with index = #entries align.push_back (aligninfo (unitid, frames)); @@ -630,11 +630,11 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_mapsecond; if (transcript.words.size() == 0) - throw std::runtime_error ("frommlf: empty reference word sequence for lattice with key " + strfun::utf8 (key)); + RuntimeError("frommlf: empty reference word sequence for lattice with key " + strfun::utf8 (key)); // determine unigram scores for all words vector lmscores (transcript.words.size()); @@ -681,7 +681,7 @@ void lattice::frommlf (const wstring & key, const std::unordered_map for score lookup } const int iwid = (int) wid; @@ -711,7 +711,7 @@ void lattice::frommlf (const wstring & key, const std::unordered_mapgetnumframes(); if (totalframes != actualmbframes) - throw std::logic_error ("fillorclear: frames in lattices do not match minibatch size"); + LogicError("fillorclear: frames in lattices do not match minibatch size"); } timechecklattice = timerchecklattice; } bool hasdata() const { return mbstartframe < epochendframe; } // true if we can access and/or advance - void checkhasdata() const { if (!hasdata()) throw std::logic_error ("minibatchiterator: access beyond end of epoch"); } + void checkhasdata() const { if (!hasdata()) LogicError("minibatchiterator: access beyond end of epoch"); } public: // interface: for (minibatchiterator i (...), i, i++) { ... } minibatchiterator (msra::dbn::minibatchsource & source, size_t epoch, size_t epochframes, size_t requestedmbframes, size_t subsetnum, size_t numsubsets, size_t datapasses) diff --git a/DataReader/HTKMLFReader/minibatchsourcehelpers.h b/DataReader/HTKMLFReader/minibatchsourcehelpers.h index 26ccd699c..bb091d2fa 100644 --- a/DataReader/HTKMLFReader/minibatchsourcehelpers.h +++ b/DataReader/HTKMLFReader/minibatchsourcehelpers.h @@ -39,9 +39,9 @@ static size_t augmentationextent (size_t featdim/*augment from*/, size_t modeldi const size_t extent = windowframes / 2; // extend each side by this if (modeldim % featdim != 0) - throw runtime_error ("augmentationextent: model vector size not multiple of input features"); + RuntimeError("augmentationextent: model vector size not multiple of input features"); if (windowframes % 2 == 0) - throw runtime_error (msra::strfun::strprintf ("augmentationextent: neighbor expansion of input features to %d not symmetrical", windowframes)); + RuntimeError(msra::strfun::strprintf ("augmentationextent: neighbor expansion of input features to %d not symmetrical", windowframes)); return extent; } @@ -213,7 +213,7 @@ public: { // test for numeric overflow if (map.size()-1 != (INDEXTYPE) (map.size()-1)) - throw std::runtime_error ("randomordering: INDEXTYPE has too few bits for this corpus"); + RuntimeError("randomordering: INDEXTYPE has too few bits for this corpus"); // 0, 1, 2... foreach_index (t, map) map[t] = (INDEXTYPE) t; // now randomize them @@ -221,7 +221,7 @@ public: { #if 1 // change to 0 to disable randomizing if (map.size() > RAND_MAX * (size_t) RAND_MAX) - throw std::runtime_error ("randomordering: too large training set: need to change to different random generator!"); + RuntimeError("randomordering: too large training set: need to change to different random generator!"); srand ((unsigned int) seed); size_t retries = 0; foreach_index (t, map) @@ -255,7 +255,7 @@ public: foreach_index (t, map) if (!((size_t) t <= map[t] + randomizationrange/2 && map[t] < (size_t) t + randomizationrange/2)) { fprintf (stderr, "randomordering: windowing condition violated %d -> %d\n", t, map[t]); - throw std::logic_error ("randomordering: windowing condition violated"); + LogicError("randomordering: windowing condition violated"); } #endif #endif diff --git a/DataReader/HTKMLFReader/msra_mgram.h b/DataReader/HTKMLFReader/msra_mgram.h index 7ea3f8f30..546e985a6 100644 --- a/DataReader/HTKMLFReader/msra_mgram.h +++ b/DataReader/HTKMLFReader/msra_mgram.h @@ -17,7 +17,6 @@ #include namespace msra { namespace lm { - using Microsoft::MSR::CNTK::RuntimeError; // =========================================================================== // core LM interface -- LM scores are accessed through this exclusively @@ -131,11 +130,8 @@ public: // create const char * p = _strdup (key); if (!p) -#ifdef _WIN32 - throw std::bad_exception ("CSymbolSet:id string allocation failure"); -#else - throw std::bad_exception (); -#endif + BadExceptionError("CSymbolSet:id string allocation failure"); + try { int id = (int) symbols.size(); @@ -241,7 +237,7 @@ public: typedef uint24_ref_t const_uint24_ref; // const version (only read) class uint24_ref : public uint24_ref_t // non-const (read and assign) { - static void overflow() { throw runtime_error ("uint32_ref: attempting to store value > 24 bits"); } + static void overflow() { RuntimeError("uint32_ref: attempting to store value > 24 bits"); } protected: friend class int24_vector; // only int24_vector may instantiate this __forceinline uint24_ref (unsigned char * p) : uint24_ref_t (p) {} @@ -288,7 +284,7 @@ class mgram_map std::vector ids; // [M+1][i] ([0] = not used) bool level1nonsparse; // true: level[1] can be directly looked up std::vector level1lookup; // id->index for unigram level - static void fail (const char * msg) { throw runtime_error (string ("mgram_map::") + msg); } + static void fail (const char * msg) { RuntimeError(string ("mgram_map::") + msg); } // mapping from w -> i -- users pass 'w', internally we use our own 'ids' std::vector w2id; // w -> id @@ -825,7 +821,7 @@ public: template class mgram_data { std::vector> data; - static void fail (const char * msg) { throw runtime_error (string ("mgram_data::") + msg); } + static void fail (const char * msg) { RuntimeError(string ("mgram_data::") + msg); } public: mgram_data(){} mgram_data (int M) { init (M); } @@ -1014,7 +1010,7 @@ public: { if (M > this->M) M = this->M; // clip; also covers default value if (M < 1 || map.size (1) == 0) - throw runtime_error ("write: attempting to write empty model"); + RuntimeError("write: attempting to write empty model"); // output header // \data\ @@ -1510,7 +1506,7 @@ protected: const mgram_map::key boKey = key.pop_h(); const mgram_map::foundcoord c = map[boKey]; if (!c.valid_w()) - throw runtime_error ("estimate: malformed data: back-off value not found"); // must exist + RuntimeError("estimate: malformed data: back-off value not found"); // must exist // look it up float Pc = P[c]; backoffPSum[j] += islog ? exp (Pc) : Pc; @@ -1605,7 +1601,7 @@ public: { msra::lm::mgram_map::foundcoord c = lm.map[msra::lm::mgram_map::key (mgram, m)]; if (!c.valid_w()) - throw std::logic_error ("locate: attempting to locate a non-existing history"); + LogicError("locate: attempting to locate a non-existing history"); return c; } }; @@ -1669,7 +1665,7 @@ public: // counts, rather than the sum of seen m-grams, to allow for count pruning. void push_back (const int * mgram, int m, unsigned int count) { - if (m > M) throw runtime_error ("push_back: called with m-gram longer than M"); + if (m > M) RuntimeError("push_back: called with m-gram longer than M"); // add to mgram_map & get location mgram_map::coord c = map.create (mgram_map::unmapped_key (mgram, m), mapCache); // save the count @@ -1810,7 +1806,7 @@ public: // special call for reset if (data == NULL) { - if (m == 0) throw runtime_error ("adapt: must pass LM order"); + if (m == 0) RuntimeError("adapt: must pass LM order"); init ((int) m); // clear out current LM adaptBuffer.clear(); adaptBufferHead.clear(); @@ -1927,7 +1923,7 @@ public: int unkId = constSymMap[""]; // or -1 -- -1 is OK if (startId == -1 || endId == -1) // if filtering, these must be given - throw runtime_error ("read: and/or missing in vocabulary"); + RuntimeError("read: and/or missing in vocabulary"); // if filtering but no , we use (vocabsize) as the id, and have // estimate() prune it @@ -2021,7 +2017,7 @@ public: void estimate (int startId, const std::vector & minObs, vector dropWord) { if (!adaptBuffer.empty()) - throw runtime_error ("estimate: adaptation buffer not empty, call adapt(*,0) to flush buffer first"); + RuntimeError("estimate: adaptation buffer not empty, call adapt(*,0) to flush buffer first"); // Establish w->id mapping -- mapping is identical (w=id) during estimation. std::vector w2id (map.maxid() +1); @@ -2067,12 +2063,12 @@ public: const mgram_map::key key_w = key.pop_h(); const mgram_map::foundcoord c_w = map[key_w]; if (!c_w.valid_w()) - throw runtime_error ("estimate: invalid shortened KN m-gram"); + RuntimeError("estimate: invalid shortened KN m-gram"); KNCounts[c_w]++; // (u,v,w) -> count (*,v,w) const mgram_map::key key_h = key_w.pop_w(); mgram_map::foundcoord c_h = map[key_h]; if (!c_h.valid_w()) - throw runtime_error ("estimate: invalid shortened KN history"); + RuntimeError("estimate: invalid shortened KN history"); KNTotalCounts[c_h]++; // (u,v,w) -> count (*,v,w) } } @@ -2115,7 +2111,7 @@ public: { count = KNCounts[iter]; if (count == 0) // must exist - throw runtime_error ("estimate: malformed data: back-off value not found (numerator)"); + RuntimeError("estimate: malformed data: back-off value not found (numerator)"); } } @@ -2127,8 +2123,8 @@ public: for (int m = 1; m <= M; m++) { - if (n1[m] == 0) throw runtime_error (msra::strfun::strprintf ("estimate: error estimating discounting values: n1[%d] == 0", m)); - if (n2[m] == 0) throw runtime_error (msra::strfun::strprintf ("estimate: error estimating discounting values: n2[%d] == 0", m)); + if (n1[m] == 0) RuntimeError(msra::strfun::strprintf ("estimate: error estimating discounting values: n1[%d] == 0", m)); + if (n2[m] == 0) RuntimeError(msra::strfun::strprintf ("estimate: error estimating discounting values: n2[%d] == 0", m)); //if (n3[m] == 0) RuntimeError ("estimate: error estimating discounting values: n3[%d] == 0", m); double Y = n1[m] / (n1[m] + 2.0 * n2[m]); if (n3[m] ==0 || n4[m] == 0) @@ -2197,7 +2193,7 @@ public: mgram_map::coord j = histCoord[m-1]; // parent if (counts[j] == 0) RuntimeError ("estimate: invalid pruning: a parent m-gram got pruned away"); - //throw runtime_error ("estimate: invalid pruning: a parent m-gram got pruned away"); + //RuntimeError("estimate: invalid pruning: a parent m-gram got pruned away"); numMGrams[m]++; } } @@ -2282,7 +2278,7 @@ public: const mgram_map::key key_h = key.pop_w(); mgram_map::foundcoord c_h = map[key_h]; if (!c_h.valid_w()) - throw runtime_error ("estimate: invalid shortened KN history"); + RuntimeError("estimate: invalid shortened KN history"); histCount = KNTotalCounts[c_h]; // (u,v,w) -> count (*,v,*) if (histCount == 0) // must exist RuntimeError ("estimate: malformed data: back-off value not found (denominator)"); @@ -2330,7 +2326,7 @@ public: else if (count == 2) dcount -= d2[m]; else if (count == 1) dcount -= d1[m]; if (dcount < 0.0) // 0.0 itself is caused by - throw runtime_error ("estimate: negative discounted count value"); + RuntimeError("estimate: negative discounted count value"); if (histCount == 0) RuntimeError ("estimate: unexpected 0 denominator"); @@ -2535,10 +2531,10 @@ skipMGram: msra::basetypes::auto_file_ptr f(fopenOrDie (clonepath, L"rbS")); std::string line = fgetline (f); if (line != "#clone") - throw runtime_error ("read: invalid header line " + line); + RuntimeError("read: invalid header line " + line); std::string lmpath8 = fgetline (f); // only one item: the pathname if (lmpath8.empty()) - throw runtime_error ("read: pathname missing"); + RuntimeError("read: pathname missing"); lmpath = msra::strfun::utf16 (lmpath8); } }; diff --git a/DataReader/HTKMLFReader/rollingwindowsource.h b/DataReader/HTKMLFReader/rollingwindowsource.h index fecede922..cf8838156 100644 --- a/DataReader/HTKMLFReader/rollingwindowsource.h +++ b/DataReader/HTKMLFReader/rollingwindowsource.h @@ -214,7 +214,7 @@ namespace msra { namespace dbn { const msra::dbn::matrixstripe operator[] (size_t t) const // get a feature vector { if (t < inmembegin || t >= inmemend) - throw std::logic_error ("biggrowablevectorarray: attempt to access vector without requesting to page it in first"); + LogicError("biggrowablevectorarray: attempt to access vector without requesting to page it in first"); const size_t blockt = getblockt (t); /*const*/ msra::dbn::matrix & block = getblock (t); return msra::dbn::matrixstripe (block, blockt, 1); @@ -262,7 +262,7 @@ namespace msra { namespace dbn { : vdim (vdim), sampperiod (0), featdim (0), numframes (0), frames (pagepath), timegetbatch (0), verbosity(2) { if (vdim == 0 && labels.empty()) - throw runtime_error ("minibatchframesource: when running without features, labels are needed"); + RuntimeError("minibatchframesource: when running without features, labels are needed"); // at this stage, we simply page in the entire training set at once and work off RAM // We will benefit from feature archives indirectly through htkfeatio. // TODO: @@ -312,7 +312,7 @@ namespace msra { namespace dbn { if (featdim == 0) // first time featdim = feat.rows(); else if (featdim != feat.rows()) - throw std::runtime_error ("minibatchframesource: inconsistent feature dimension across files"); + RuntimeError("minibatchframesource: inconsistent feature dimension across files"); // HVite occasionally generates mismatching output --skip such files if (!key.empty()) // (we have a key if supervised mode) { @@ -328,7 +328,7 @@ namespace msra { namespace dbn { // append to cache frame.resize (featdim); if (feat.cols() < 2) // (2 frames needed for boundary markers) - throw std::runtime_error ("minibatchframesource: utterances < 2 frames not supported"); + RuntimeError("minibatchframesource: utterances < 2 frames not supported"); foreach_column (t, feat) { foreach_index (k, frame) @@ -349,13 +349,13 @@ namespace msra { namespace dbn { { const auto & e = labseq[i]; if ((i > 0 && labseq[i-1].firstframe + labseq[i-1].numframes != e.firstframe) || (i == 0 && e.firstframe != 0)) - throw std::runtime_error (msra::strfun::strprintf ("minibatchframesource: labels not in consecutive order MLF in label set: %S", key.c_str())); + RuntimeError(msra::strfun::strprintf ("minibatchframesource: labels not in consecutive order MLF in label set: %S", key.c_str())); for (size_t t = e.firstframe; t < e.firstframe + e.numframes; t++) { if (e.classid >= udim) - throw std::runtime_error (msra::strfun::strprintf ("minibatchframesource: class id exceeds model dimension in file %S", key.c_str())); + RuntimeError(msra::strfun::strprintf ("minibatchframesource: class id exceeds model dimension in file %S", key.c_str())); if (e.classid != (CLASSIDTYPE) e.classid) - throw std::runtime_error ("CLASSIDTYPE has too few bits"); + RuntimeError("CLASSIDTYPE has too few bits"); classids.push_back ((CLASSIDTYPE) e.classid); numclasses = max (numclasses, (size_t)(1u + e.classid)); } @@ -363,7 +363,7 @@ namespace msra { namespace dbn { if (vdim == 0) numframes = classids.size(); if (numframes != classids.size()) // TODO: remove this once we are confident - throw std::runtime_error (msra::strfun::strprintf ("minibatchframesource: label duration inconsistent with feature file in MLF label set: %S", key.c_str())); + RuntimeError(msra::strfun::strprintf ("minibatchframesource: label duration inconsistent with feature file in MLF label set: %S", key.c_str())); assert (numframes == classids.size()); } else @@ -374,17 +374,17 @@ namespace msra { namespace dbn { assert (vdim == 0 || numframes == frames.size()); assert (labels.empty() || numframes == classids.size()); if ((vdim != 0 && numframes != frames.size()) || (!labels.empty() && numframes != classids.size())) - throw std::runtime_error ("minibatchframesource: numframes variable screwup"); + RuntimeError("minibatchframesource: numframes variable screwup"); fprintf (stderr, " %d frames read from %d utterances; %d classes\n", (int)numframes, (int)infiles.size(), (int)numclasses); if (notfound > 0) { fprintf (stderr, "minibatchframesource: %d files out of %d not found in label set\n", (int)notfound, (int)infiles.size()); if (notfound > infiles.size() / 2) - throw std::runtime_error ("minibatchframesource: too many files not found in label set--assuming broken configuration\n"); + RuntimeError("minibatchframesource: too many files not found in label set--assuming broken configuration\n"); } if (numframes == 0 && !mayhavenoframe) - throw std::runtime_error ("minibatchframesource: no input features given!"); + RuntimeError("minibatchframesource: no input features given!"); // notify frames source to switch from population to consumption mode frames.no_more_push_back(); @@ -484,7 +484,7 @@ namespace msra { namespace dbn { // In frame mode, there is no constraint, i.e. it is 'globalts' itself. /*implement*/ size_t firstvalidglobalts (const size_t globalts) { return globalts; } - /*implement*/ const std::vector & unitcounts() const { throw logic_error ("unitcounts: not implemented for this feature source"); static std::vector x; return x;/*keep compiler happy*/ } + /*implement*/ const std::vector & unitcounts() const { LogicError("unitcounts: not implemented for this feature source"); static std::vector x; return x;/*keep compiler happy*/ } }; // --------------------------------------------------------------------------- @@ -520,7 +520,7 @@ namespace msra { namespace dbn { { if (vdim[0] == 0 && labels.empty()) - throw runtime_error ("minibatchframesourcemulti: when running without features, labels are needed"); + RuntimeError("minibatchframesourcemulti: when running without features, labels are needed"); // at this stage, we simply page in the entire training set at once and work off RAM // We will benefit from feature archives indirectly through htkfeatio. // TODO: @@ -536,7 +536,7 @@ namespace msra { namespace dbn { std::vectorframesaccum; if (infiles.size()==0) - throw runtime_error("minibatchframesourcemulti: need at least one network input specified with features"); + RuntimeError("minibatchframesourcemulti: need at least one network input specified with features"); if (labels.size()==0) fprintf(stderr,"no MLF label files detected\n"); @@ -606,7 +606,7 @@ namespace msra { namespace dbn { if (featdim == 0) // first time featdim = feat.rows(); else if (featdim != feat.rows()) - throw std::runtime_error ("minibatchframesourcemulti: inconsistent feature dimension across files"); + RuntimeError("minibatchframesourcemulti: inconsistent feature dimension across files"); // HVite occasionally generates mismatching output --skip such files if (!key.empty()) // (we have a key if supervised mode) { @@ -622,7 +622,7 @@ namespace msra { namespace dbn { // append to cache frame.resize (featdim); if (feat.cols() < 2) // (2 frames needed for boundary markers) - throw std::runtime_error ("minibatchframesourcemulti: utterances < 2 frames not supported"); + RuntimeError("minibatchframesourcemulti: utterances < 2 frames not supported"); foreach_column (t, feat) { foreach_index (k, frame) @@ -656,13 +656,13 @@ namespace msra { namespace dbn { { const auto & e = labseq[i]; if ((i > 0 && labseq[i-1].firstframe + labseq[i-1].numframes != e.firstframe) || (i == 0 && e.firstframe != 0)) - throw std::runtime_error (msra::strfun::strprintf ("minibatchframesourcemulti: labels not in consecutive order MLF in label set: %S", key.c_str())); + RuntimeError(msra::strfun::strprintf ("minibatchframesourcemulti: labels not in consecutive order MLF in label set: %S", key.c_str())); for (size_t t = e.firstframe; t < e.firstframe + e.numframes; t++) { if (e.classid >= udim[j]) - throw std::runtime_error (msra::strfun::strprintf ("minibatchframesourcemulti: class id exceeds model dimension in file %S", key.c_str())); + RuntimeError(msra::strfun::strprintf ("minibatchframesourcemulti: class id exceeds model dimension in file %S", key.c_str())); if (e.classid != (CLASSIDTYPE) e.classid) - throw std::runtime_error ("CLASSIDTYPE has too few bits"); + RuntimeError("CLASSIDTYPE has too few bits"); classids[j].push_back ((CLASSIDTYPE) e.classid); numclasses[j] = max (numclasses[j], (size_t)(1u + e.classid)); } @@ -670,7 +670,7 @@ namespace msra { namespace dbn { if (vdim[m] == 0) numframes = classids[j].size(); if (numframes != classids[j].size()) // TODO: remove this once we are confident - throw std::runtime_error (msra::strfun::strprintf ("minibatchframesourcemulti: label duration inconsistent with feature file in MLF label set: %S", key.c_str())); + RuntimeError(msra::strfun::strprintf ("minibatchframesourcemulti: label duration inconsistent with feature file in MLF label set: %S", key.c_str())); assert (numframes == classids[j].size()); } @@ -691,7 +691,7 @@ namespace msra { namespace dbn { assert (labels[j].empty() || numframes == classids[j].size()); if (vdim[m] != 0 && numframes != pframes[m]->size()) // || (!labels.empty() && numframes != classids.size())) - throw std::runtime_error ("\nminibatchframesource: numframes variable screwup"); + RuntimeError("\nminibatchframesource: numframes variable screwup"); if (m==0) { foreach_index (j, numclasses) @@ -702,7 +702,7 @@ namespace msra { namespace dbn { { fprintf (stderr, "minibatchframesourcemulti: %d files out of %d not found in label set\n", (int)notfound, (int)infiles[m].size()); if (notfound > infiles[m].size() / 2) - throw std::runtime_error ("minibatchframesourcemulti: too many files not found in label set--assuming broken configuration\n"); + RuntimeError("minibatchframesourcemulti: too many files not found in label set--assuming broken configuration\n"); } // notify frames source to switch from population to consumption mode pframes[m]->no_more_push_back(); @@ -710,7 +710,7 @@ namespace msra { namespace dbn { } if (numframes == 0 && !mayhavenoframe) - throw std::runtime_error ("minibatchframesource: no input features given!"); + RuntimeError("minibatchframesource: no input features given!"); // initialize randomizer @@ -824,7 +824,7 @@ namespace msra { namespace dbn { std::vector> & /*latticepairs*/) { // should never get here - throw runtime_error("minibatchframesourcemulti: getbatch() being called for single input feature and single output feature, should use minibatchframesource instead\n"); + RuntimeError("minibatchframesourcemulti: getbatch() being called for single input feature and single output feature, should use minibatchframesource instead\n"); } double gettimegetbatch () { return timegetbatch;} @@ -833,7 +833,7 @@ namespace msra { namespace dbn { // In frame mode, there is no constraint, i.e. it is 'globalts' itself. /*implement*/ size_t firstvalidglobalts (const size_t globalts) { return globalts; } - /*implement*/ const std::vector & unitcounts() const { throw logic_error ("unitcounts: not implemented for this feature source"); } + /*implement*/ const std::vector & unitcounts() const { LogicError("unitcounts: not implemented for this feature source"); } }; };}; diff --git a/DataReader/HTKMLFReader/utterancesourcemulti.h b/DataReader/HTKMLFReader/utterancesourcemulti.h index ce6930e65..e533248e7 100644 --- a/DataReader/HTKMLFReader/utterancesourcemulti.h +++ b/DataReader/HTKMLFReader/utterancesourcemulti.h @@ -16,7 +16,6 @@ #include "unordered_set" namespace msra { namespace dbn { - using Microsoft::MSR::CNTK::LogicError; // --------------------------------------------------------------------------- // minibatchutterancesource -- feature source to provide randomized utterances @@ -80,7 +79,7 @@ class minibatchutterancesourcemulti : public minibatchsource void push_back (utterancedesc &&/*destructive*/ utt) { if (isinram()) - throw std::logic_error ("utterancechunkdata: frames already paged into RAM--too late to add data"); + LogicError("utterancechunkdata: frames already paged into RAM--too late to add data"); firstframes.push_back (totalframes); totalframes += utt.numframes(); utteranceset.push_back (utt); @@ -92,7 +91,7 @@ class minibatchutterancesourcemulti : public minibatchsource msra::dbn::matrixstripe getutteranceframes (size_t i) const // return the frame set for a given utterance { if (!isinram()) - throw std::logic_error ("getutteranceframes: called when data have not been paged in"); + LogicError("getutteranceframes: called when data have not been paged in"); const size_t ts = firstframes[i]; const size_t n = numframes(i); return msra::dbn::matrixstripe (frames, ts, n); @@ -100,7 +99,7 @@ class minibatchutterancesourcemulti : public minibatchsource shared_ptr getutterancelattice (size_t i) const // return the frame set for a given utterance { if (!isinram()) - throw std::logic_error ("getutteranceframes: called when data have not been paged in"); + LogicError("getutteranceframes: called when data have not been paged in"); return lattices[i]; } @@ -112,9 +111,9 @@ class minibatchutterancesourcemulti : public minibatchsource void requiredata (string & featkind, size_t & featdim, unsigned int & sampperiod, const latticesource & latticesource, int verbosity=0) const { if (numutterances() == 0) - throw std::logic_error ("requiredata: cannot page in virgin block"); + LogicError("requiredata: cannot page in virgin block"); if (isinram()) - throw std::logic_error ("requiredata: called when data is already in memory"); + LogicError("requiredata: called when data is already in memory"); try // this function supports retrying since we read from the unrealible network, i.e. do not return in a broken state { msra::asr::htkfeatreader reader; // feature reader (we reinstantiate it for each block, i.e. we reopen the file actually) @@ -152,9 +151,9 @@ class minibatchutterancesourcemulti : public minibatchsource void releasedata() const { if (numutterances() == 0) - throw std::logic_error ("releasedata: cannot page out virgin block"); + LogicError("releasedata: cannot page out virgin block"); if (!isinram()) - throw std::logic_error ("releasedata: called when data is not memory"); + LogicError("releasedata: called when data is not memory"); // release frames frames.resize (0, 0); // release lattice data @@ -236,7 +235,7 @@ class minibatchutterancesourcemulti : public minibatchsource { if (ci == chunkindex && ui == utteranceindex && fi == frameindex) return; - throw std::logic_error ("frameref: bit fields too small"); + LogicError("frameref: bit fields too small"); } frameref() : chunkindex (0), utteranceindex (0), frameindex (0) {} }; @@ -249,7 +248,7 @@ class minibatchutterancesourcemulti : public minibatchsource VECTOR & v; size_t first; size_t n; - void check (size_t i) const { if (i >= n) throw std::logic_error ("shiftedvector: index out of bounds"); } + void check (size_t i) const { if (i >= n) LogicError("shiftedvector: index out of bounds"); } public: shiftedvector (VECTOR & v, size_t first, size_t n) : v (v), first (first), n (n) { } // TODO: the following is not templated--do it if needed; also should return a const reference then @@ -273,7 +272,7 @@ class minibatchutterancesourcemulti : public minibatchsource foreach_index(i,classids) { if ((*classids[i])[classidsbegin + n] != (CLASSIDTYPE) -1) - throw std::logic_error ("getclassids: expected boundary marker not found, internal data structure screwed up"); + LogicError("getclassids: expected boundary marker not found, internal data structure screwed up"); allclassids.push_back(std::move(shiftedvector> ((*classids[i]), classidsbegin, n))); } return allclassids; // nothing to return @@ -296,7 +295,7 @@ class minibatchutterancesourcemulti : public minibatchsource foreach_index(i, phoneboundaries) { if ((*phoneboundaries[i])[classidsbegin + n] != (CLASSIDTYPE)-1) - throw std::logic_error("getclassids: expected boundary marker not found, internal data structure screwed up"); + LogicError("getclassids: expected boundary marker not found, internal data structure screwed up"); allphoneboundaries.push_back(std::move(shiftedvector>((*phoneboundaries[i]), classidsbegin, n))); } return allphoneboundaries; // nothing to return @@ -361,14 +360,14 @@ public: uttduration = std::vector(numutts, 0); } else if (infiles[m].size()!=numutts) - throw std::runtime_error("minibatchutterancesourcemulti: all feature files must have same number of utterances"); + RuntimeError("minibatchutterancesourcemulti: all feature files must have same number of utterances"); foreach_index(i, infiles[m]){ utterancedesc utterance(msra::asr::htkfeatreader::parsedpath(infiles[m][i]), 0); //mseltzer - is this foolproof for multiio? is classids always non-empty? const size_t uttframes = utterance.numframes(); // will throw if frame bounds not given --required to be given in this mode // we need at least 2 frames for boundary markers to work if (uttframes < 2) - throw std::runtime_error("minibatchutterancesource: utterances < 2 frames not supported"); + RuntimeError("minibatchutterancesource: utterances < 2 frames not supported"); if (uttframes > frameref::maxframesperutterance) { fprintf(stderr, "minibatchutterancesource: skipping %d-th file (%d frames) because it exceeds max. frames (%d) for frameref bit field: %S\n", i, (int)uttframes, (int)frameref::maxframesperutterance, key.c_str()); @@ -394,7 +393,7 @@ public: invalidutts++; } if (invalidutts > uttisvalid.size() / 2) - throw std::runtime_error("minibatchutterancesource: too many files with inconsistent durations, assuming broken configuration\n"); + RuntimeError("minibatchutterancesource: too many files with inconsistent durations, assuming broken configuration\n"); else if (invalidutts>0) fprintf(stderr, "Found inconsistent durations across feature streams in %d out of %d files\n", (int)invalidutts, (int)uttisvalid.size()); @@ -408,7 +407,7 @@ public: // numutts = infiles[m].size(); //else // if (infiles[m].size()!=numutts) - // throw std::runtime_error("minibatchutterancesourcemulti: all feature files must have same number of utterances\n"); + // RuntimeError("minibatchutterancesourcemulti: all feature files must have same number of utterances\n"); if (m==0) classidsbegin.clear(); @@ -427,7 +426,7 @@ public: // already performed these checks above // we need at least 2 frames for boundary markers to work //if (uttframes < 2) - // throw std::runtime_error ("minibatchutterancesource: utterances < 2 frames not supported"); + // RuntimeError("minibatchutterancesource: utterances < 2 frames not supported"); //if (uttframes > frameref::maxframesperutterance) //{ // fprintf (stderr, "minibatchutterancesource: skipping %d-th file (%d frames) because it exceeds max. frames (%d) for frameref bit field: %S", i, uttframes, frameref::maxframesperutterance, key.c_str()); @@ -498,14 +497,14 @@ public: const auto & e = labseq[i]; if ((i > 0 && labseq[i - 1].firstframe + labseq[i - 1].numframes != e.firstframe) || (i == 0 && e.firstframe != 0)) { - throw std::runtime_error(msra::strfun::strprintf("minibatchutterancesource: labels not in consecutive order MLF in label set: %S", key.c_str())); + RuntimeError(msra::strfun::strprintf("minibatchutterancesource: labels not in consecutive order MLF in label set: %S", key.c_str())); } if (e.classid >= udim[j]) { - throw std::runtime_error(msra::strfun::strprintf("minibatchutterancesource: class id %d exceeds model output dimension %d in file %S", e.classid, udim[j], key.c_str())); + RuntimeError(msra::strfun::strprintf("minibatchutterancesource: class id %d exceeds model output dimension %d in file %S", e.classid, udim[j], key.c_str())); } if (e.classid != (CLASSIDTYPE) e.classid) - throw std::runtime_error ("CLASSIDTYPE has too few bits"); + RuntimeError("CLASSIDTYPE has too few bits"); for (size_t t = e.firstframe; t < e.firstframe + e.numframes; t++) { classids[j]->push_back ((CLASSIDTYPE) e.classid); @@ -523,7 +522,7 @@ public: phoneboundaries[j]->push_back((CLASSIDTYPE)-1); // append a boundary marker marker for checking if (!labels[j].empty() && classids[j]->size() != _totalframes + utteranceset.size()) - throw std::logic_error (msra::strfun::strprintf ("minibatchutterancesource: label duration inconsistent with feature file in MLF label set: %S", key.c_str())); + LogicError(msra::strfun::strprintf ("minibatchutterancesource: label duration inconsistent with feature file in MLF label set: %S", key.c_str())); assert (labels[j].empty() || classids[j]->size() == _totalframes + utteranceset.size()); } } @@ -557,7 +556,7 @@ public: //printf("cid[index] = %d\n",cid[utteranceset[i].classidsbegin + utteranceset[i].numframes()]); //printf("CLASSIDTYPE(-1) = %d\n",(CLASSIDTYPE) -1); if (cid[utteranceset[i].classidsbegin + utteranceset[i].numframes()] != (CLASSIDTYPE) -1) - throw std::logic_error ("minibatchutterancesource: classids[] out of sync"); + LogicError("minibatchutterancesource: classids[] out of sync"); } } } @@ -565,7 +564,7 @@ public: { fprintf (stderr, "minibatchutterancesource: out of %d files, %d files not found in label set and %d have no lattice\n", (int)infiles[0].size(), (int)nomlf, (int)nolat); if (nomlf + nolat > infiles[m].size() / 2) - throw std::runtime_error ("minibatchutterancesource: too many files not found in label set--assuming broken configuration\n"); + RuntimeError("minibatchutterancesource: too many files not found in label set--assuming broken configuration\n"); } if (m==0) {foreach_index(j, numclasses) { fprintf(stderr,"label set %d: %d classes\n", j, (int)numclasses[j]); } } // distribute them over chunks @@ -607,7 +606,7 @@ private: template static void randomshuffle (VECTOR & v, size_t randomseed) { if (v.size() > RAND_MAX * (size_t) RAND_MAX) - throw std::runtime_error ("randomshuffle: too large set: need to change to different random generator!"); + RuntimeError("randomshuffle: too large set: need to change to different random generator!"); srand ((unsigned int) randomseed); foreach_index (i, v) { @@ -626,7 +625,7 @@ private: foreach_index(j, v) { if (v[j].size() > RAND_MAX * (size_t) RAND_MAX) - throw std::runtime_error ("randomshuffle: too large set: need to change to different random generator!"); + RuntimeError("randomshuffle: too large set: need to change to different random generator!"); } srand ((unsigned int) randomseed); @@ -647,7 +646,7 @@ private: static void checkoverflow (size_t fieldval, size_t targetval, const char * fieldname) { if (fieldval != targetval) - throw std::runtime_error (msra::strfun::strprintf ("checkoverflow: bit field %s too small for value 0x%x (cut from 0x%x)", fieldname, targetval, fieldval)); + RuntimeError(msra::strfun::strprintf ("checkoverflow: bit field %s too small for value 0x%x (cut from 0x%x)", fieldname, targetval, fieldval)); } // helper for testing whether a swapped frame position is valid (w.r.t. beign in RAM when being at position 't') @@ -852,7 +851,7 @@ private: const auto & uttref = randomizedutterancerefs[i]; // check if it is valid for this position if (uttref.chunkindex < positionchunkwindows[i].windowbegin() || uttref.chunkindex >= positionchunkwindows[i].windowend()) - throw std::logic_error ("lazyrandomization: randomization logic mangled!"); + LogicError("lazyrandomization: randomization logic mangled!"); } // create lookup table for (globalts values -> pos) -> randomizedutteranceposmap[] @@ -972,7 +971,7 @@ private: { const size_t randomizedchunkindex = randomizedframerefs[t].chunkindex; if (randomizedchunkindex < poswindowbegin || randomizedchunkindex >= poswindowend) - throw std::logic_error ("lazyrandomization: nope, you got frame randomization wrong, dude"); + LogicError("lazyrandomization: nope, you got frame randomization wrong, dude"); t++; } } @@ -1017,7 +1016,7 @@ private: size_t numinram=0; if (chunkindex < windowbegin || chunkindex >= windowend) - throw std::logic_error ("requirerandomizedchunk: requested utterance outside in-memory chunk range"); + LogicError("requirerandomizedchunk: requested utterance outside in-memory chunk range"); foreach_index(m, randomizedchunks) { @@ -1065,7 +1064,7 @@ private: auto iter = std::lower_bound (randomizedchunks[0].begin(), randomizedchunks[0].end(), t, [&] (const chunk & chunk, size_t t) { return chunk.globalte() <= t; }); const size_t chunkindex = iter - randomizedchunks[0].begin(); if (t < randomizedchunks[0][chunkindex].globalts || t >= randomizedchunks[0][chunkindex].globalte()) - throw std::logic_error ("chunkforframepos: dude, learn STL!"); + LogicError("chunkforframepos: dude, learn STL!"); return chunkindex; } @@ -1107,7 +1106,7 @@ public: // There must be a precise match; it is not possible to specify frames that are not on boundaries. auto positer = randomizedutteranceposmap.find (globalts); if (positer == randomizedutteranceposmap.end()) - throw std::logic_error ("getbatch: invalid 'globalts' parameter; must match an existing utterance boundary"); + LogicError("getbatch: invalid 'globalts' parameter; must match an existing utterance boundary"); const size_t spos = positer->second; // determine how many utterances will fit into the requested minibatch size @@ -1417,7 +1416,7 @@ public: std::vector> & /*latticepairs*/) { // should never get here - throw runtime_error("minibatchframesourcemulti: getbatch() being called for single input feature and single output feature, should use minibatchutterancesource instead\n"); + RuntimeError("minibatchframesourcemulti: getbatch() being called for single input feature and single output feature, should use minibatchutterancesource instead\n"); // for single input/output set size to be 1 and run old getbatch //feat.resize(1); diff --git a/DataReader/LUSequenceReader/LUSequenceReader.cpp b/DataReader/LUSequenceReader/LUSequenceReader.cpp index 7d342878f..b033483a2 100644 --- a/DataReader/LUSequenceReader/LUSequenceReader.cpp +++ b/DataReader/LUSequenceReader/LUSequenceReader.cpp @@ -697,13 +697,13 @@ bool BatchLUSequenceReader::EnsureDataAvailable(size_t /*mbStartSample int j = 0; if (mLastPosInSentence != 0) - throw std::runtime_error("LUSequenceReader : only support begining sentence at zero"); + RuntimeError("LUSequenceReader : only support begining sentence at zero"); if (mSentenceBeginAt.size() != mToProcess.size()) - throw std::runtime_error("LUSequenceReader : need to preallocate mSentenceBegin"); + RuntimeError("LUSequenceReader : need to preallocate mSentenceBegin"); if (mSentenceEndAt.size() != mToProcess.size()) - throw std::runtime_error("LUSequenceReader : need to preallocate mSentenceEnd"); + RuntimeError("LUSequenceReader : need to preallocate mSentenceEnd"); if (mMaxSentenceLength > m_mbSize) - throw std::runtime_error("LUSequenceReader : minibatch size needs to be large enough to accomodate the longest sentence"); + RuntimeError("LUSequenceReader : minibatch size needs to be large enough to accomodate the longest sentence"); /// reset sentence-end index to ((int) MinibatchPackingFlags::NoInput), which is negative mSentenceEndAt.assign(mSentenceEndAt.size(), ((int) MinibatchPackingFlags::NoInput)); diff --git a/DataReader/LibSVMBinaryReader/LibSVMBinaryReader.cpp b/DataReader/LibSVMBinaryReader/LibSVMBinaryReader.cpp index b746ba353..fd6c6f291 100644 --- a/DataReader/LibSVMBinaryReader/LibSVMBinaryReader.cpp +++ b/DataReader/LibSVMBinaryReader/LibSVMBinaryReader.cpp @@ -429,7 +429,7 @@ void LibSVMBinaryReader::SetLabelMapping(const std::wstring& /*section { if (m_cachingReader) { - throw runtime_error("Cannot set mapping table when the caching reader is being used"); + RuntimeError("Cannot set mapping table when the caching reader is being used"); } m_mapIdToLabel = labelMapping; m_mapLabelToId.clear(); @@ -487,7 +487,7 @@ void LibSVM_BinaryInput::Init(wstring fileName, size_t dim) { char message[256]; sprintf_s(message, "Unable to Open/Create file %ls, error %x", fileName.c_str(), GetLastError()); - throw runtime_error(message); + RuntimeError(message); } m_filemap = CreateFileMapping(m_hndl, NULL, PAGE_READONLY, 0, 0, NULL); @@ -718,7 +718,7 @@ bool LibSVMBinaryReader::GetData(const std::wstring& sectionName, size { return m_cachingReader->GetData(sectionName, numRecords, data, dataBufferSize, recordStart); } - throw runtime_error("GetData not supported in LibSVMBinaryReader"); + RuntimeError("GetData not supported in LibSVMBinaryReader"); } // instantiate all the combinations we expect to be used template class LibSVMBinaryReader; diff --git a/DataReader/SparsePCReader/SparsePCReader.cpp b/DataReader/SparsePCReader/SparsePCReader.cpp index 5999fc5b9..73da67209 100644 --- a/DataReader/SparsePCReader/SparsePCReader.cpp +++ b/DataReader/SparsePCReader/SparsePCReader.cpp @@ -120,7 +120,7 @@ void SparsePCReader::Init(const ConfigParameters& readerConfig) { char message[256]; sprintf_s(message, "Unable to Open/Create file %ls, error %x", m_file.c_str(), GetLastError()); - throw runtime_error(message); + RuntimeError(message); } GetFileSizeEx(m_hndl, (PLARGE_INTEGER)&m_filePositionMax); @@ -236,7 +236,7 @@ bool SparsePCReader::GetMinibatch(std::mapCopyFrom(m_pMBLayout); NOT_IMPLEMENTED; } virtual const std::map& GetLabelMapping(const std::wstring& sectionName); virtual void SetLabelMapping(const std::wstring& sectionName, const std::map& labelMapping); - virtual bool GetData(const std::wstring& /*sectionName*/, size_t /*numRecords*/, void* /*data*/, size_t& /*dataBufferSize*/, size_t /*recordStart*/) { throw runtime_error("GetData not supported in SparsePCReader"); }; + virtual bool GetData(const std::wstring& /*sectionName*/, size_t /*numRecords*/, void* /*data*/, size_t& /*dataBufferSize*/, size_t /*recordStart*/) { RuntimeError("GetData not supported in SparsePCReader"); }; virtual bool DataEnd(EndDataType endDataType); }; }}} diff --git a/DataReader/UCIFastReader/UCIFastReader.cpp b/DataReader/UCIFastReader/UCIFastReader.cpp index 4959493e7..b8ced6bf6 100644 --- a/DataReader/UCIFastReader/UCIFastReader.cpp +++ b/DataReader/UCIFastReader/UCIFastReader.cpp @@ -946,7 +946,7 @@ void UCIFastReader::SetLabelMapping(const std::wstring& /*sectionName* { if (m_cachingReader) { - throw runtime_error("Cannot set mapping table when the caching reader is being used"); + RuntimeError("Cannot set mapping table when the caching reader is being used"); } m_mapIdToLabel = labelMapping; m_mapLabelToId.clear(); @@ -971,7 +971,7 @@ bool UCIFastReader::GetData(const std::wstring& sectionName, size_t nu { return m_cachingReader->GetData(sectionName, numRecords, data, dataBufferSize, recordStart); } - throw runtime_error("GetData not supported in UCIFastReader"); + RuntimeError("GetData not supported in UCIFastReader"); } template diff --git a/DataReader/UCIFastReader/UCIParser.cpp b/DataReader/UCIFastReader/UCIParser.cpp index 0e222e8ca..d4b2a0c3b 100644 --- a/DataReader/UCIFastReader/UCIParser.cpp +++ b/DataReader/UCIFastReader/UCIParser.cpp @@ -7,6 +7,7 @@ // #include "stdafx.h" +#include "Basics.h" #include "UCIParser.h" #include #include @@ -367,10 +368,10 @@ void UCIParser::ParseInit(LPCWSTR fileName, size_t startFeat errno_t err = _wfopen_s( &m_pFile, fileName, L"rb" ); if (err) - throw std::runtime_error("UCIParser::ParseInit - error opening file"); + RuntimeError("UCIParser::ParseInit - error opening file"); int rc = _fseeki64(m_pFile, 0, SEEK_END); if (rc) - throw std::runtime_error("UCIParser::ParseInit - error seeking in file"); + RuntimeError("UCIParser::ParseInit - error seeking in file"); m_fileSize = GetFilePosition(); m_fileBuffer = new BYTE[m_bufferSize]; @@ -384,7 +385,7 @@ int64_t UCIParser::GetFilePosition() { int64_t position = ftell64(m_pFile); if (position == -1L) - throw std::runtime_error("UCIParser::GetFilePosition - error retrieving file position in file"); + RuntimeError("UCIParser::GetFilePosition - error retrieving file position in file"); return position; } @@ -397,7 +398,7 @@ void UCIParser::SetFilePosition(int64_t position) { int rc = _fseeki64(m_pFile, position, SEEK_SET); if (rc) - throw std::runtime_error("UCIParser::SetFilePosition - error seeking in file"); + RuntimeError("UCIParser::SetFilePosition - error seeking in file"); // setup state machine to start at this position PrepareStartPosition(position); @@ -450,7 +451,7 @@ size_t UCIParser::UpdateBuffer() size_t bytesToRead = min(m_bufferSize, m_fileSize-m_bufferStart)-saveBytes; size_t bytesRead = fread(m_fileBuffer+saveBytes, 1, bytesToRead, m_pFile); if (bytesRead == 0 && ferror(m_pFile)) - throw std::runtime_error("UCIParser::UpdateBuffer - error reading file"); + RuntimeError("UCIParser::UpdateBuffer - error reading file"); return bytesRead; } diff --git a/DataReader/UCIReader/readaheadsource.h b/DataReader/UCIReader/readaheadsource.h index 09a757ee5..7e7a67d96 100644 --- a/DataReader/UCIReader/readaheadsource.h +++ b/DataReader/UCIReader/readaheadsource.h @@ -170,9 +170,9 @@ class minibatchreadaheadsource : public noncopyable/*assignment operator needed // Note: We may still get data beyond the end of the epoch, in utterance mode, since the epoch boundary likely falls within an utterance. CAutoLock lock (*this); if (!fifo.empty() && globalts != fifo.back().globalts + fifo.back().feat.GetNumCols()) - throw std::logic_error ("minibatchreadaheadsource: FIFO got out of order while pre-reading new batch"); + LogicError("minibatchreadaheadsource: FIFO got out of order while pre-reading new batch"); if (newglobalts != SIZE_MAX) - throw std::logic_error ("minibatchreadaheadsource: main thread reset to new epoch while current epoch not yet finished"); + LogicError("minibatchreadaheadsource: main thread reset to new epoch while current epoch not yet finished"); globalts += batch.feat.GetNumCols(); } else @@ -237,7 +237,7 @@ public: fprintf (stderr, "minibatchreadaheadsource: signalling thread to enter new epoch\n"); CAutoLock lock (*this); if (!fifo.empty()) - throw std::logic_error ("getbatch: FIFO not cleared at end of epoch"); + LogicError("getbatch: FIFO not cleared at end of epoch"); newglobalts = globalts; currentepochreqframes = p_framesrequested; // it is assumed that these won't change currentepochendframe = (epoch + 1) * epochframes; @@ -269,7 +269,7 @@ public: } if (globalts + framesrequested < currentepochendframe && currentepochreqframes != framesrequested) - throw std::logic_error ("getbatch: cannot change minibatch size mid-epoch"); + LogicError("getbatch: cannot change minibatch size mid-epoch"); // loop for(;;) // wait for batch to appear { @@ -284,7 +284,7 @@ public: flagcallerchanged(); // it must be the correct one if (front.globalts != globalts) - throw std::logic_error ("getbatch: data in FIFO out of sequence"); + LogicError("getbatch: data in FIFO out of sequence"); // if we actually read anything put it in here if (front.readRecords) diff --git a/DataReader/UCIReader/simplethread.h b/DataReader/UCIReader/simplethread.h index cf3775af0..058341f64 100644 --- a/DataReader/UCIReader/simplethread.h +++ b/DataReader/UCIReader/simplethread.h @@ -36,11 +36,11 @@ public: { h = ::CreateEvent (NULL, FALSE/*manual reset*/, initialstate ? TRUE : FALSE, NULL); if (h == NULL) - throw std::runtime_error ("signallingevent: CreateEvent() failed"); + RuntimeError("signallingevent: CreateEvent() failed"); } ~signallingevent() { ::CloseHandle (h); } - void wait() { if (::WaitForSingleObject (h, INFINITE) != WAIT_OBJECT_0) throw std::runtime_error ("wait: WaitForSingleObject() unexpectedly failed"); } - void flag() { if (::SetEvent (h) == 0) throw std::runtime_error ("flag: SetEvent() unexpectedly failed"); } + void wait() { if (::WaitForSingleObject (h, INFINITE) != WAIT_OBJECT_0) RuntimeError("wait: WaitForSingleObject() unexpectedly failed"); } + void flag() { if (::SetEvent (h) == 0) RuntimeError("flag: SetEvent() unexpectedly failed"); } }; @@ -82,16 +82,16 @@ public: unsigned int threadid; uintptr_t rc = _beginthreadex (NULL/*security*/, 0/*stack*/, staticthreadproc, this, CREATE_SUSPENDED, &threadid); if (rc == 0) - throw std::runtime_error ("simplethread: _beginthreadex() failed"); + RuntimeError("simplethread: _beginthreadex() failed"); threadhandle = OpenThread (THREAD_ALL_ACCESS, FALSE, threadid); if (threadhandle == NULL) - throw std::logic_error ("simplethread: _beginthreadex() unexpectedly did not return valid thread id"); // BUGBUG: leaking something + LogicError("simplethread: _beginthreadex() unexpectedly did not return valid thread id"); // BUGBUG: leaking something DWORD rc1 = ::ResumeThread (threadhandle); if (rc1 == (DWORD) -1) { ::TerminateThread (threadhandle, 0); ::CloseHandle (threadhandle); - throw std::logic_error ("simplethread: ResumeThread() failed unexpectedly"); + LogicError("simplethread: ResumeThread() failed unexpectedly"); } try { @@ -118,7 +118,7 @@ public: else if (rc == WAIT_OBJECT_0) return true; else - throw std::runtime_error ("wait: WaitForSingleObject() failed unexpectedly"); + RuntimeError("wait: WaitForSingleObject() failed unexpectedly"); } //void join() //{ diff --git a/MachineLearning/CNTK/CNTK.cpp b/MachineLearning/CNTK/CNTK.cpp index a847987fc..320409506 100644 --- a/MachineLearning/CNTK/CNTK.cpp +++ b/MachineLearning/CNTK/CNTK.cpp @@ -1568,7 +1568,7 @@ int wmain1(int argc, wchar_t* argv[]) // called from wmain which is a wrapper delete g_mpi; } - catch (const ScriptableObjects::ScriptingError &err) + catch (const ScriptableObjects::ScriptingException &err) { fprintf(stderr, "EXCEPTION occurred: %s\n", err.what()); err.PrintError(); diff --git a/MachineLearning/CNTK/FullNetworkBuilder.h b/MachineLearning/CNTK/FullNetworkBuilder.h index abb6f80c5..3bbebe0fb 100644 --- a/MachineLearning/CNTK/FullNetworkBuilder.h +++ b/MachineLearning/CNTK/FullNetworkBuilder.h @@ -122,7 +122,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { origNameToNormNameMap[nodeName] = normPtr; } else - throw new runtime_error("for InputValue nodes, only mvNorm is supported 4th argument\n"); + RuntimeError("for InputValue nodes, only mvNorm is supported 4th argument\n"); } } else if (opName == L"Parameter" || opName == LearnableParameter::TypeName()) @@ -204,7 +204,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { nodePtr->AttachInputs(inputs[0], inputs[1], inputs[2]); break; default: - throw std::logic_error("Invalid number of children."); + LogicError("Invalid number of children."); } } diff --git a/MachineLearning/CNTK/SimpleRecurrentNetEvaluator.h b/MachineLearning/CNTK/SimpleRecurrentNetEvaluator.h index 09771d5c0..c719dd239 100644 --- a/MachineLearning/CNTK/SimpleRecurrentNetEvaluator.h +++ b/MachineLearning/CNTK/SimpleRecurrentNetEvaluator.h @@ -39,19 +39,19 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (crossEntropyNodes.size()==0) { - throw new runtime_error("No CrossEntropyWithSoftmax node found\n"); + RuntimeError("No CrossEntropyWithSoftmax node found\n"); } if (evaluationNodes.size()==0) { - throw new runtime_error("No Evaluation node found\n"); + RuntimeError("No Evaluation node found\n"); } if (crossEntropyNodes.size()==0) { - throw new runtime_error("Evaluate() does not yet support reading multiple CrossEntropyWithSoftMax Nodes\n"); + RuntimeError("Evaluate() does not yet support reading multiple CrossEntropyWithSoftMax Nodes\n"); } if (evaluationNodes.size() == 0) { - throw new runtime_error("Evaluate() does not yet support reading multiple Evaluation Nodes\n"); + RuntimeError("Evaluate() does not yet support reading multiple Evaluation Nodes\n"); } std::map*> inputMatrices; diff --git a/MachineLearning/CNTK/SynchronousExecutionEngine.h b/MachineLearning/CNTK/SynchronousExecutionEngine.h index 43f82c38c..9bb46cf54 100644 --- a/MachineLearning/CNTK/SynchronousExecutionEngine.h +++ b/MachineLearning/CNTK/SynchronousExecutionEngine.h @@ -228,7 +228,7 @@ public: return inputs; } if (nodeParamStart + nodeParamCount > parameter.size()) - throw logic_error("EvaluateParmeters: nodeParamters specified that do not exist"); + LogicError("EvaluateParmeters: nodeParamters specified that do not exist"); size_t numChildren = nodeParamCount; for (size_t i=0; i < numChildren;++i) { diff --git a/MachineLearning/CNTKComputationNetworkLib/ComputationNode.h b/MachineLearning/CNTKComputationNetworkLib/ComputationNode.h index d9c4524b2..cd5b90258 100644 --- a/MachineLearning/CNTKComputationNetworkLib/ComputationNode.h +++ b/MachineLearning/CNTKComputationNetworkLib/ComputationNode.h @@ -518,7 +518,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void InferImageDimsFromInput(const size_t index, const bool outputSameAsInput = true) { if (index >= ChildrenSize()) - throw invalid_argument("InferImageDimsFromInput: output index"); + InvalidArgument("InferImageDimsFromInput: output index"); const auto & child = m_children[index]; if (child != nullptr) diff --git a/MachineLearning/CNTKComputationNetworkLib/NonlinearityNodes.h b/MachineLearning/CNTKComputationNetworkLib/NonlinearityNodes.h index fdc57932d..171c0c80e 100644 --- a/MachineLearning/CNTKComputationNetworkLib/NonlinearityNodes.h +++ b/MachineLearning/CNTKComputationNetworkLib/NonlinearityNodes.h @@ -1237,7 +1237,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { fprintf(stderr, "NULL"); continue; } - throw runtime_error("One of the children is missing."); + RuntimeError("One of the children is missing."); } fprintf(stderr, "%ls[%lu, %lu]", child->NodeName().c_str(), child->GetNumRows(), child->GetNumCols()); @@ -1364,12 +1364,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (m_imageLayout.channels > 0) { if (m_imageLayout.GetNumElements() != m_numRows) - throw runtime_error("Image dimensions do not match row size."); + RuntimeError("Image dimensions do not match row size."); } else { if (m_numRows % (m_imageLayout.width * m_imageLayout.height) > 0) - throw runtime_error("Image row size is not a multiple of specified image dimensions."); + RuntimeError("Image row size is not a multiple of specified image dimensions."); else m_imageLayout.channels = m_numRows / (m_imageLayout.width * m_imageLayout.height); } @@ -1379,13 +1379,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (m_imageLayout.channels > 0) { if (m_numRows % (m_imageLayout.width * m_imageLayout.channels) > 0) - throw runtime_error("Image row size is not a multiple of specified image dimensions."); + RuntimeError("Image row size is not a multiple of specified image dimensions."); else m_imageLayout.height = m_numRows / (m_imageLayout.width * m_imageLayout.channels); } else { - throw runtime_error("At least two image dimensions must be specified."); + RuntimeError("At least two image dimensions must be specified."); } } } @@ -1396,15 +1396,15 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (m_imageLayout.channels > 0) { if (m_numRows % (m_imageLayout.height * m_imageLayout.channels) > 0) - throw runtime_error("Image row size is not a multiple of specified image dimensions."); + RuntimeError("Image row size is not a multiple of specified image dimensions."); else m_imageLayout.width = m_numRows / (m_imageLayout.height * m_imageLayout.channels); } else - throw runtime_error("At least two image dimensions must be specified."); + RuntimeError("At least two image dimensions must be specified."); } else if (m_imageLayout.channels > 0) - throw runtime_error("At least two image dimensions must be specified."); + RuntimeError("At least two image dimensions must be specified."); } } }; @@ -1482,7 +1482,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { fprintf(stderr, "NULL"); continue; } - throw runtime_error("One of the children is missing."); + RuntimeError("One of the children is missing."); } fprintf(stderr, "%ls[%lu, %lu]", child->NodeName().c_str(), child->FunctionValues().GetNumRows(), child->FunctionValues().GetNumCols()); @@ -1497,10 +1497,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { Base::Validate(isFinalValidationPass); if (m_children.size() != 1) - throw std::logic_error("Diagonal operation: Should have one input."); + LogicError("Diagonal operation: Should have one input."); if (Inputs(0)->FunctionValues().GetNumElements() == 0) - throw std::logic_error("Diagonal operation: The input node has 0 element."); + LogicError("Diagonal operation: The input node has 0 element."); size_t cols = Inputs(0)->FunctionValues().GetNumCols(); @@ -1531,7 +1531,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { virtual void ComputeInputPartial(const size_t inputIndex) { if (inputIndex > 0) - throw std::invalid_argument("Diagonal operation only takes one input."); + InvalidArgument("Diagonal operation only takes one input."); ComputeInputPartialS(Inputs(0)->GradientValues(), GradientValues()); } @@ -1632,7 +1632,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { fprintf(stderr, "NULL"); continue; } - throw runtime_error("One of the children is missing."); + RuntimeError("One of the children is missing."); } fprintf(stderr, "%ls[%lu, %lu]", child->NodeName().c_str(), child->GetNumRows(), child->GetNumCols()); diff --git a/MachineLearning/CNTKEval/CNTKEvalTest/CNTKEvalTest.cpp b/MachineLearning/CNTKEval/CNTKEvalTest/CNTKEvalTest.cpp index 88d25e868..e33f35cac 100644 --- a/MachineLearning/CNTKEval/CNTKEvalTest/CNTKEvalTest.cpp +++ b/MachineLearning/CNTKEval/CNTKEvalTest/CNTKEvalTest.cpp @@ -91,7 +91,7 @@ int wmain(int argc, wchar_t* argv[]) else if (type == "double") DoCommand(config); else - throw runtime_error("invalid precision specified: " + type); + RuntimeError("invalid precision specified: " + type); } catch(std::exception &err) { diff --git a/MachineLearning/CNTKSGDLib/MultiNetworksSGD.h b/MachineLearning/CNTKSGDLib/MultiNetworksSGD.h index ec6a97cec..2dcbabe41 100644 --- a/MachineLearning/CNTKSGDLib/MultiNetworksSGD.h +++ b/MachineLearning/CNTKSGDLib/MultiNetworksSGD.h @@ -139,7 +139,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const bool makeMode) { if (validationSetDataReader.size() == 0) - throw std::invalid_argument("validation set reader should not be null."); + InvalidArgument("validation set reader should not be null."); int startEpoch = DetermineEncoderDecoderStartEpoch(makeMode); if (startEpoch == m_maxEpochs) @@ -295,7 +295,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { learnRateInitialized = this->LoadCheckPointInfo(startEpoch - 1, totalSamplesSeen, learnRatePerSample, smoothedGradients, prevCriterion, m_prevChosenMinibatchSize); if (m_autoLearnRateSearchType == LearningRateSearchAlgorithm::AdjustAfterEpoch && !learnRateInitialized && m_learningRatesParam.size() <= startEpoch) - throw std::invalid_argument("When using \"AdjustAfterEpoch\", there must either exist a checkpoint file, or an explicit learning rate must be specified in config for the starting epoch."); + InvalidArgument("When using \"AdjustAfterEpoch\", there must either exist a checkpoint file, or an explicit learning rate must be specified in config for the starting epoch."); ULONG dropOutSeed = 1; double prevDropoutRate = 0; @@ -616,7 +616,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } if (m_autoLearnRateSearchType == LearningRateSearchAlgorithm::AdjustAfterEpoch && !learnRateInitialized && m_learningRatesParam.size() <= startEpoch) - throw std::invalid_argument("When using \"AdjustAfterEpoch\", there must either exist a checkpoint file, or an explicit learning rate must be specified in config for the starting epoch."); + InvalidArgument("When using \"AdjustAfterEpoch\", there must either exist a checkpoint file, or an explicit learning rate must be specified in config for the starting epoch."); ULONG dropOutSeed = 1; double prevDropoutRate = 0; @@ -910,7 +910,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { criterionNodes, localEpochCriterion, localEpochEvalErrors) == false) { - throw runtime_error("SGD::TrainOneEpochEncoderDecoderWithHiddenStates gradient check not passed!"); + RuntimeError("SGD::TrainOneEpochEncoderDecoderWithHiddenStates gradient check not passed!"); } localEpochCriterion.SetValue(0); localEpochEvalErrors.SetValue(0); diff --git a/MachineLearning/CNTKSGDLib/SGD.cpp b/MachineLearning/CNTKSGDLib/SGD.cpp index ed24a41e3..5fdc15a2d 100644 --- a/MachineLearning/CNTKSGDLib/SGD.cpp +++ b/MachineLearning/CNTKSGDLib/SGD.cpp @@ -21,7 +21,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else if (s == L"kl" || s == L"klreg") return AdaptationRegType::KL; else - throw std::invalid_argument("ParseAdaptationRegType: Invalid Adaptation Regularization Type. Valid values are (None | KL)"); + InvalidArgument("ParseAdaptationRegType: Invalid Adaptation Regularization Type. Valid values are (None | KL)"); } static GradientsUpdateType ParseGradUpdateType(wstring s) @@ -36,7 +36,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else if (s == L"fsadagrad") return GradientsUpdateType::FSAdaGrad; else - throw std::invalid_argument("ParseGradUpdateType: Invalid Gradient Updating Type. Valid values are (None | AdaGrad | RmsProp | FSAdaGrad )"); + InvalidArgument("ParseGradUpdateType: Invalid Gradient Updating Type. Valid values are (None | AdaGrad | RmsProp | FSAdaGrad )"); } static ParallelizationMethod ParseParallelizationMethod(wstring s) @@ -49,7 +49,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else if (s == L"modelaveragingsgd") return ParallelizationMethod::ModelAveragingSGD; else - throw std::invalid_argument("ParseParallelizationMethod: Invalid Parallelization Method. Valid values are (None | DataParallelSGD | ModelAveragingSGD)"); + InvalidArgument("ParseParallelizationMethod: Invalid Parallelization Method. Valid values are (None | DataParallelSGD | ModelAveragingSGD)"); } static LearningRateSearchAlgorithm ParseLearningRateSearchType(wstring s) @@ -63,7 +63,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else if (s == L"adjustafterepoch" || s == L"afterepoch" || s == L"after") return LearningRateSearchAlgorithm::AdjustAfterEpoch; else - throw std::invalid_argument("autoAdjustLR: Invalid learning rate search type. Valid values are (None | SearchBeforeEpoch | AdjustAfterEpoch)"); + InvalidArgument("autoAdjustLR: Invalid learning rate search type. Valid values are (None | SearchBeforeEpoch | AdjustAfterEpoch)"); } template @@ -263,7 +263,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { m_zeroThresholdFor1Bit = configDataParallelSGD("useZeroThresholdFor1BitQuantization", "true"); if ((m_numGradientBits < 1) || (m_numGradientBits > (8 * sizeof(ElemType)))) { - throw std::invalid_argument("gradientBits must be in the range [1, 32] when using precision=float and in range [1, 64] when using precision=double!"); + InvalidArgument("gradientBits must be in the range [1, 32] when using precision=float and in range [1, 64] when using precision=double!"); } } @@ -393,21 +393,21 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (m_epochSize != requestDataSize && m_epochSize < m_mbSize[i]) { - throw std::invalid_argument("epoch size must be larger than mbsize."); + InvalidArgument("epoch size must be larger than mbsize."); } } if (m_autoLearnRateSearchType == LearningRateSearchAlgorithm::None && (learningRatesPerSample.size() == 0 && learningRatesPerMB.size() == 0)) { - throw std::invalid_argument("If autoLearnRateSearchType is false " + InvalidArgument("If autoLearnRateSearchType is false " "you must specify the learningRatesPerSample " "or learningRatesPerMB parameter."); } if (learningRatesPerSample.size() > 0 && learningRatesPerMB.size() > 0) { - throw std::invalid_argument("You specified both learningRatesPerSample " + InvalidArgument("You specified both learningRatesPerSample " "and learningRatesPerMB. Please comment " "out one of them."); } @@ -424,7 +424,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (momentumPerSample.size() > 0 && momentumPerMB.size() > 0) { - throw std::invalid_argument("You specified both momentumPerSample " + InvalidArgument("You specified both momentumPerSample " "and momentumPerMB. Please comment " "out one of them."); } @@ -579,7 +579,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { auto & sequenceCriterionNodes = GetTrainCriterionNodes(*sequenceNet); if (origCriterionNodes.size() == 0 || sequenceCriterionNodes.size() == 0) { - throw std::runtime_error("Training criterion node does not exist."); + RuntimeError("Training criterion node does not exist."); } replacedCriterionNodes.push_back(origCriterionNodes[0]); origNet.ReplaceFinalCriterionNode(origCriterionNodes[0]->NodeName(), sequenceCriterionNodes[0]); diff --git a/MachineLearning/CNTKSGDLib/SimpleEvaluator.h b/MachineLearning/CNTKSGDLib/SimpleEvaluator.h index 3de6b17f1..e1b106be7 100644 --- a/MachineLearning/CNTKSGDLib/SimpleEvaluator.h +++ b/MachineLearning/CNTKSGDLib/SimpleEvaluator.h @@ -75,7 +75,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { fprintf(stderr, "evalNodeNames are not specified, using all the default evalnodes and training criterion nodes.\n"); if (m_net.EvaluationNodes().size() == 0 && m_net.FinalCriterionNodes().size() == 0) - throw std::logic_error("There is no default evalnodes or training criterion node specified in the network."); + LogicError("There is no default evalnodes or training criterion node specified in the network."); for (int i = 0; i < m_net.EvaluationNodes().size(); i++) evalNodes.push_back(m_net.EvaluationNodes()[i]); @@ -90,7 +90,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const auto & node = m_net.GetNodeFromName(evalNodeNames[i]); m_net.BuildAndValidateSubNetwork(node); if (node->GetNumRows() != 1 || node->GetNumCols() != 1) - throw std::logic_error("The nodes passed to SimpleEvaluator::Evaluate function must be either eval or training criterion nodes (which evalues to 1x1 value)."); + LogicError("The nodes passed to SimpleEvaluator::Evaluate function must be either eval or training criterion nodes (which evalues to 1x1 value)."); evalNodes.push_back(node); } } diff --git a/MachineLearning/CNTKSGDLib/SimpleOutputWriter.h b/MachineLearning/CNTKSGDLib/SimpleOutputWriter.h index c60e1ef2b..24afef557 100644 --- a/MachineLearning/CNTKSGDLib/SimpleOutputWriter.h +++ b/MachineLearning/CNTKSGDLib/SimpleOutputWriter.h @@ -40,7 +40,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (m_verbosity > 0) fprintf (stderr, "OutputNodeNames are not specified, using the default outputnodes.\n"); if (m_net.OutputNodes().size() == 0) - throw std::logic_error("There is no default output node specified in the network."); + LogicError("There is no default output node specified in the network."); outputNodes = m_net.OutputNodes(); } @@ -120,7 +120,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { fprintf (stderr, "OutputNodeNames are not specified, using the default outputnodes.\n"); if (m_net.OutputNodes().size() == 0) - throw std::logic_error("There is no default output node specified in the network."); + LogicError("There is no default output node specified in the network."); outputNodes = m_net.OutputNodes(); } diff --git a/MachineLearning/SequenceTraining/latticeforwardbackward.cpp b/MachineLearning/SequenceTraining/latticeforwardbackward.cpp index bb64db9eb..8b4b300d7 100644 --- a/MachineLearning/SequenceTraining/latticeforwardbackward.cpp +++ b/MachineLearning/SequenceTraining/latticeforwardbackward.cpp @@ -50,13 +50,13 @@ public: } auto & buffer = heap.back(); if (elementsneeded > heap.back().size() - allocatedinlast) - throw std::logic_error ("newmatrix: allocation logic screwed up"); + LogicError("newmatrix: allocation logic screwed up"); // get our buffer into a handy vector-like thingy array_ref vecbuffer (&buffer[allocatedinlast], elementsneeded); // allocate in the current heap location matrices.resize (matrices.size() + 1); if (matrices.size()+1 > matrices.capacity()) - throw std::logic_error ("newmatrix: littlematrixheap cannot grow but was constructed with too small number of eements"); + LogicError("newmatrix: littlematrixheap cannot grow but was constructed with too small number of eements"); auto & matrix = matrices.back(); matrix = matrixfrombuffer (vecbuffer, rows, cols); allocatedinlast += elementsneeded; @@ -404,7 +404,7 @@ template static bool islogzero (FLOAT v) { return v < LOGZERO/2; } } if (exitbackpointer == invalidbp) - throw std::logic_error ("exitbackpointer came up empty"); + LogicError("exitbackpointer came up empty"); fwscore = exitscore; // score passed on to next unit fwbackpointer = exitbackpointer; // and accompanying backpointer js = je; @@ -433,7 +433,7 @@ template static bool islogzero (FLOAT v) { return v < LOGZERO/2; for (size_t t = te -1; t + 1 > ts; t--) { if (j < (int) js || j >= (int) je) - throw std::logic_error ("invalid backpointer resulting in state index out of range"); + LogicError("invalid backpointer resulting in state index out of range"); int bp = (int) backpointers(j,t); // save the backpointer before overwriting it (gammas and backpointers are aliases of each other) if (!returnsenoneids) // return binary gammas (for MMI; this mode is compatible with softalignmode) @@ -443,7 +443,7 @@ template static bool islogzero (FLOAT v) { return v < LOGZERO/2; thisedgealignmentsj[t] = (unsigned short) hmm.getsenoneid(j-js); if (bp == invalidbp) - throw std::logic_error ("deltabackpointer not initialized"); + LogicError("deltabackpointer not initialized"); j = bp; // trace back one step } @@ -451,7 +451,7 @@ template static bool islogzero (FLOAT v) { return v < LOGZERO/2; je = js; } if (j != -1) - throw std::logic_error ("invalid backpointer resulting in not reaching start of utterance when tracing back"); + LogicError("invalid backpointer resulting in not reaching start of utterance when tracing back"); assert (je == 0 && te == 0); // we return the full path score @@ -806,7 +806,7 @@ void lattice::forwardbackwardalign (parallelstate & parallelstate, if (edgeframes == 0) // dummy !NULL edge at end of lattice { if ((size_t) j != edges.size() -1) - throw std::runtime_error ("forwardbackwardalign: unxpected 0-frame edge (only allowed at very end)"); + RuntimeError("forwardbackwardalign: unxpected 0-frame edge (only allowed at very end)"); // note: abcs[j] is already initialized to be NULL in this case, which protects us from accidentally using it } else @@ -846,7 +846,7 @@ void lattice::forwardbackwardalign (parallelstate & parallelstate, if (parallelstate.enabled() && !parallelsil) // silence edge shall be process separately if not cuda and not PARALLEL_SIL { if (softalignstates) - throw std::logic_error ("forwardbackwardalign: parallelized version currently only handles hard alignments"); + LogicError("forwardbackwardalign: parallelized version currently only handles hard alignments"); if (minlogpp > LOGZERO) fprintf(stderr, "forwardbackwardalign: pruning not supported (we won't need it!) :)\n"); edgeacscores.resize (edges.size()); @@ -1157,14 +1157,14 @@ void lattice::mmierrorsignal (parallelstate & parallelstate, double minlogpp, co const msra::math::ssematrixbase & logLLs, const msra::asr::simplesenonehmm & hset, const float lmf, const float wp, const float amf) { if (transcript[0].firstframe != 0) // TODO: should we store the #frames instead? Then we can validate the total duration - throw std::logic_error ("scoregroundtruth: first transcript[] token does not start at frame 0"); + LogicError("scoregroundtruth: first transcript[] token does not start at frame 0"); // get the silence models, since they are treated specially const size_t numframes = logLLs.cols(); const auto & sil = hset.gethmm (hset.gethmmid ("sil")); const auto & sp = hset.gethmm (hset.gethmmid ("sp")); if (sp.numstates != 1 || sil.numstates != 3) - throw std::runtime_error ("scoregroundtruth: only supports 1-state /sp/ and 3-state /sil/ tied to /sp/"); + RuntimeError("scoregroundtruth: only supports 1-state /sp/ and 3-state /sil/ tied to /sp/"); const size_t silst = sp.senoneids[0]; // loop over words @@ -1174,7 +1174,7 @@ void lattice::mmierrorsignal (parallelstate & parallelstate, double minlogpp, co size_t ts = transcript[i].firstframe; size_t te = ((size_t) i+1 < transcript.size()) ? transcript[i+1].firstframe : numframes; if (ts >= te) - throw std::logic_error ("scoregroundtruth: transcript[] tokens out of order"); + LogicError("scoregroundtruth: transcript[] tokens out of order"); // acoustic score: loop over frames const msra::asr::simplesenonehmm::transP * prevtransP = NULL; // previous transP int prevs = -1; // previous state index @@ -1202,7 +1202,7 @@ void lattice::mmierrorsignal (parallelstate & parallelstate, double minlogpp, co int transPindex = hset.senonetransP (senoneid); int sindex = hset.senonestate (senoneid); if (transPindex == -1 || sindex == -1) - throw std::runtime_error ("scoregroundtruth: failed to resolve ambiguous senone " + (string) hset.getsenonename (senoneid)); + RuntimeError("scoregroundtruth: failed to resolve ambiguous senone " + (string) hset.getsenonename (senoneid)); transP = &hset.transPs[transPindex]; s = sindex; } @@ -1364,7 +1364,7 @@ double lattice::forwardbackward (parallelstate & parallelstate, const msra::math backpointers thisbackpointers (*this, hset); // memory for forwardbackward if (info.numframes != logLLs.cols()) - throw std::logic_error (msra::strfun::strprintf ("forwardbackward: #frames mismatch between lattice (%d) and LLs (%d)", (int) info.numframes, (int) logLLs.cols())); + LogicError(msra::strfun::strprintf ("forwardbackward: #frames mismatch between lattice (%d) and LLs (%d)", (int) info.numframes, (int) logLLs.cols())); // TODO: the following checks should throw, but I don't dare in case this will crash a critical job... if we never see this warning, then if (info.numframes != uids.size()) fprintf (stderr, "forwardbackward: #frames mismatch between lattice (%d) and uids (%d)\n", (int) info.numframes, (int) uids.size()); diff --git a/MachineLearning/SequenceTraining/parallelforwardbackward.cpp b/MachineLearning/SequenceTraining/parallelforwardbackward.cpp index 4da2af09f..f25dbfbee 100644 --- a/MachineLearning/SequenceTraining/parallelforwardbackward.cpp +++ b/MachineLearning/SequenceTraining/parallelforwardbackward.cpp @@ -373,7 +373,7 @@ namespace msra { namespace lattices { // only copy once // TODO: this can only be cached once --but there is no check whether a different model is passed if (lr3transPgpu->size() > 0) - throw std::logic_error ("cachehset: cannot bind to multiple model sets"); + LogicError("cachehset: cannot bind to multiple model sets"); auto_timer copyhmms; // transPs @@ -424,18 +424,18 @@ namespace msra { namespace lattices { { hmmscpuforgpu[i].numstates = (unsigned char) hmms[i].getnumstates(); if (hmmscpuforgpu[i].numstates != hmms[i].getnumstates()) - throw std::logic_error("parallelforwardbackwardalign : hmms.numstates is out of range of unsigned char"); + LogicError("parallelforwardbackwardalign : hmms.numstates is out of range of unsigned char"); for (size_t m = 0; m < hmmscpuforgpu[i].numstates; m++) { hmmscpuforgpu[i].senoneids[m] = (unsigned short) hmms[i].getsenoneid(m); if (hmmscpuforgpu[i].senoneids[m] != hmms[i].getsenoneid(m)) - throw std::logic_error("parallelforwardbackwardalign : hmms.numstates is out of range of unsigned short"); + LogicError("parallelforwardbackwardalign : hmms.numstates is out of range of unsigned short"); } hmmscpuforgpu[i].transPindex = (unsigned short) hmms[i].gettransPindex(); if (hmmscpuforgpu[i].transPindex != hmms[i].gettransPindex()) - throw std::logic_error("parallelforwardbackwardalign : hmms.transPindex is out of range of unsigned short"); + LogicError("parallelforwardbackwardalign : hmms.transPindex is out of range of unsigned short"); } hmmsgpu->assign (hmmscpuforgpu, true/*sync*/); // need to sync if we free the memory right after (and we won't buy much from async) copyhmms.show("copyhmms"); // 246.776281 ms --note: forgot hmmsgpu @@ -455,7 +455,7 @@ namespace msra { namespace lattices { void validatehset (const msra::asr::simplesenonehmm & hset) { if (hmmsgpu->size() != hset.hmms.size() || lr3transPgpu->size() != hset.transPs.size()) - throw std::logic_error ("validatehset: not bound to hset or to wrong hset"); + LogicError("validatehset: not bound to hset or to wrong hset"); } // current lattice diff --git a/Math/Math/CPUMatrix.cpp b/Math/Math/CPUMatrix.cpp index 407637ac2..46520e6f3 100644 --- a/Math/Math/CPUMatrix.cpp +++ b/Math/Math/CPUMatrix.cpp @@ -241,7 +241,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix CPUMatrix::ColumnSlice(size_t startColumn, size_t numCols) const { //if (numCols == 0) - // throw std::logic_error("The slice cannot have 0 columns."); + // LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int)startColumn, (int)numCols, (int)m_numCols); @@ -264,7 +264,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignColumnSlice(const CPUMatrix& fromMatrix, size_t startColumn, size_t numCols) { //if (numCols == 0) - // throw std::logic_error("The slice cannot have 0 columns."); + // LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > fromMatrix.m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int)startColumn, (int)numCols, (int)fromMatrix.m_numCols); @@ -285,13 +285,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::SetColumnSlice(const CPUMatrix& fromMatrix, size_t startColumn, size_t numCols) { //if (numCols == 0) - // throw std::logic_error("The slice cannot have 0 columns."); + // LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > m_numCols) - throw std::logic_error("The slice is out of range of the destination matrix."); + LogicError("The slice is out of range of the destination matrix."); if (numCols > fromMatrix.GetNumCols()) InvalidArgument("The slice (%d) is out of range of the source matrix (%d).", (int)numCols, (int)fromMatrix.GetNumCols()); if (m_numRows != fromMatrix.m_numRows) - throw std::logic_error("The number of rows in source and destination matrices do not match"); + LogicError("The number of rows in source and destination matrices do not match"); //SetOwnBuffer(false); memcpy(m_pArray + startColumn*m_numRows, fromMatrix.m_pArray, numCols*m_numRows*sizeof(ElemType)); @@ -304,13 +304,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignToRowSliceValuesOf(const CPUMatrix& a, const size_t startIndex, const size_t numRows) { if (a.GetNumRows() != numRows) - throw std::logic_error("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); + LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) - throw std::logic_error("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); + LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) - throw std::logic_error("AddToRowSliceValuesOf: columns does not match."); + LogicError("AddToRowSliceValuesOf: columns does not match."); long n = (long)a.GetNumCols(), m = (long)numRows; @@ -342,10 +342,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignRowSliceValuesOf(const CPUMatrix& a, const size_t startIndex, const size_t numRows) { //if (a.IsEmpty()) - // throw std::logic_error("AssignRowSliceValuesOf: input matrix a is empty."); + // LogicError("AssignRowSliceValuesOf: input matrix a is empty."); if (startIndex + numRows > a.GetNumRows()) - throw std::logic_error("AssignRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); + LogicError("AssignRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); Resize(numRows, a.GetNumCols()); @@ -381,16 +381,16 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AddToRowSliceValuesOf(const CPUMatrix& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) - throw std::logic_error("AddToRowSliceValuesOf: input matrix a is empty."); + LogicError("AddToRowSliceValuesOf: input matrix a is empty."); if (a.GetNumRows() != numRows) - throw std::logic_error("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); + LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) - throw std::logic_error("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); + LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) - throw std::logic_error("AddToRowSliceValuesOf: columns does not match."); + LogicError("AddToRowSliceValuesOf: columns does not match."); long n=(long)a.GetNumCols(), m=(long)numRows; @@ -422,16 +422,16 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AddWithRowSliceValuesOf(const CPUMatrix& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) - throw std::logic_error("AddWithRowSliceValuesOf: input matrix a is empty."); + LogicError("AddWithRowSliceValuesOf: input matrix a is empty."); if (GetNumRows() != numRows) - throw std::logic_error("AddWithRowSliceValuesOf: GetNumRows() != numRows."); + LogicError("AddWithRowSliceValuesOf: GetNumRows() != numRows."); if (startIndex + numRows > a.GetNumRows()) - throw std::logic_error("AddWithRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); + LogicError("AddWithRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); if (a.GetNumCols() != GetNumCols()) - throw std::logic_error("AddWithRowSliceValuesOf: columns does not match."); + LogicError("AddWithRowSliceValuesOf: columns does not match."); long n = (long)a.GetNumCols(), m = (long)numRows; @@ -532,10 +532,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignRepeatOf(const CPUMatrix& a, const size_t numRowRepeats, const size_t numColRepeats) { if (this == &a) - throw std::logic_error("AssignRepeatOf: a is the same as [this]. Does not support inplace repeat."); + LogicError("AssignRepeatOf: a is the same as [this]. Does not support inplace repeat."); if (a.IsEmpty()) - throw std::logic_error("AssignRepeatOf: Matrix a is empty."); + LogicError("AssignRepeatOf: Matrix a is empty."); Resize(a.GetNumRows() * numRowRepeats, a.GetNumCols() * numColRepeats); long n = (long)a.GetNumCols(), m = (long)a.GetNumRows(); @@ -576,10 +576,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AddToRowRepeatValuesOf(const CPUMatrix& a, const size_t numRepeats) { if (a.IsEmpty()) - throw std::logic_error("AddToRowRepeatValuesOf: input matrix a is empty."); + LogicError("AddToRowRepeatValuesOf: input matrix a is empty."); if (a.GetNumRows() != GetNumRows() * numRepeats) - throw std::logic_error("AddToRowRepeatValuesOf: a.GetNumRows() != GetNumRows() * numRepeats."); + LogicError("AddToRowRepeatValuesOf: a.GetNumRows() != GetNumRows() * numRepeats."); long n = (long)a.GetNumCols(), m = (long)GetNumRows(); @@ -630,7 +630,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix CPUMatrix::Transpose() { if (IsEmpty()) - throw std::logic_error("Transpose: Matrix is empty."); + LogicError("Transpose: Matrix is empty."); CPUMatrix c; c.AssignTransposeOf(*this); @@ -641,10 +641,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignTransposeOf (const CPUMatrix& a) { if (this == &a) - throw std::logic_error("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); + LogicError("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); if (a.IsEmpty()) - throw std::logic_error("AssignTransposeOf: Matrix a is empty."); + LogicError("AssignTransposeOf: Matrix a is empty."); Resize(a.GetNumCols(), a.GetNumRows()); long n=(long)a.GetNumCols(), m=(long)a.GetNumRows(); @@ -676,7 +676,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetValue(const ElemType v) { if (IsEmpty()) - throw std::logic_error("SetValue: Matrix is empty."); + LogicError("SetValue: Matrix is empty."); bool isFinite = std::numeric_limits::is_integer || std::isfinite((double)v); if (isFinite && v == 0) { @@ -706,7 +706,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetColumn(const ElemType* colPointer, size_t j) { if (IsEmpty()) - throw std::logic_error("SetColumn: Matrix is empty."); + LogicError("SetColumn: Matrix is empty."); if (colPointer==NULL) return; @@ -733,7 +733,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetColumn(const ElemType val, size_t j) { if (IsEmpty()) - throw std::logic_error("SetColumn: Matrix is empty."); + LogicError("SetColumn: Matrix is empty."); auto& us = *this; long m=(long)GetNumRows(); @@ -757,7 +757,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetColumn(const CPUMatrix& valMat, size_t j) { if (IsEmpty()) - throw std::logic_error("SetColumn: Matrix is empty."); + LogicError("SetColumn: Matrix is empty."); assert(valMat.GetNumRows() == GetNumRows() && valMat.GetNumCols() == 1) ; auto& us = *this; @@ -792,7 +792,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetValue(const size_t numRows, const size_t numCols, ElemType *pArray, const size_t matrixFlags) { if (pArray == nullptr) - throw std::invalid_argument("Invalid pArray."); + InvalidArgument("Invalid pArray."); m_format = matrixFormatDense; m_computeDevice = CPUDEVICE; @@ -816,7 +816,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (IsEmpty()) { - throw std::invalid_argument("NumRows or NumCols is 0. Nothing to copy"); + InvalidArgument("NumRows or NumCols is 0. Nothing to copy"); } else { @@ -863,10 +863,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetDiagonalValue(const ElemType v) { if (IsEmpty()) - throw std::logic_error("SetDiagonalValue: Matrix is empty."); + LogicError("SetDiagonalValue: Matrix is empty."); if (GetNumRows() != GetNumCols()) - throw std::logic_error("SetDiagonalValue: NumRows and NumCols do not agree."); + LogicError("SetDiagonalValue: NumRows and NumCols do not agree."); auto& us = *this; long m=(long)GetNumRows(); @@ -890,18 +890,18 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetDiagonalValue(const CPUMatrix& vector) { if (IsEmpty() || vector.IsEmpty()) - throw std::logic_error("SetDiagonalValue: Matrix is empty."); + LogicError("SetDiagonalValue: Matrix is empty."); if (GetNumRows() != GetNumCols()) - throw std::logic_error("SetDiagonalValue: NumRows and NumCols do not agree."); + LogicError("SetDiagonalValue: NumRows and NumCols do not agree."); if (vector.GetNumRows() != 1 && vector.GetNumCols() != 1) - throw std::logic_error("SetDiagonalValue: input vector must be a vector."); + LogicError("SetDiagonalValue: input vector must be a vector."); if (vector.GetNumElements() == 1) //reduce to simple form SetDiagonalValue(vector(0,0)); else if (vector.GetNumRows() != GetNumRows()) - throw std::logic_error("SetDiagonalValue: input vector's dimension does not agree with [this]."); + LogicError("SetDiagonalValue: input vector's dimension does not agree with [this]."); else { auto& us = *this; @@ -948,7 +948,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetUniformRandomValue(const ElemType low, const ElemType high, unsigned long seed) { if (IsEmpty()) - throw std::logic_error("SetUniformRandomValue: Matrix is empty."); + LogicError("SetUniformRandomValue: Matrix is empty."); #ifdef _MSC_VER // TODO: check if available under GCC/Linux std::ranlux64_base_01 generator; @@ -979,10 +979,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) - throw std::invalid_argument("SetUniformRandomValue: sigma must be a positive value."); + InvalidArgument("SetUniformRandomValue: sigma must be a positive value."); if (IsEmpty()) - throw std::logic_error("SetUniformRandomValue: Matrix is empty."); + LogicError("SetUniformRandomValue: Matrix is empty."); auto& us = *this; #ifdef _MSC_VER // TODO: check if available under GCC/Linux @@ -1003,10 +1003,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::AddGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) - throw std::invalid_argument("SetUniformRandomValue: sigma must be a positive value."); + InvalidArgument("SetUniformRandomValue: sigma must be a positive value."); if (IsEmpty()) - throw std::logic_error("SetUniformRandomValue: Matrix is empty."); + LogicError("SetUniformRandomValue: Matrix is empty."); auto& us = *this; #ifdef _MSC_VER // TODO: check if available under GCC/Linux @@ -1043,7 +1043,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SetUniformRandomMask(const ElemType maskRate, const ElemType scaleValue, unsigned long seed) { if (IsEmpty()) - throw std::logic_error("SetUniformRandomValue: Matrix is empty."); + LogicError("SetUniformRandomValue: Matrix is empty."); auto& us = *this; #ifdef _MSC_VER // TODO: check if available under GCC/Linux @@ -1296,7 +1296,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { assert (numRows*numCols == GetNumElements()); if (numRows*numCols != GetNumElements()) - throw std::invalid_argument("Reshape: Total number of elements does not match."); + InvalidArgument("Reshape: Total number of elements does not match."); m_numRows = numRows; m_numCols = numCols; @@ -1323,7 +1323,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (numElements > 0) { if (!OwnBuffer()) - throw logic_error("Resize: Resizing an matrix you don't own is not supported."); + LogicError("Resize: Resizing an matrix you don't own is not supported."); pArray = NewArray(numElements); } // success: update the object @@ -1423,7 +1423,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignSumOf(const ElemType alpha, const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSumOf: Matrix a is empty."); + LogicError("AssignSumOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -1740,11 +1740,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignElementProductOf (const CPUMatrix& a, const CPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOf: Matrix is empty."); + LogicError("AssignElementProductOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("AssignElementProductOf: The input matrix dimensions do not match."); + InvalidArgument("AssignElementProductOf: The input matrix dimensions do not match."); auto& us=*this; if (this != &a) @@ -1776,14 +1776,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AddElementProductOf (const CPUMatrix& a, const CPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AddElementProductOf: Matrix is empty."); + LogicError("AddElementProductOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("AddElementProductOf : The input matrix dimensions do not match."); + InvalidArgument("AddElementProductOf : The input matrix dimensions do not match."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == GetNumCols())) - throw std::invalid_argument("AddElementProductOf : The input matrix dimensions do not match [this]."); + InvalidArgument("AddElementProductOf : The input matrix dimensions do not match [this]."); auto& us=*this; @@ -1816,11 +1816,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignElementDivisionOf (const CPUMatrix& a, const CPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementDivisionOf: Matrix is empty."); + LogicError("AssignElementDivisionOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("AssignElementDivisionOf : The input matrix dimensions do not match."); + InvalidArgument("AssignElementDivisionOf : The input matrix dimensions do not match."); auto& us=*this; if (this != &a) @@ -1847,11 +1847,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::ColumnElementMultiplyWith(const CPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("ColumnElementMultiplyWith: Matrix is empty."); + LogicError("ColumnElementMultiplyWith: Matrix is empty."); assert (a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) - throw std::invalid_argument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); + InvalidArgument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); auto& us=*this; @@ -1882,11 +1882,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::RowElementMultiplyWith(const CPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("RowElementMultiplyWith: Matrix is empty."); + LogicError("RowElementMultiplyWith: Matrix is empty."); assert (a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols()); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) - throw std::invalid_argument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); + InvalidArgument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); auto& us=*this; @@ -1917,11 +1917,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::RowElementDivideBy(const CPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("RowElementDivideBy: Matrix is empty."); + LogicError("RowElementDivideBy: Matrix is empty."); assert(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols()); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) - throw std::invalid_argument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); + InvalidArgument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); auto& us = *this; @@ -1956,11 +1956,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::ColumnElementDivideBy(const CPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("ColumnElementDivideBy: Matrix is empty."); + LogicError("ColumnElementDivideBy: Matrix is empty."); assert (a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) - throw std::invalid_argument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); + InvalidArgument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); auto& us=*this; @@ -1999,7 +1999,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType smallValue = EPS_IN_INVERSE; if (a.IsEmpty()) - throw std::logic_error("AssignElementInverseOf: Matrix a is empty."); + LogicError("AssignElementInverseOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2030,7 +2030,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignSigmoidOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSigmoidOf: Matrix a is empty."); + LogicError("AssignSigmoidOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2061,7 +2061,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignLinearRectifierDerivativeOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignLinearRectifierDerivativeOf: Matrix a is empty."); + LogicError("AssignLinearRectifierDerivativeOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2100,7 +2100,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignSigmoidDerivativeOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSigmoidDerivativeOf: Matrix a is empty."); + LogicError("AssignSigmoidDerivativeOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2148,7 +2148,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignTanhOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignTanhOf: Matrix a is empty."); + LogicError("AssignTanhOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2188,7 +2188,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignLogSoftmaxOf (const CPUMatrix& a, const bool isColWise) { if (a.IsEmpty()) - throw std::logic_error("AssignLogSoftmaxOf: Matrix a is empty."); + LogicError("AssignLogSoftmaxOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2249,7 +2249,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignSqrtOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSqrtOf: Matrix a is empty."); + LogicError("AssignSqrtOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2289,7 +2289,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignExpOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignExpOf: Matrix a is empty."); + LogicError("AssignExpOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2329,7 +2329,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignAbsOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignAbsOf: Matrix a is empty."); + LogicError("AssignAbsOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2375,7 +2375,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignLogOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignLogOf: Matrix a is empty."); + LogicError("AssignLogOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2400,7 +2400,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignLog10Of (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignLogOf: Matrix a is empty."); + LogicError("AssignLogOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2411,7 +2411,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { const ElemType v = a(i,j); if (v <= 0) - throw std::logic_error("AssignLogOf: Log can only applied to numbers larger than 0."); + LogicError("AssignLogOf: Log can only applied to numbers larger than 0."); else if (v < EPS_IN_LOG) { us(i,j) = LOG10_OF_EPS_IN_LOG; @@ -2435,7 +2435,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignCosineOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignCosineOf: Matrix a is empty."); + LogicError("AssignCosineOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2462,7 +2462,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignNegativeSineOf (const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignCosineOf: Matrix a is empty."); + LogicError("AssignCosineOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2484,7 +2484,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::InplaceTruncateBottom (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateBottom: Matrix is empty."); + LogicError("InplaceTruncateBottom: Matrix is empty."); auto& us=*this; @@ -2522,7 +2522,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::InplaceTruncate (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncate: Matrix is empty."); + LogicError("InplaceTruncate: Matrix is empty."); auto& us=*this; ElemType locThresholdPos = abs(threshold); @@ -2573,7 +2573,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::InplaceSoftThreshold(const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncate: Matrix is empty."); + LogicError("InplaceTruncate: Matrix is empty."); long m = (long)GetNumElements(); @@ -2627,7 +2627,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignTruncateBottomOf (const CPUMatrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateBottomOf: Matrix a is empty."); + LogicError("AssignTruncateBottomOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2650,7 +2650,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::InplaceTruncateTop (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateTop: Matrix is empty."); + LogicError("InplaceTruncateTop: Matrix is empty."); auto& us=*this; @@ -2669,7 +2669,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignTruncateTopOf (const CPUMatrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateTopOf: Matrix a is empty."); + LogicError("AssignTruncateTopOf: Matrix a is empty."); auto& us=*this; if (this != &a) @@ -2694,7 +2694,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::SetToZeroIfAbsLessThan (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("SetToZeroIfAbsLessThan: Matrix is empty."); + LogicError("SetToZeroIfAbsLessThan: Matrix is empty."); auto& us=*this; @@ -2713,7 +2713,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUMatrix::SumOfAbsElements () const { if (IsEmpty()) - throw std::logic_error("SumOfAbsElements: Matrix is empty."); + LogicError("SumOfAbsElements: Matrix is empty."); if (sizeof(ElemType) == sizeof(double)) { @@ -2739,7 +2739,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUMatrix::SumOfElements () const { if (IsEmpty()) - throw std::logic_error("SumOfElements: Matrix is empty."); + LogicError("SumOfElements: Matrix is empty."); ElemType sum=0; long m=(long)GetNumElements(); // note: OpenMP requires loop indices to be long, not size_t @@ -2763,7 +2763,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignSumOfElements(const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSumOfElements: Matrix a is empty."); + LogicError("AssignSumOfElements: Matrix a is empty."); auto& us=*this; us.Resize(1,1); @@ -2783,7 +2783,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::VectorSum(const CPUMatrix& a, CPUMatrix& c, const bool isColWise) { if (a.IsEmpty()) - throw std::logic_error("VectorSum: Input matrix a is empty."); + LogicError("VectorSum: Input matrix a is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -2828,7 +2828,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::VectorNorm1(CPUMatrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNorm1: Matrix is empty."); + LogicError("VectorNorm1: Matrix is empty."); auto& us=*this; @@ -2886,7 +2886,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::VectorNorm2(CPUMatrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNorm2: Matrix is empty."); + LogicError("VectorNorm2: Matrix is empty."); auto& us=*this; @@ -2969,7 +2969,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::VectorNormInf(CPUMatrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNormInf: Matrix is empty."); + LogicError("VectorNormInf: Matrix is empty."); auto& us=*this; @@ -3032,12 +3032,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignKhatriRaoProductOf(const CPUMatrix& a, const CPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignKhatriRaoProductOf: Matrix is empty."); + LogicError("AssignKhatriRaoProductOf: Matrix is empty."); long cols = (long) a.GetNumCols(); assert(cols == b.GetNumCols()); if (cols != b.GetNumCols()) - throw invalid_argument("a.GetNumCols() != b.GetNumCols()"); + InvalidArgument("a.GetNumCols() != b.GetNumCols()"); long rowsA = (long) a.GetNumRows(); long rowsB = (long) b.GetNumRows(); @@ -3071,22 +3071,22 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AddColumnReshapeProductOf(const CPUMatrix& a, const CPUMatrix& b, const bool transposeAColumn) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AddColumnReshapeProductOf: Matrix is empty."); + LogicError("AddColumnReshapeProductOf: Matrix is empty."); long cols = (long) a.GetNumCols(); assert(cols == b.GetNumCols()); if (cols != b.GetNumCols()) - throw invalid_argument("AddColumnReshapeProductOf: a.GetNumCols() != b.GetNumCols()"); + InvalidArgument("AddColumnReshapeProductOf: a.GetNumCols() != b.GetNumCols()"); long rowsA = (long) a.GetNumRows(); long rowsB = (long) b.GetNumRows(); if (rowsA % rowsB != 0) - throw invalid_argument("AddColumnReshapeProductOf: number of rows in a should be multiples of that in b."); + InvalidArgument("AddColumnReshapeProductOf: number of rows in a should be multiples of that in b."); long rowsC = rowsA / rowsB; if (rowsC != GetNumRows() || cols != GetNumCols()) - throw invalid_argument("AddColumnReshapeProductOf: This matrix does not have the right size."); + InvalidArgument("AddColumnReshapeProductOf: This matrix does not have the right size."); auto & us = *this; @@ -3152,7 +3152,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUMatrix::FrobeniusNorm() const { if (IsEmpty()) - throw std::logic_error("FrobeniusNorm: Matrix is empty."); + LogicError("FrobeniusNorm: Matrix is empty."); ElemType v = 0; @@ -3177,7 +3177,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignFrobeniusNormOf(const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignFrobeniusNormOf: Matrix a is empty."); + LogicError("AssignFrobeniusNormOf: Matrix a is empty."); auto& us=*this; us.Resize(1,1); @@ -3190,7 +3190,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUMatrix::MatrixNormInf() const { if (IsEmpty()) - throw std::logic_error("MatrixNormInf: Matrix is empty."); + LogicError("MatrixNormInf: Matrix is empty."); auto& us=*this; @@ -3210,7 +3210,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUMatrix::MatrixNorm0() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm0: Matrix is empty."); + LogicError("MatrixNorm0: Matrix is empty."); auto& us=*this; @@ -3233,7 +3233,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUMatrix::MatrixNorm1() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm1: Matrix is empty."); + LogicError("MatrixNorm1: Matrix is empty."); auto& us=*this; @@ -3250,7 +3250,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignSignOf(const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSignOf: Matrix a is empty."); + LogicError("AssignSignOf: Matrix a is empty."); auto& us = *this; if (this != &a) @@ -3276,7 +3276,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AddSignOf(const CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AddSignOf: Matrix a is empty."); + LogicError("AddSignOf: Matrix a is empty."); auto& us = *this; if (this != &a) @@ -3302,7 +3302,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::VectorMax(CPUMatrix& maxIndexes, CPUMatrix& maxValues, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorMax: Matrix is empty."); + LogicError("VectorMax: Matrix is empty."); auto& us=*this; const int m = (int)GetNumRows(); @@ -3361,7 +3361,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::VectorMin(CPUMatrix& minIndexes, CPUMatrix& minValues, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorMin: Matrix is empty."); + LogicError("VectorMin: Matrix is empty."); auto& us=*this; const int m = (int)GetNumRows(); @@ -3421,7 +3421,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignNumOfDiff(const CPUMatrix& a, const CPUMatrix& b) { if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) - throw std::invalid_argument ("AssignNumOfDiff: a and b must have same dimension."); + InvalidArgument("AssignNumOfDiff: a and b must have same dimension."); ElemType n = 0; foreach_coord(i,j,a) @@ -3444,10 +3444,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::Print(const char* matrixName, size_t rowStart, size_t rowEnd, size_t colStart, size_t colEnd) const { if (IsEmpty()) - throw std::logic_error("Print: Matrix is empty."); + LogicError("Print: Matrix is empty."); if (rowEnd >= GetNumRows() || colEnd >= GetNumCols()) - throw std::invalid_argument("Index out of range."); + InvalidArgument("Index out of range."); if (matrixName != nullptr) fprintf (stderr, "\n###### %s (%lu, %lu) ######\n", matrixName, GetNumRows(), GetNumCols()); @@ -3476,14 +3476,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { template void CPUMatrix::ReadFromFile(FILE*, const char * /*matrixName*/) { - throw std::runtime_error("not implemented."); + RuntimeError("not implemented."); } //matrixName is used to verify that correct matrix is read. template void CPUMatrix::WriteToFile(FILE*, const char * /*matrixName*/) { - throw std::runtime_error("not implemented."); + RuntimeError("not implemented."); } //assume each column is an input sample. Each sample is stored in [channel, row, col] (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11) @@ -3842,7 +3842,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType beta, CPUMatrix& c) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("MultiplyAndWeightedAdd: one of the input matrix is empty."); + LogicError("MultiplyAndWeightedAdd: one of the input matrix is empty."); int m, n, k, l; int lda, ldb, ldc; @@ -3902,7 +3902,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && k>0 && l>0 && n>0); //converting from size_t to int may cause overflow assert (k == l); if (k != l) - throw std::invalid_argument("CPUMatrix::MultiplyAndWeightedAdd : The inner dimensions of a and b must match."); + InvalidArgument("CPUMatrix::MultiplyAndWeightedAdd : The inner dimensions of a and b must match."); c.Resize(m,n); ldc = (int)c.GetNumRows(); @@ -3934,7 +3934,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::SVD(const CPUMatrix& A, CPUMatrix& SIGMA, CPUMatrix& U, CPUMatrix& VT, CPUMatrix& W) { if (A.IsEmpty()) - throw std::logic_error("SVD: input matrix is empty."); + LogicError("SVD: input matrix is empty."); int info; int m, n, lda, ldu, ldvt; @@ -4152,7 +4152,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::ScaleAndAdd(ElemType alpha, const CPUMatrix& a, CPUMatrix& c) { if (a.IsEmpty() || c.IsEmpty()) - throw std::logic_error("ScaleAndAdd: one of the input matrices is empty."); + LogicError("ScaleAndAdd: one of the input matrices is empty."); if (a.GetNumRows() != 1 && a.GetNumCols() != 1) // a is not a col or row vector { @@ -4165,7 +4165,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && n>0 && len>0); //converting from size_t to int may cause overflow assert ((int)c.GetNumRows() == m && (int)c.GetNumCols() == n); if ((int)c.GetNumRows() != m || (int)c.GetNumCols() != n) - throw std::invalid_argument("Dimension of matrix c does not match dimension of matrix a."); + InvalidArgument("Dimension of matrix c does not match dimension of matrix a."); if (sizeof(ElemType) == sizeof(double)) { @@ -4213,7 +4213,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { int m = (int)c.GetNumRows(); assert (m == (int)a.GetNumRows()); if (m != (int)a.GetNumRows()) - throw std::invalid_argument("To add column vector, rows should match."); + InvalidArgument("To add column vector, rows should match."); if (sizeof(ElemType) == sizeof(double)) { @@ -4247,7 +4247,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { int n = (int)c.GetNumCols(); assert (n == (int)a.GetNumCols()); if (n != (int)a.GetNumCols()) - throw std::invalid_argument("To add row vector, cols should match."); + InvalidArgument("To add row vector, cols should match."); if (sizeof(ElemType) == sizeof(double)) { @@ -4292,11 +4292,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumRows() == c.GetNumRows() && a.GetNumCols() == b.GetNumCols() && a.GetNumCols() == c.GetNumCols())) { - throw std::invalid_argument("AddScaledDifference: a, b, and c must have same dimension."); + InvalidArgument("AddScaledDifference: a, b, and c must have same dimension."); } if (a.IsEmpty()) - throw std::logic_error("AddScaledDifference: Input matrix a is empty."); + LogicError("AddScaledDifference: Input matrix a is empty."); long m=(long)c.GetNumElements(); #pragma omp parallel for @@ -4328,11 +4328,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) { - throw std::invalid_argument("AssignScaledDifference: a, b must have same dimension."); + InvalidArgument("AssignScaledDifference: a, b must have same dimension."); } if (a.IsEmpty()) - throw std::logic_error("AssignScaledDifference: Input matrix a is empty."); + LogicError("AssignScaledDifference: Input matrix a is empty."); if (&c != &a && &c != &b) c.Resize(a.GetNumRows(), a.GetNumCols()); @@ -4360,7 +4360,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (ai >= a.GetNumRows() || aj >=a.GetNumCols() || ci >= c.GetNumRows() || cj >=c.GetNumCols()) - throw std::invalid_argument("AddElementToElement: index out of range."); + InvalidArgument("AddElementToElement: index out of range."); c(ci, cj) += a(ai, aj); } @@ -4371,7 +4371,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { //{ // if (ai >= a.GetNumRows() || aj >=a.GetNumCols() || // ci >= c.GetNumRows() || cj >=c.GetNumCols()) - // throw std::invalid_argument("AddElementToElement: index out of range."); + // InvalidArgument("AddElementToElement: index out of range."); // // ElemType v = a(ai,aj); // c(ci, cj) += ((v < EPS_IN_LOG) ? LOG_OF_EPS_IN_LOG : log(v)); @@ -4383,7 +4383,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (ai >= a.GetNumRows() || aj >=a.GetNumCols() || ci >= c.GetNumRows() || cj >=c.GetNumCols()) - throw std::invalid_argument("AssignElementToElement: index out of range."); + InvalidArgument("AssignElementToElement: index out of range."); c(ci, cj) = a(ai, aj); } @@ -4399,7 +4399,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { assert(alpha.GetNumElements() == 1); if (!(alpha.GetNumElements() == 1)) - throw std::invalid_argument("AddScaledDifference: alpha must be a 1X1 matrix."); + InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); AddScaledDifference(alpha(0,0), a, b, c); } @@ -4415,7 +4415,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { assert(alpha.GetNumElements() == 1); if (!(alpha.GetNumElements() == 1)) - throw std::invalid_argument("AddScaledDifference: alpha must be a 1X1 matrix."); + InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); AssignScaledDifference(alpha(0,0), a, b, c); } @@ -4427,7 +4427,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::Scale(ElemType alpha, const CPUMatrix& a, CPUMatrix& c) { if (a.IsEmpty()) - throw std::logic_error("Scale: Input matrix a is empty."); + LogicError("Scale: Input matrix a is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -4459,7 +4459,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::Scale(ElemType alpha, CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("Scale: Input matrix a is empty."); + LogicError("Scale: Input matrix a is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -4494,7 +4494,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::Scale(CPUMatrix alpha, CPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("Scale: Input matrix a is empty."); + LogicError("Scale: Input matrix a is empty."); if (alpha.GetNumElements()!=1) LogicError("Matrix alpha must be 1x1"); CPUMatrix::Scale(alpha(0,0),a); @@ -4504,7 +4504,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::InnerProduct (const CPUMatrix& a, const CPUMatrix& b, CPUMatrix& c, const bool isColWise) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProduct: one of the input matrices is empty."); + LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -4514,7 +4514,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert (m==k && n==l); //converting from size_t to int may cause overflow if (m!=k || n!=l) - throw std::invalid_argument("InnerProduct: Matrices a and b should have same dimension."); + InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); if ((isColWise && m == 1) || !isColWise && n == 1) //in this case it's equivalent to element-wise product { @@ -4587,7 +4587,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUMatrix::InnerProductOfMatrices(const CPUMatrix& a, const CPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProductOfMatrices: one of the input matrices is empty."); + LogicError("InnerProductOfMatrices: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -4597,7 +4597,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert (m==k && n==l); //converting from size_t to int may cause overflow if (m!=k || n!=l) - throw std::invalid_argument("InnerProductOfMatrices: Matrices a and b should have same dimension."); + InvalidArgument("InnerProductOfMatrices: Matrices a and b should have same dimension."); if (sizeof(ElemType) == sizeof(double)) { @@ -4622,7 +4622,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::ElementWisePower (ElemType alpha, const CPUMatrix& a, CPUMatrix& c) { if (a.IsEmpty()) - throw std::logic_error("Scale: The input matrix a is empty."); + LogicError("Scale: The input matrix a is empty."); c.Resize(a.GetNumRows(), a.GetNumCols()); @@ -4656,7 +4656,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { bool CPUMatrix::AreEqual(const CPUMatrix& a, const CPUMatrix& b, const ElemType threshold /*= 1e-8*/) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AreEqual: one of the input matrices is empty."); + LogicError("AreEqual: one of the input matrices is empty."); if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) return false; @@ -4752,14 +4752,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignElementProductOfWithShiftNeg(const CPUMatrix& a, const CPUMatrix& b, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOfWithShiftNeg: Matrix is empty."); + LogicError("AssignElementProductOfWithShiftNeg: Matrix is empty."); assert(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); + InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); if (a.GetNumRows() != 1) - throw std::invalid_argument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); + InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); auto& us = *this; if (this != &a) @@ -4792,7 +4792,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::InnerProductWithShiftNeg(const CPUMatrix& a, const CPUMatrix& b, CPUMatrix& c, const bool isColWise, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProduct: one of the input matrices is empty."); + LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -4802,11 +4802,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert(m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert(m == k && n == l); //converting from size_t to int may cause overflow if (m != k || n != l) - throw std::invalid_argument("InnerProduct: Matrices a and b should have same dimension."); + InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); if ((isColWise && m == 1) || !isColWise && n == 1) //in this case it's equivalent to element-wise product { - throw std::invalid_argument("InnerProduct: Both matrices should be normal ones, not vectors"); + InvalidArgument("InnerProduct: Both matrices should be normal ones, not vectors"); // c.AssignElementProductOf(a, b); } else if (isColWise) //col-wise @@ -4861,7 +4861,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::invalid_argument("InnerProduct: Rowwise is not supported yet"); + InvalidArgument("InnerProduct: Rowwise is not supported yet"); c.Resize(m, 1); @@ -4898,13 +4898,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::GetARowByIndex(const CPUMatrix& a, size_t index) { if (a.IsEmpty()) - throw std::logic_error("GetARowByIndex: the input matrices is empty."); + LogicError("GetARowByIndex: the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); if (index <0 || index >= m) - throw std::logic_error("GetARowByIndex: the row index is out of range."); + LogicError("GetARowByIndex: the row index is out of range."); assert(m>0 && n>0); //converting from size_t to int may cause overflow @@ -4957,7 +4957,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void CPUMatrix::ConductRowElementMultiplyWithShift(const CPUMatrix& a, const CPUMatrix& b, CPUMatrix& c, size_t shift, bool bFirstmatrixfixed) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProduct: one of the input matrices is empty."); + LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -4967,7 +4967,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert(m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert(m == 1 && n == l); //converting from size_t to int may cause overflow if (m != 1 || n != l) - throw std::invalid_argument("InnerProduct: Matrices a and b should have same dimension."); + InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); c.Resize(k, l); // c must the the same size of b @@ -5006,14 +5006,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix& CPUMatrix::AssignElementProductOfWithShift(const CPUMatrix& a, const CPUMatrix& b, size_t shift) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOfWithShiftNeg: Matrix is empty."); + LogicError("AssignElementProductOfWithShiftNeg: Matrix is empty."); assert(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); + InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); if (a.GetNumRows() != 1) - throw std::invalid_argument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); + InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); auto& us = *this; if (this != &a) @@ -5247,7 +5247,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { auto& us = *this; if (us.GetNumCols() != gamma.GetNumCols() || us.GetNumRows() != gamma.GetNumRows()) - throw std::logic_error("DropFrame: target matrix is not in the same size as gamm matrix."); + LogicError("DropFrame: target matrix is not in the same size as gamm matrix."); #pragma omp parallel for foreach_column(j, label) diff --git a/Math/Math/CPUSparseMatrix.cpp b/Math/Math/CPUSparseMatrix.cpp index 57d2ce858..e79fc06bf 100644 --- a/Math/Math/CPUSparseMatrix.cpp +++ b/Math/Math/CPUSparseMatrix.cpp @@ -124,7 +124,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (format != MatrixFormat::matrixFormatSparseCSC && format != MatrixFormat::matrixFormatSparseCSR && format != MatrixFormat::matrixFormatSparseBlockCol && format != MatrixFormat::matrixFormatSparseBlockRow) { - throw std::logic_error("CPUSparseMatrix: unsupported sparse matrix format"); + LogicError("CPUSparseMatrix: unsupported sparse matrix format"); } m_format = format; ZeroInit(); @@ -210,7 +210,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if(m_format != MatrixFormat::matrixFormatSparseCSC && m_format != MatrixFormat::matrixFormatSparseCSR) { - throw std::logic_error("CPUSparseMatrix: unsupported SetValue() call."); + LogicError("CPUSparseMatrix: unsupported SetValue() call."); } if(m_elemSizeAllocated < m_nz +1) //automatic resize @@ -220,11 +220,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if(row < 0 || row >= m_numRows) { - throw std::logic_error("CPUSparseMatrix: SetValue() invalid row id"); + LogicError("CPUSparseMatrix: SetValue() invalid row id"); } if(col < 0 || col >= m_numCols) { - throw std::logic_error("CPUSparseMatrix: SetValue() invalid column id"); + LogicError("CPUSparseMatrix: SetValue() invalid column id"); } size_t r = (m_format == matrixFormatSparseCSC) ? row: col; @@ -238,7 +238,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if(c == m_colIdx && r <= m_unCompIndex[m_nz-1]) { - throw std::logic_error("CPUSparseMatrix: SetValue is not called properly"); + LogicError("CPUSparseMatrix: SetValue is not called properly"); } } @@ -305,7 +305,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix CPUSparseMatrix::ColumnSliceToDense(size_t startColumn, size_t numCols) const { //if (numCols == 0) - // throw std::logic_error("The slice cannot have 0 columns."); + // LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int)startColumn, (int)numCols, (int)m_numCols); @@ -336,7 +336,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CPUMatrix CPUSparseMatrix::DiagonalToDense() const { if (m_numRows != m_numCols) - throw std::logic_error("DiagonalToDense can be called only for square matrix."); + LogicError("DiagonalToDense can be called only for square matrix."); if (m_format != MatrixFormat::matrixFormatSparseCSC) NOT_IMPLEMENTED; @@ -439,7 +439,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { size_t *blockIds = new size_t[newCompIndexSize]; if (keepExistingValues && (m_nz > numNZElemToReserve || m_compIndexSize > newCompIndexSize)) - throw std::logic_error("Resize: To keep values m_nz should <= numNZElemToReserve and m_compIndexSize <= newCompIndexSize"); + LogicError("Resize: To keep values m_nz should <= numNZElemToReserve and m_compIndexSize <= newCompIndexSize"); if (keepExistingValues && m_elemSizeAllocated > 0) { @@ -480,7 +480,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (lhs.IsEmpty() || rhs.IsEmpty()) - throw std::logic_error("MultiplyAndWeightedAdd: one of the input matrix is empty."); + LogicError("MultiplyAndWeightedAdd: one of the input matrix is empty."); int m = transposeA? (int)lhs.GetNumCols(): (int)lhs.GetNumRows(); int k = transposeA? (int)lhs.GetNumRows(): (int)lhs.GetNumCols(); @@ -491,7 +491,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (k == l); if (k != l) { - throw std::invalid_argument("CPUSparseMatrix::MultiplyAndWeightedAdd: The inner dimensions of a and b must match."); + InvalidArgument("CPUSparseMatrix::MultiplyAndWeightedAdd: The inner dimensions of a and b must match."); } if (c.GetNumRows() != m || c.GetNumCols() != n) @@ -567,7 +567,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const CPUSparseMatrix& rhs, const bool transposeB, CPUSparseMatrix& c) { if (lhs.IsEmpty() || rhs.IsEmpty()) - throw std::logic_error("LeftMultiplyAndAdd: one of the input matrix is empty."); + LogicError("LeftMultiplyAndAdd: one of the input matrix is empty."); size_t m = transposeA? (int)lhs.GetNumCols(): (int)lhs.GetNumRows(); size_t k = transposeA? (int)lhs.GetNumRows(): (int)lhs.GetNumCols(); @@ -578,7 +578,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (k == l); if (k != l) { - throw std::invalid_argument("CPUSparseMatrix::MultiplyAndAdd: The inner dimensions of a and b must match."); + InvalidArgument("CPUSparseMatrix::MultiplyAndAdd: The inner dimensions of a and b must match."); } c.Reset(); @@ -637,7 +637,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if(c.m_nz > c.GetSizeAllocated()) { - throw std::logic_error("sparse matrix out of range."); + LogicError("sparse matrix out of range."); } //c.SetFormat(matrixFormatSparseBlockCol); } @@ -656,12 +656,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (lhs.IsEmpty() || rhs.IsEmpty()) { - throw std::logic_error("ScaleAndAdd: one of the input matrix is empty."); + LogicError("ScaleAndAdd: one of the input matrix is empty."); } if (lhs.GetNumRows() != rhs.GetNumRows() || lhs.GetNumCols() != rhs.GetNumCols()) { - throw std::invalid_argument("CPUSparseMatrix::ScaleAndAdd: The dimensions of a and b must match."); + InvalidArgument("CPUSparseMatrix::ScaleAndAdd: The dimensions of a and b must match."); } if(lhs.GetFormat() == MatrixFormat::matrixFormatSparseCSC || lhs.GetFormat() == MatrixFormat::matrixFormatSparseCSR) @@ -700,7 +700,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("CPUSparseMatrix:: ScaleAndAdd() Not implemented"); + RuntimeError("CPUSparseMatrix:: ScaleAndAdd() Not implemented"); } } @@ -709,7 +709,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { bool CPUSparseMatrix::AreEqual(const CPUSparseMatrix& a, const CPUSparseMatrix& b, const ElemType threshold) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AreEqual: one of the input matrices is empty."); + LogicError("AreEqual: one of the input matrices is empty."); if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) return false; @@ -759,7 +759,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("CPUSparseMatrix:: NormalGrad() only support block sparse format"); + RuntimeError("CPUSparseMatrix:: NormalGrad() only support block sparse format"); } } @@ -992,7 +992,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUSparseMatrix::FrobeniusNorm() const { if (this->IsEmpty()) - throw std::logic_error("FrobeniusNorm: Matrix is empty."); + LogicError("FrobeniusNorm: Matrix is empty."); ElemType v = 0; @@ -1019,7 +1019,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUSparseMatrix::SumOfAbsElements() const { if (this->IsEmpty()) - throw std::logic_error("SumOfAbsElements: Matrix is empty."); + LogicError("SumOfAbsElements: Matrix is empty."); if (sizeof(ElemType) == sizeof(double)) { @@ -1046,7 +1046,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType CPUSparseMatrix::SumOfElements() const { if (this->IsEmpty()) - throw std::logic_error("SumOfElements: Matrix is empty."); + LogicError("SumOfElements: Matrix is empty."); ElemType sum = 0; @@ -1075,7 +1075,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { size_t elsize; stream >> elsize; if (sizeof(ElemType) != elsize) - throw std::runtime_error("Template argument size doesn't match those in file"); + RuntimeError("Template argument size doesn't match those in file"); std::wstring matrixName; // now prepare this header to receive the data being read diff --git a/Math/Math/CPUSparseMatrix.h b/Math/Math/CPUSparseMatrix.h index b1ecdfa3b..46c4526e9 100644 --- a/Math/Math/CPUSparseMatrix.h +++ b/Math/Math/CPUSparseMatrix.h @@ -89,7 +89,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (col >= m_numCols || row >= m_numRows) { - throw std::runtime_error("Position outside matrix dimensions"); + RuntimeError("Position outside matrix dimensions"); } if (m_format == MatrixFormat::matrixFormatSparseCSC) diff --git a/Math/Math/GPUMatrix.cu b/Math/Math/GPUMatrix.cu index 2093eb604..1a2e7204c 100755 --- a/Math/Math/GPUMatrix.cu +++ b/Math/Math/GPUMatrix.cu @@ -266,9 +266,9 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::ChangeDeviceTo(DEVICEID_TYPE to_id) { if (!OwnBuffer()) - throw std::logic_error("Cannot change device on Managed external matrix"); + LogicError("Cannot change device on Managed external matrix"); if (to_id == CPUDEVICE) - throw std::logic_error("to_id must be valid GPU"); + LogicError("to_id must be valid GPU"); if (m_computeDevice==to_id) return; @@ -380,7 +380,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix::GPUMatrix(int deviceId) { if (deviceId == MANAGEDEXTERN) - throw std::logic_error("Basic constructor cannot be used with Managed Extern types"); + LogicError("Basic constructor cannot be used with Managed Extern types"); ZeroInit(deviceId); }; @@ -390,7 +390,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix::GPUMatrix(FILE* f, const char * matrixName, int deviceId) { if (deviceId == MANAGEDEXTERN) - throw std::logic_error("File constructor cannot be used with Managed Extern types"); + LogicError("File constructor cannot be used with Managed Extern types"); ReadFromFile(f, matrixName); } @@ -399,7 +399,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix::GPUMatrix(const size_t numRows, const size_t numCols,int deviceId) { if (deviceId == MANAGEDEXTERN) - throw std::logic_error("constructor cannot be used with Managed Extern types"); + LogicError("constructor cannot be used with Managed Extern types"); ZeroInit(deviceId); m_numRows = numRows; m_numCols = numCols; @@ -525,7 +525,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix GPUMatrix::ColumnSlice(size_t startColumn, size_t numCols) const { //if (numCols == 0) - // throw std::logic_error("The slice cannot have 0 columns."); + // LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int)startColumn, (int)numCols, (int)m_numCols); @@ -539,7 +539,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignColumnSlice(const GPUMatrix& fromMatrix, size_t startColumn, size_t numCols) { if (numCols == 0) - throw std::logic_error("The slice cannot have 0 columns."); + LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > fromMatrix.m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int)startColumn, (int)numCols, (int)fromMatrix.m_numCols); @@ -563,13 +563,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::SetColumnSlice(const GPUMatrix& fromMatrix, size_t startColumn, size_t numCols) { //if (numCols == 0) - // throw std::logic_error("The slice cannot have 0 columns."); + // LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > m_numCols) - throw std::logic_error("The slice is out of range of the destination matrix."); + LogicError("The slice is out of range of the destination matrix."); if (numCols > fromMatrix.GetNumCols()) InvalidArgument("The slice (%d) is out of range of the source matrix (%d).", (int)numCols, (int)fromMatrix.GetNumCols()); if (m_numRows != fromMatrix.m_numRows) - throw std::logic_error("The number of rows in source and destination matrices do not match"); + LogicError("The number of rows in source and destination matrices do not match"); if (m_numRows*numCols > 0) // TODO: remove if unnecessary CUDA_CALL(cudaMemcpy(m_pArray + LocateColumn(startColumn), fromMatrix.m_pArray, sizeof(ElemType)*m_numRows*numCols, cudaMemcpyDeviceToDevice)); @@ -582,16 +582,16 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignToRowSliceValuesOf(const GPUMatrix& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) - throw std::logic_error("AddToRowSliceValuesOf: input matrix a is empty."); + LogicError("AddToRowSliceValuesOf: input matrix a is empty."); if (a.GetNumRows() != numRows) - throw std::logic_error("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); + LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) - throw std::logic_error("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); + LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) - throw std::logic_error("AddToRowSliceValuesOf: columns does not match."); + LogicError("AddToRowSliceValuesOf: columns does not match."); CUDA_LONG N = (CUDA_LONG)a.GetNumElements(); int blocksPerGrid = (int)ceil(1.0*N / threadsPerBlock); @@ -611,10 +611,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignRowSliceValuesOf(const GPUMatrix& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) - throw std::logic_error("AssignRowSliceValuesOf: input matrix a is empty."); + LogicError("AssignRowSliceValuesOf: input matrix a is empty."); if (startIndex + numRows > a.GetNumRows()) - throw std::logic_error("AssignRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); + LogicError("AssignRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); Resize(numRows, a.GetNumCols()); @@ -636,16 +636,16 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AddToRowSliceValuesOf(const GPUMatrix& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) - throw std::logic_error("AddToRowSliceValuesOf: input matrix a is empty."); + LogicError("AddToRowSliceValuesOf: input matrix a is empty."); if (a.GetNumRows() != numRows) - throw std::logic_error("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); + LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) - throw std::logic_error("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); + LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) - throw std::logic_error("AddToRowSliceValuesOf: columns does not match."); + LogicError("AddToRowSliceValuesOf: columns does not match."); CUDA_LONG N=(CUDA_LONG)a.GetNumElements(); int blocksPerGrid =(int)ceil(1.0*N/threadsPerBlock); @@ -665,16 +665,16 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AddWithRowSliceValuesOf(const GPUMatrix& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) - throw std::logic_error("AddWithRowSliceValuesOf: input matrix a is empty."); + LogicError("AddWithRowSliceValuesOf: input matrix a is empty."); if (GetNumRows() != numRows) - throw std::logic_error("AddWithRowSliceValuesOf: GetNumRows() != numRows."); + LogicError("AddWithRowSliceValuesOf: GetNumRows() != numRows."); if (startIndex + numRows > a.GetNumRows()) - throw std::logic_error("AddWithRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); + LogicError("AddWithRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); if (a.GetNumCols() != GetNumCols()) - throw std::logic_error("AddWithRowSliceValuesOf: columns does not match."); + LogicError("AddWithRowSliceValuesOf: columns does not match."); CUDA_LONG N = (CUDA_LONG)GetNumElements(); int blocksPerGrid = (int)ceil(1.0*N / threadsPerBlock); @@ -790,10 +790,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignRepeatOf(const GPUMatrix& a, const size_t numRowRepeats, const size_t numColRepeats) { if (this == &a) - throw std::logic_error("AssignRepeatOf: a is the same as [this]. Does not support inplace repeat."); + LogicError("AssignRepeatOf: a is the same as [this]. Does not support inplace repeat."); if (a.IsEmpty()) - throw std::logic_error("AssignRepeatOf: Matrix a is empty."); + LogicError("AssignRepeatOf: Matrix a is empty."); Resize(a.GetNumRows() * numRowRepeats, a.GetNumCols() * numColRepeats); @@ -815,10 +815,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AddToRowRepeatValuesOf(const GPUMatrix& a, const size_t numRepeats) { if (a.IsEmpty()) - throw std::logic_error("AddToRowRepeatValuesOf: input matrix a is empty."); + LogicError("AddToRowRepeatValuesOf: input matrix a is empty."); if (a.GetNumRows() != GetNumRows() * numRepeats) - throw std::logic_error("AddToRowSliceValuesOf: a.GetNumRows() != GetNumRows() * numRepeats."); + LogicError("AddToRowSliceValuesOf: a.GetNumRows() != GetNumRows() * numRepeats."); Resize(a.GetNumRows() / numRepeats, a.GetNumCols()); @@ -839,10 +839,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignPositiveAndShiftedNegSample(const GPUMatrix& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber) { if (this == &a) - throw std::logic_error("AssignPositiveAndShiftedNegSample: a is the same as [this]. Does not support inplace assignment."); + LogicError("AssignPositiveAndShiftedNegSample: a is the same as [this]. Does not support inplace assignment."); if (a.IsEmpty()) - throw std::logic_error("AssignPositiveAndShiftedNegSample: Matrix a is empty."); + LogicError("AssignPositiveAndShiftedNegSample: Matrix a is empty."); Resize(a.GetNumRows() * (posNumber + negNumber), a.GetNumCols()); @@ -864,13 +864,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AddFoldedPositiveAndShiftedNegSample(const GPUMatrix& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber) { if (this == &a) - throw std::logic_error("AddFoldedPositiveAndShiftedNegSample: a is the same as [this]. Does not support inplace assignment."); + LogicError("AddFoldedPositiveAndShiftedNegSample: a is the same as [this]. Does not support inplace assignment."); if (a.IsEmpty()) - throw std::logic_error("AddFoldedPositiveAndShiftedNegSample: Matrix a is empty."); + LogicError("AddFoldedPositiveAndShiftedNegSample: Matrix a is empty."); if (a.GetNumRows() != GetNumRows() * (posNumber + negNumber) || a.GetNumCols() != GetNumCols()) - throw std::logic_error("AddFoldedPositiveAndShiftedNegSample: dimensions mismatch."); + LogicError("AddFoldedPositiveAndShiftedNegSample: dimensions mismatch."); CUDA_LONG N = (CUDA_LONG)a.GetNumElements(); CUDA_LONG n = (CUDA_LONG)a.GetNumCols(), m = (CUDA_LONG)a.GetNumRows(); @@ -891,7 +891,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix GPUMatrix::Transpose() const { if (IsEmpty()) - throw std::logic_error("Transpose: Matrix is empty."); + LogicError("Transpose: Matrix is empty."); GPUMatrix c(GetComputeDeviceId()); c.AssignTransposeOf(*this); @@ -910,7 +910,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { cudaGetDevice(&computeDevice); if (computeDevice < 0 || computeDevice >= MaxGpus) - throw std::logic_error("GetCublasHandle: Maximum GPU exceeded"); + LogicError("GetCublasHandle: Maximum GPU exceeded"); cublasHandle_t cuHandle = s_cuHandle[computeDevice]; if (cuHandle == NULL) { @@ -925,10 +925,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignTransposeOf (const GPUMatrix& a) { if (this == &a) - throw std::logic_error("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); + LogicError("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); if (a.IsEmpty()) - throw std::logic_error("AssignTransposeOf: Matrix a is empty."); + LogicError("AssignTransposeOf: Matrix a is empty."); if (GetNumRows()!=a.GetNumCols() || GetNumCols()!=a.GetNumRows()) Resize(a.GetNumCols(), a.GetNumRows()); @@ -951,11 +951,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Unsupported template argument in GPUMatrix"); + RuntimeError("Unsupported template argument in GPUMatrix"); } if (st!=CUBLAS_STATUS_SUCCESS) { - throw std::runtime_error("AssignTransposeOf failed"); + RuntimeError("AssignTransposeOf failed"); } m_numRows=a.m_numCols; m_numCols=a.m_numRows; @@ -967,7 +967,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::SetValue(const ElemType v) { if (IsEmpty()) - throw std::logic_error("SetValue: Matrix is empty."); + LogicError("SetValue: Matrix is empty."); CUDA_LONG N = (CUDA_LONG) GetNumElements(); @@ -1005,7 +1005,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::SetValue(const ElemType* d_v) //d_v is pointer to the the value in GPU memory { if (IsEmpty()) - throw std::logic_error("SetValue: Matrix is empty."); + LogicError("SetValue: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(1.0*N/threadsPerBlock); @@ -1022,7 +1022,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::SetColumn(const ElemType* colPointer, size_t colInd) { if (IsEmpty()) - throw std::logic_error("SetValue: Matrix is empty."); + LogicError("SetValue: Matrix is empty."); if (colPointer==NULL) return; CUDA_CALL(cudaMemcpy(m_pArray+LocateColumn(colInd),colPointer,sizeof(ElemType)*m_numRows,cudaMemcpyHostToDevice)); @@ -1032,9 +1032,9 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::SetColumn(const GPUMatrix& valMat, size_t colInd) { if (IsEmpty()) - throw std::logic_error("SetColumn: Matrix is empty."); + LogicError("SetColumn: Matrix is empty."); if (valMat.GetNumCols() != 1) - throw std::logic_error("SetColumn: only support one column matrix now."); + LogicError("SetColumn: only support one column matrix now."); CUDA_CALL(cudaMemcpy(m_pArray + LocateColumn(colInd), valMat.m_pArray, sizeof(ElemType)*m_numRows, cudaMemcpyDeviceToDevice)); } @@ -1102,7 +1102,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Row major isn't implemented"); + RuntimeError("Row major isn't implemented"); } } } @@ -1128,19 +1128,19 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::SetDiagonalValue(const GPUMatrix& vector) { if (IsEmpty() || vector.IsEmpty()) - throw std::logic_error("SetDiagonalValue: Matrix is empty."); + LogicError("SetDiagonalValue: Matrix is empty."); if (GetNumRows() != GetNumCols()) - throw std::logic_error("SetDiagonalValue: NumRows and NumCols do not agree."); + LogicError("SetDiagonalValue: NumRows and NumCols do not agree."); if (vector.GetNumRows() != 1 && vector.GetNumCols() != 1) - throw std::logic_error("SetDiagonalValue: input vector must be a vector."); + LogicError("SetDiagonalValue: input vector must be a vector."); if (vector.GetNumElements() == 1) //reduce to simple form SetDiagonalValue(vector.m_pArray[0]); else if (vector.GetNumRows() != GetNumRows()) - throw std::logic_error("SetDiagonalValue: input vector's dimension does not agree with [this]."); + LogicError("SetDiagonalValue: input vector's dimension does not agree with [this]."); else { CUDA_LONG N=(CUDA_LONG)GetNumRows(); @@ -1410,7 +1410,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { assert (numRows*numCols == GetNumElements()); if (numRows*numCols != GetNumElements()) - throw std::invalid_argument("Reshape: total number of elements does not match."); + InvalidArgument("Reshape: total number of elements does not match."); m_numRows = numRows; m_numCols = numCols; @@ -1436,7 +1436,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else { if (!OwnBuffer()) - throw std::invalid_argument("Can't resize a externally managed matrix"); + InvalidArgument("Can't resize a externally managed matrix"); PrepareDevice(); if (m_pArray!=NULL) CUDA_CALL(cudaFree(m_pArray)); //delete and reallocate @@ -1475,7 +1475,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::operator+= (ElemType alpha) { if (IsEmpty()) - throw std::logic_error("operator+=: Matrix is empty."); + LogicError("operator+=: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(1.0*N/threadsPerBlock); cudaEvent_t done = nullptr; @@ -1491,7 +1491,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix GPUMatrix::operator+ (ElemType alpha) const { if (IsEmpty()) - throw std::logic_error("operator+: Matrix is empty."); + LogicError("operator+: Matrix is empty."); const GPUMatrix& us=*this; GPUMatrix c(us); @@ -1565,7 +1565,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::operator-= (ElemType alpha) { if (IsEmpty()) - throw std::logic_error("operato-=: Matrix is empty."); + LogicError("operato-=: Matrix is empty."); return operator+=(-1*alpha); } @@ -1573,7 +1573,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix GPUMatrix::operator- (ElemType alpha) const { if (IsEmpty()) - throw std::logic_error("operator-: Matrix is empty."); + LogicError("operator-: Matrix is empty."); return operator+(-1*alpha); } @@ -1757,14 +1757,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AddElementProductOf (const GPUMatrix& a, const GPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AddElementProductOf: Matrix is empty."); + LogicError("AddElementProductOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match [this]."); + InvalidArgument("The input matrix dimensions do not match [this]."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(1.0*N/threadsPerBlock); @@ -1782,10 +1782,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::ColumnElementMultiplyWith(const GPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("ColumnElementMultiplyWith: Matrix is empty."); + LogicError("ColumnElementMultiplyWith: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) - throw std::invalid_argument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); + InvalidArgument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); CUDA_LONG N=(CUDA_LONG)a.GetNumRows(); CUDA_LONG M=(CUDA_LONG)GetNumCols(); @@ -1805,10 +1805,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::RowElementMultiplyWith(const GPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("RowElementMultiplyWith: Matrix is empty."); + LogicError("RowElementMultiplyWith: Matrix is empty."); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) - throw std::invalid_argument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); + InvalidArgument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); CUDA_LONG N = (CUDA_LONG)GetNumRows(); CUDA_LONG M = (CUDA_LONG)a.GetNumCols(); @@ -1828,10 +1828,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::RowElementDivideBy(const GPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("RowElementDivideBy: Matrix is empty."); + LogicError("RowElementDivideBy: Matrix is empty."); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) - throw std::invalid_argument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); + InvalidArgument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); CUDA_LONG N = (CUDA_LONG)GetNumRows(); CUDA_LONG M = (CUDA_LONG)a.GetNumCols(); @@ -1851,10 +1851,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::ColumnElementDivideBy(const GPUMatrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("ColumnElementDivideBy: Matrix is empty."); + LogicError("ColumnElementDivideBy: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) - throw std::invalid_argument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); + InvalidArgument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); CUDA_LONG N = (CUDA_LONG)a.GetNumRows(); CUDA_LONG M = (CUDA_LONG)GetNumCols(); @@ -1874,7 +1874,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::ElementInverse () { if (IsEmpty()) - throw std::logic_error("ElementInverse: Matrix is empty."); + LogicError("ElementInverse: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(1.0*N/threadsPerBlock); @@ -1931,7 +1931,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignSigmoidDerivativeOf (const GPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSigmoidDerivativeOf: Matrix a is empty."); + LogicError("AssignSigmoidDerivativeOf: Matrix a is empty."); //auto& us=*this; if (this != &a) @@ -2098,7 +2098,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::InplaceLogSoftmax (const bool isColWise) { if (IsEmpty()) - throw std::logic_error("InplaceLogSoftmax: Matrix is empty."); + LogicError("InplaceLogSoftmax: Matrix is empty."); PrepareDevice(); if (isColWise) @@ -2259,7 +2259,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::InplaceTruncateBottom (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateBottom: Matrix is empty."); + LogicError("InplaceTruncateBottom: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(N*1.0/threadsPerBlock); @@ -2277,7 +2277,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignTruncateBottomOf (const GPUMatrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateBottomOf: Matrix a is empty."); + LogicError("AssignTruncateBottomOf: Matrix a is empty."); if (this!=&a) { @@ -2301,7 +2301,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::InplaceTruncateTop (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateTop: Matrix is empty."); + LogicError("InplaceTruncateTop: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(N*1.0/threadsPerBlock); PrepareDevice(); @@ -2318,7 +2318,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignTruncateTopOf (const GPUMatrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateTopOf: Matrix a is empty."); + LogicError("AssignTruncateTopOf: Matrix a is empty."); if (this!=&a) { @@ -2342,7 +2342,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::InplaceTruncate(const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncate: Matrix is empty."); + LogicError("InplaceTruncate: Matrix is empty."); CUDA_LONG N = (CUDA_LONG)GetNumElements(); int blocksPerGrid = (int)ceil(N*1.0 / threadsPerBlock); @@ -2360,7 +2360,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::InplaceSoftThreshold(const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceSoftThreshold: Matrix is empty."); + LogicError("InplaceSoftThreshold: Matrix is empty."); CUDA_LONG N = (CUDA_LONG)GetNumElements(); int blocksPerGrid = (int)ceil(N*1.0 / threadsPerBlock); @@ -2377,7 +2377,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::SetToZeroIfAbsLessThan (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("SetToZeroIfAbsLessThan: Matrix is empty."); + LogicError("SetToZeroIfAbsLessThan: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(N*1.0/threadsPerBlock); PrepareDevice(); @@ -2394,7 +2394,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::SumOfAbsElements() const { if (IsEmpty()) - throw std::logic_error("SumOfAbsElements: Matrix is empty"); + LogicError("SumOfAbsElements: Matrix is empty"); cublasHandle_t cuHandle = GetCublasHandle(GetComputeDeviceId()); if (sizeof(ElemType)==sizeof(float)) @@ -2415,7 +2415,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::SumOfElements() const { if (IsEmpty()) - throw std::logic_error("SumOfElements: Matrix is empty"); + LogicError("SumOfElements: Matrix is empty"); PrepareDevice(); ElemType* d_sum = NULL; @@ -2433,7 +2433,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignSumOfElements(const GPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSumOfElements: Matrix a is empty"); + LogicError("AssignSumOfElements: Matrix a is empty"); Resize(1,1); @@ -2452,7 +2452,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { DeviceBoundNumber GPUMatrix::Sum_AsDeviceBoundNum() const { if (IsEmpty()) - throw std::logic_error("Matrix is empty"); + LogicError("Matrix is empty"); PrepareDevice(); ElemType* d_sum = NULL; CUDA_CALL(cudaMalloc((void**)&d_sum,sizeof(ElemType))); @@ -2491,12 +2491,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::ElementMultiplyWith (const GPUMatrix& a) { if (IsEmpty() || a.IsEmpty()) - throw std::logic_error("ElementMultiplyWith: Matrix is empty."); + LogicError("ElementMultiplyWith: Matrix is empty."); GPUMatrix& us=*this; assert (us.GetNumRows() == a.GetNumRows() && us.GetNumCols() == a.GetNumCols()); if (us.GetNumRows() != a.GetNumRows() || us.GetNumCols() != a.GetNumCols()) - throw std::invalid_argument("The matrix dimensions do not match."); + InvalidArgument("The matrix dimensions do not match."); CUDA_LONG N=(CUDA_LONG)GetNumElements(); int blocksPerGrid =(int)ceil(((double)N)/threadsPerBlock); @@ -2514,11 +2514,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignElementProductOf (const GPUMatrix& a, const GPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOf: Matrix is empty."); + LogicError("AssignElementProductOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); Resize(a.GetNumRows(), a.GetNumCols()); CUDA_LONG N=(CUDA_LONG)GetNumElements(); @@ -2543,11 +2543,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignElementDivisionOf (const GPUMatrix& a, const GPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementDivisionOf: Matrix is empty."); + LogicError("AssignElementDivisionOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); Resize(a.GetNumRows(), a.GetNumCols()); CUDA_LONG N=(CUDA_LONG)GetNumElements(); @@ -2573,13 +2573,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (a.GetComputeDeviceId() != c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } a.PrepareDevice(); if (a.IsEmpty()) - throw std::logic_error("VectorSum: Input matrix is empty."); + LogicError("VectorSum: Input matrix is empty."); const CUDA_LONG n = (CUDA_LONG)a.GetNumRows(); const CUDA_LONG m = (CUDA_LONG)a.GetNumCols(); @@ -2609,7 +2609,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::VectorNorm1(GPUMatrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNorm1: Matrix is empty."); + LogicError("VectorNorm1: Matrix is empty."); const CUDA_LONG n = (CUDA_LONG)GetNumRows(); const CUDA_LONG m = (CUDA_LONG)GetNumCols(); @@ -2649,7 +2649,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::VectorNorm2(GPUMatrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNorm2: Matrix is empty."); + LogicError("VectorNorm2: Matrix is empty."); const CUDA_LONG n = (CUDA_LONG)GetNumRows(); const CUDA_LONG m = (CUDA_LONG)GetNumCols(); @@ -2690,7 +2690,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::VectorNormInf(GPUMatrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorMax: Matrix is empty."); + LogicError("VectorMax: Matrix is empty."); //this implementation is not efficient GPUMatrix tmp; @@ -2717,12 +2717,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignKhatriRaoProductOf(const GPUMatrix& a, const GPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignKhatriRaoProductOf: Matrix is empty."); + LogicError("AssignKhatriRaoProductOf: Matrix is empty."); CUDA_LONG cols = a.GetNumCols(); assert (cols == b.GetNumCols()); if (!(cols == b.GetNumCols())) - throw std::invalid_argument("AssignKhatriRaoProductOf: The input matrix dimensions do not match."); + InvalidArgument("AssignKhatriRaoProductOf: The input matrix dimensions do not match."); CUDA_LONG rowsA = (CUDA_LONG)a.GetNumRows(); CUDA_LONG rowsB = (CUDA_LONG)b.GetNumRows(); @@ -2749,21 +2749,21 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AddColumnReshapeProductOf(const GPUMatrix& a, const GPUMatrix& b, const bool transposeAColumn) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AddColumnReshapeProductOf: Matrix is empty."); + LogicError("AddColumnReshapeProductOf: Matrix is empty."); CUDA_LONG cols = a.GetNumCols(); assert (cols == b.GetNumCols()); if (!(cols == b.GetNumCols())) - throw std::invalid_argument("AddColumnReshapeProductOf: The input matrix dimensions do not match."); + InvalidArgument("AddColumnReshapeProductOf: The input matrix dimensions do not match."); CUDA_LONG rowsA = (CUDA_LONG)a.GetNumRows(); CUDA_LONG rowsB = (CUDA_LONG)b.GetNumRows(); if (rowsA % rowsB != 0) - throw std::invalid_argument("AddColumnReshapeProductOf: number of rows in a should be multiples of that in b."); + InvalidArgument("AddColumnReshapeProductOf: number of rows in a should be multiples of that in b."); CUDA_LONG rowsC = rowsA / rowsB; if (rowsC != GetNumRows() || cols != GetNumCols()) - throw std::invalid_argument("AddColumnReshapeProductOf: This matrix does not have the right size."); + InvalidArgument("AddColumnReshapeProductOf: This matrix does not have the right size."); float N=(float)GetNumElements(); int blocksPerGrid =(int)ceil(N/threadsPerBlock); @@ -2789,7 +2789,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::FrobeniusNorm() const { if (IsEmpty()) - throw std::logic_error("FrobeniusNorm: Matrix is empty."); + LogicError("FrobeniusNorm: Matrix is empty."); PrepareDevice(); ElemType* d_sum = NULL; @@ -2807,7 +2807,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignFrobeniusNormOf (const GPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignFrobeniusNormOf: Matrix a is empty."); + LogicError("AssignFrobeniusNormOf: Matrix a is empty."); Resize(1,1); @@ -2822,7 +2822,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::MatrixNormInf() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm1: Matrix is empty."); + LogicError("MatrixNorm1: Matrix is empty."); PrepareDevice(); ElemType* d_maxAbs = NULL; @@ -2839,7 +2839,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::MatrixNorm1() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm1: Matrix is empty."); + LogicError("MatrixNorm1: Matrix is empty."); return SumOfAbsElements(); } @@ -2847,7 +2847,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::MatrixNorm0() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm0: Matrix is empty."); + LogicError("MatrixNorm0: Matrix is empty."); PrepareDevice(); ElemType* d_nz = NULL; @@ -2864,7 +2864,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignSignOf(const GPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSignOf: Matrix a is empty."); + LogicError("AssignSignOf: Matrix a is empty."); if (this != &a) Resize(a.GetNumRows(), a.GetNumCols()); @@ -2884,7 +2884,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AddSignOf(const GPUMatrix& a) { if (a.IsEmpty()) - throw std::logic_error("AddSignOf: Matrix a is empty."); + LogicError("AddSignOf: Matrix a is empty."); if (this != &a) Resize(a.GetNumRows(), a.GetNumCols()); @@ -2904,7 +2904,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::VectorMax(GPUMatrix& maxIndexes, GPUMatrix& maxValues, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorMax: Matrix is empty."); + LogicError("VectorMax: Matrix is empty."); const GPUMatrix& us=*this; const CUDA_LONG m = (CUDA_LONG)GetNumRows(); @@ -2940,7 +2940,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::VectorMin(GPUMatrix& minIndexes, GPUMatrix& minValues, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorMax: Matrix is empty."); + LogicError("VectorMax: Matrix is empty."); const GPUMatrix& us=*this; const int m = (int)GetNumRows(); @@ -2978,7 +2978,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignNumOfDiff(const GPUMatrix& a, const GPUMatrix& b) { if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) - throw std::invalid_argument ("AssignNumOfDiff: a and b must have same dimension."); + InvalidArgument("AssignNumOfDiff: a and b must have same dimension."); Resize(1,1); //result should be one element @@ -3219,7 +3219,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { a.PrepareDevice(); if ((a.GetComputeDeviceId()!=b.GetComputeDeviceId()) || (b.GetComputeDeviceId()!=c.GetComputeDeviceId())) //different GPUs { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { @@ -3234,11 +3234,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (!(m>0 && k>0 && l>0 && n>0)) { - throw std::runtime_error("!(m>0 && k>0 && l>0 && n>0)"); //converting from size_t to int may cause overflow + RuntimeError("!(m>0 && k>0 && l>0 && n>0)"); //converting from size_t to int may cause overflow } if (k!=l) { - throw std::runtime_error("matrix dim mismatch in MultiplyAndWeightedAdd"); + RuntimeError("matrix dim mismatch in MultiplyAndWeightedAdd"); } if (sizeof(ElemType)==sizeof(float)) { @@ -3250,7 +3250,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Unsupported template argument in GPUMatrix"); + RuntimeError("Unsupported template argument in GPUMatrix"); } c.m_numRows=m; c.m_numCols=n; @@ -3287,13 +3287,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (a.GetComputeDeviceId()!=c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { a.PrepareDevice(); if (a.IsEmpty() || c.IsEmpty()) - throw std::logic_error("ScaleAndAdd: one of the input matrices is empty."); + LogicError("ScaleAndAdd: one of the input matrices is empty."); //if (a.GetNumRows() != 1 && a.GetNumCols() != 1) // a is not a col or row vector if (a.GetNumRows()==c.GetNumRows() && a.GetNumCols()==c.GetNumCols()) // dimensions match { @@ -3306,7 +3306,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && n>0 && len>0); //converting from size_t to int may cause overflow assert ((int)c.GetNumRows() == m && (int)c.GetNumCols() == n); if ((int)c.GetNumRows() != m || (int)c.GetNumCols() != n) - throw std::invalid_argument("dimension of matrix c does not match dimension of matrix a."); + InvalidArgument("dimension of matrix c does not match dimension of matrix a."); cublasHandle_t cuHandle = GetCublasHandle(a.GetComputeDeviceId()); if (sizeof(ElemType) == sizeof(float)) @@ -3319,7 +3319,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Unsupported template argument in GPUMatrix"); + RuntimeError("Unsupported template argument in GPUMatrix"); } } else if (a.GetNumElements() == 1) @@ -3339,7 +3339,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { CUDA_LONG m = (CUDA_LONG)c.GetNumRows(); CUDA_LONG n = (CUDA_LONG)c.GetNumCols(); if (m != (CUDA_LONG)a.GetNumRows()) - throw std::invalid_argument("To add column vector, rows should match."); + InvalidArgument("To add column vector, rows should match."); cudaEvent_t done = nullptr; int blocksPerGrid = (int)(ceil(1.0*m*n / threadsPerBlock)); @@ -3370,7 +3370,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { int n = (int)c.GetNumCols(); assert (n == (int)a.GetNumCols()); if (n != (int)a.GetNumCols()) - throw std::invalid_argument("To add row vector, cols should match."); + InvalidArgument("To add row vector, cols should match."); if (sizeof(ElemType) == sizeof(double)) { @@ -3388,7 +3388,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } } else - throw std::invalid_argument("dimension of matrix c does not match dimension of matrix a."); + InvalidArgument("dimension of matrix c does not match dimension of matrix a."); } } @@ -3403,7 +3403,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (a.GetComputeDeviceId()!=c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { @@ -3415,11 +3415,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumRows() == c.GetNumRows() && a.GetNumCols() == b.GetNumCols() && a.GetNumCols() == c.GetNumCols())) { - throw std::invalid_argument("AddScaledDifference: a, b, and c must have same dimension."); + InvalidArgument("AddScaledDifference: a, b, and c must have same dimension."); } if (a.IsEmpty()) - throw std::logic_error("AddScaledDifference: Input matrix a is empty."); + LogicError("AddScaledDifference: Input matrix a is empty."); cudaEvent_t done = nullptr; CUDA_LONG n=(CUDA_LONG)a.GetNumElements(); @@ -3443,7 +3443,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (a.GetComputeDeviceId()!=c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { @@ -3453,11 +3453,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) { - throw std::invalid_argument("AssignScaledDifference: a, b must have same dimension."); + InvalidArgument("AssignScaledDifference: a, b must have same dimension."); } if (a.IsEmpty()) - throw std::logic_error("AssignScaledDifference: Input matrix a is empty."); + LogicError("AssignScaledDifference: Input matrix a is empty."); if (&c != &a && &c != &b) c.Resize(a.GetNumRows(), a.GetNumCols()); @@ -3484,11 +3484,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { { assert(alpha.GetNumElements() == 1); if (!(alpha.GetNumElements() == 1)) - throw std::invalid_argument("AddScaledDifference: alpha must be a 1X1 matrix."); + InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); if (a.GetComputeDeviceId()!=c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { @@ -3500,11 +3500,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumRows() == c.GetNumRows() && a.GetNumCols() == b.GetNumCols() && a.GetNumCols() == c.GetNumCols())) { - throw std::invalid_argument("AddScaledDifference: a, b, and c must have same dimension."); + InvalidArgument("AddScaledDifference: a, b, and c must have same dimension."); } if (a.IsEmpty()) - throw std::logic_error("AddScaledDifference: Input matrix a is empty."); + LogicError("AddScaledDifference: Input matrix a is empty."); cudaEvent_t done = nullptr; CUDA_LONG n=(CUDA_LONG)a.GetNumElements(); @@ -3528,11 +3528,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { { assert(alpha.GetNumElements() == 1); if (!(alpha.GetNumElements() == 1)) - throw std::invalid_argument("AddScaledDifference: alpha must be a 1X1 matrix."); + InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); if (a.GetComputeDeviceId()!=c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { @@ -3542,11 +3542,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) { - throw std::invalid_argument("AssignScaledDifference: a, b must have same dimension."); + InvalidArgument("AssignScaledDifference: a, b must have same dimension."); } if (a.IsEmpty()) - throw std::logic_error("AssignScaledDifference: Input matrix a is empty."); + LogicError("AssignScaledDifference: Input matrix a is empty."); c.Resize(a.GetNumRows(), a.GetNumCols()); @@ -3567,7 +3567,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (ai >= a.GetNumRows() || aj >=a.GetNumCols() || ci >= c.GetNumRows() || cj >=c.GetNumCols()) - throw std::invalid_argument("AddElementToElement: index out of range."); + InvalidArgument("AddElementToElement: index out of range."); a.PrepareDevice(); cudaEvent_t done = nullptr; @@ -3595,7 +3595,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Unsupported template argument in GPUMatrix"); + RuntimeError("Unsupported template argument in GPUMatrix"); } } @@ -3605,7 +3605,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (alpha.GetNumElements()!=1) { - throw std::runtime_error("Matrix alpha must be 1x1"); + RuntimeError("Matrix alpha must be 1x1"); } cublasHandle_t cuHandle = GetCublasHandle(a.GetComputeDeviceId()); cublasSetPointerMode(cuHandle, CUBLAS_POINTER_MODE_DEVICE); @@ -3620,7 +3620,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else { cublasSetPointerMode(cuHandle, CUBLAS_POINTER_MODE_HOST); - throw std::runtime_error("Unsupported template argument in GPUMatrix"); + RuntimeError("Unsupported template argument in GPUMatrix"); } cublasSetPointerMode(cuHandle, CUBLAS_POINTER_MODE_HOST); } @@ -3629,7 +3629,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::Scale(ElemType alpha, const GPUMatrix& a, GPUMatrix& c) { if (a.IsEmpty()) - throw std::logic_error("Scale: Input matrix a is empty."); + LogicError("Scale: Input matrix a is empty."); c=a; Scale(alpha,c); @@ -3640,10 +3640,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::InnerProduct (const GPUMatrix& a, const GPUMatrix& b, GPUMatrix& c, const bool isColWise) { if (a.GetComputeDeviceId()!=b.GetComputeDeviceId() || b.GetComputeDeviceId()!=c.GetComputeDeviceId()) //different GPUs - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("Scale: one of the input matrices is empty."); + LogicError("Scale: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -3653,7 +3653,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert (m==k && n==l); //converting from size_t to int may cause overflow if (m!=k || n!=l) - throw std::invalid_argument("Matrices a and b should have same dimension."); + InvalidArgument("Matrices a and b should have same dimension."); if (isColWise) c.Resize(1,n); @@ -3693,7 +3693,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::InnerProductOfMatrices(const GPUMatrix& a, const GPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProductOfMatrices: one of the input matrices is empty."); + LogicError("InnerProductOfMatrices: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -3703,7 +3703,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert (m==k && n==l); //converting from size_t to int may cause overflow if (m!=k || n!=l) - throw std::invalid_argument("InnerProductOfMatrices: Matrices a and b should have same dimension."); + InvalidArgument("InnerProductOfMatrices: Matrices a and b should have same dimension."); cublasHandle_t cuHandle = GetCublasHandle(a.GetComputeDeviceId()); if (sizeof(ElemType) == sizeof(double)) @@ -3727,7 +3727,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignInnerProductOfMatrices(const GPUMatrix& a, const GPUMatrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProductOfMatrices: one of the input matrices is empty."); + LogicError("InnerProductOfMatrices: one of the input matrices is empty."); Resize(1,1); @@ -3739,7 +3739,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert (m==k && n==l); //converting from size_t to int may cause overflow if (m!=k || n!=l) - throw std::invalid_argument("InnerProductOfMatrices: Matrices a and b should have same dimension."); + InvalidArgument("InnerProductOfMatrices: Matrices a and b should have same dimension."); cublasHandle_t cuHandle = GetCublasHandle(a.GetComputeDeviceId()); cublasSetPointerMode(cuHandle, CUBLAS_POINTER_MODE_DEVICE); @@ -3761,12 +3761,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (a.GetComputeDeviceId() != c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { if (a.IsEmpty()) - throw std::logic_error("ElementWisePower: The input matrix a is empty."); + LogicError("ElementWisePower: The input matrix a is empty."); c.Resize(a.GetNumRows(), a.GetNumCols()); @@ -3786,7 +3786,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { bool GPUMatrix::AreEqual(const GPUMatrix& a, const GPUMatrix& b, const ElemType threshold /*= 1e-8*/) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AreEqual: one of the input matrices is empty."); + LogicError("AreEqual: one of the input matrices is empty."); if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) return false; @@ -3814,7 +3814,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { bool GPUMatrix::HasElement(const GPUMatrix& a, const ElemType v) { if (a.IsEmpty()) - throw std::logic_error("HasElement: the input matrix is empty."); + LogicError("HasElement: the input matrix is empty."); bool bResult = false; a.PrepareDevice(); @@ -3892,7 +3892,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const int l = (int)SmoothedGradients.GetNumCols(); assert (m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert (m==k && n==l); //converting from size_t to int may cause overflow - if (m!=k || n!=l) throw std::invalid_argument("InnerProductOfMatrices: Matrices a and b should have same dimension."); + if (m!=k || n!=l) InvalidArgument("InnerProductOfMatrices: Matrices a and b should have same dimension."); if (sizeof(ElemType) == sizeof(double)) { @@ -3924,14 +3924,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignElementProductOfWithShiftNeg(const GPUMatrix& a, const GPUMatrix& b, const size_t shift, const size_t nt) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOf: Matrix is empty."); + LogicError("AssignElementProductOf: Matrix is empty."); assert(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); if (!(a.GetNumRows() == 1)) - throw std::invalid_argument("The input matrix must be a row vector."); + InvalidArgument("The input matrix must be a row vector."); Resize(nt + 1, a.GetNumCols()); int BS = a.GetNumCols(); @@ -3956,10 +3956,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::InnerProductWithShiftNeg(const GPUMatrix& a, const GPUMatrix& b, GPUMatrix& c, const size_t shift, const size_t nt) { if (a.GetComputeDeviceId() != b.GetComputeDeviceId() || b.GetComputeDeviceId() != c.GetComputeDeviceId()) //different GPUs - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("Scale: one of the input matrices is empty."); + LogicError("Scale: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -3969,7 +3969,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert(m>0 && n>0 && k>0 && l>0); //converting from size_t to int may cause overflow assert(m == k && n == l); //converting from size_t to int may cause overflow if (m != k || n != l) - throw std::invalid_argument("Matrices a and b should have same dimension."); + InvalidArgument("Matrices a and b should have same dimension."); c.Resize(nt + 1, n); @@ -3994,7 +3994,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::GetARowByIndex(const GPUMatrix& a, const size_t m) { if (a.IsEmpty()) - throw std::logic_error("GetARowByIndex: Matrix is empty."); + LogicError("GetARowByIndex: Matrix is empty."); Resize(1, a.GetNumCols()); @@ -4002,7 +4002,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { int P = a.GetNumCols(); if (m >= n) - throw std::logic_error("GetARowByIndex: m is out of range."); + LogicError("GetARowByIndex: m is out of range."); int blocksPerGrid = (int)ceil(((double)P) / threadsPerBlock); @@ -4024,10 +4024,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUMatrix::ConductRowElementMultiplyWithShift(const GPUMatrix& a, const GPUMatrix& b, GPUMatrix& c, const size_t shift, const bool isafixed) { if (a.GetComputeDeviceId() != b.GetComputeDeviceId() || b.GetComputeDeviceId() != c.GetComputeDeviceId()) //different GPUs - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("Scale: one of the input matrices is empty."); + LogicError("Scale: one of the input matrices is empty."); const int m = (int)a.GetNumRows(); const int n = (int)a.GetNumCols(); @@ -4036,7 +4036,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert(m>0 && n>0 && O>0 && P>0); //converting from size_t to int may cause overflow if (m != 1 || n != P) - throw std::invalid_argument("Matrices a and b should have same dimension."); + InvalidArgument("Matrices a and b should have same dimension."); c.Resize(O, P); @@ -4063,11 +4063,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::AssignElementProductOfWithShift(const GPUMatrix& a, const GPUMatrix& b, const size_t shift) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOfWithShift: Matrix is empty."); + LogicError("AssignElementProductOfWithShift: Matrix is empty."); assert(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); //int O = a.GetNumRows(); int P = a.GetNumCols(); @@ -4090,7 +4090,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUMatrix& GPUMatrix::DropFrame(const GPUMatrix& label, const GPUMatrix& gamma, const ElemType & threshhold) { if (IsEmpty()) - throw std::logic_error("DropFrame: Matrix is empty."); + LogicError("DropFrame: Matrix is empty."); PrepareDevice(); @@ -4112,7 +4112,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const GPUMatrix& dnnoutput, const GPUMatrix& gamma, ElemType alpha) { if (IsEmpty()) - throw std::logic_error("AssignSequenceError: Matrix is empty."); + LogicError("AssignSequenceError: Matrix is empty."); PrepareDevice(); @@ -4137,7 +4137,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUMatrix::LogAddSumOfElements() const { if (this->IsEmpty()) - throw std::logic_error("SumOfElements: Matrix is empty"); + LogicError("SumOfElements: Matrix is empty"); PrepareDevice(); ElemType* d_sum = NULL; @@ -4161,10 +4161,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { const GPUMatrix& pos_scores, const GPUMatrix& pair_scores, const int shift) { if (alpha.IsEmpty() || pos_scores.IsEmpty() || pair_scores.IsEmpty()) - throw std::logic_error("RCRFBackwardCompute: one of the input matrices is empty."); + LogicError("RCRFBackwardCompute: one of the input matrices is empty."); if (alpha.GetNumRows() != pos_scores.GetNumRows() || alpha.GetNumCols() != pos_scores.GetNumCols()) - throw std::logic_error("RCRFBackwardCompute: matrix dimensions mismatched."); + LogicError("RCRFBackwardCompute: matrix dimensions mismatched."); size_t iNumLab = alpha.GetNumRows(); size_t iNumPos = alpha.GetNumCols(); diff --git a/Math/Math/GPUMatrix.h b/Math/Math/GPUMatrix.h index 10b75e16d..e469eb26e 100644 --- a/Math/Math/GPUMatrix.h +++ b/Math/Math/GPUMatrix.h @@ -135,8 +135,8 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Reshape(const size_t numRows, const size_t numCols); void Resize(const size_t numRows, const size_t numCols, bool growOnly = true); //by default we only reallocate if need to grow - ElemType& operator() (const size_t /*row*/, const size_t /*col*/) { throw std::logic_error("GPUMatrix doesn't support this"); } - const ElemType& operator() (const size_t /*row*/, const size_t /*col*/) const { throw std::logic_error("GPUMatrix doesn't support this"); } + ElemType& operator() (const size_t /*row*/, const size_t /*col*/) { LogicError("GPUMatrix doesn't support this"); } + const ElemType& operator() (const size_t /*row*/, const size_t /*col*/) const { LogicError("GPUMatrix doesn't support this"); } ElemType Get00Element() const; void SetValue(const ElemType v); @@ -411,7 +411,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { size_t elsize; stream>>elsize; if (sizeof(ElemType)!=elsize) - throw std::logic_error("Template argument size doesn't match those in file"); + LogicError("Template argument size doesn't match those in file"); std::wstring matrixName; size_t numRows, numCols; int format; diff --git a/Math/Math/GPUSparseMatrix.cu b/Math/Math/GPUSparseMatrix.cu index bb0b57874..164d471a9 100644 --- a/Math/Math/GPUSparseMatrix.cu +++ b/Math/Math/GPUSparseMatrix.cu @@ -53,7 +53,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (matrixFormat != MatrixFormat::matrixFormatSparseCSC && matrixFormat != MatrixFormat::matrixFormatSparseCSR && matrixFormat != MatrixFormat::matrixFormatSparseBlockCol && matrixFormat != MatrixFormat::matrixFormatSparseBlockRow) { - throw std::logic_error("GPUSparseMatrix: unsupported sparse matrix format"); + LogicError("GPUSparseMatrix: unsupported sparse matrix format"); } m_computeDevice = (computeDevice == AUTOPLACEMATRIX) ? GPUMatrix::GetBestGPUDeviceId() : computeDevice; //current GPU device Id @@ -376,9 +376,9 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUSparseMatrix::ChangeDeviceTo(DEVICEID_TYPE to_id) { if (!OwnBuffer()) - throw std::logic_error("Cannot change device on Managed external matrix"); + LogicError("Cannot change device on Managed external matrix"); if (to_id == CPUDEVICE) - throw std::logic_error("to_id must be valid GPU"); + LogicError("to_id must be valid GPU"); if (m_computeDevice == to_id) return; @@ -634,7 +634,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (reallocate) { if (!OwnBuffer()) - throw logic_error("Cannot Resize since the buffer is managed externally."); + LogicError("Cannot Resize since the buffer is managed externally."); PrepareDevice(); @@ -697,7 +697,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const size_t nz, const size_t numRows, const size_t numCols, const bool IsOnDevice /*= false*/, const DEVICEID_TYPE devId /*= -1*/) { if (h_CSRRow == nullptr || h_Col == nullptr || h_Val == nullptr) - throw std::logic_error("SetMatrixFromCSRFormat: nullptr passed in."); + LogicError("SetMatrixFromCSRFormat: nullptr passed in."); SetComputeDeviceId(PrepareDevice(devId)); @@ -731,7 +731,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUSparseMatrix::GetMatrixFromCSRFormat(CPUSPARSE_INDEX_TYPE*& h_CSRRow, CPUSPARSE_INDEX_TYPE*& h_Col, ElemType*& h_Val, size_t &nz, size_t &numRows, size_t &numCols) const { if (h_CSRRow != nullptr || h_Col != nullptr || h_Val != nullptr) - throw std::logic_error("GetMatrixFromCSRFormat: Passed pointers must be nullptr"); + LogicError("GetMatrixFromCSRFormat: Passed pointers must be nullptr"); nz = GetNumNZElements(); numRows = GetNumRows(); @@ -772,7 +772,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const size_t nz, const size_t numRows, const size_t numCols, const bool IsOnDevice /*= false*/, const DEVICEID_TYPE devId /*= -1*/) { if (h_CSCCol == nullptr || h_Row == nullptr || h_Val == nullptr) - throw std::logic_error("SetMatrixFromCSCFormat: nullptr passed in."); + LogicError("SetMatrixFromCSCFormat: nullptr passed in."); SetComputeDeviceId(PrepareDevice(devId)); m_format = matrixFormatSparseCSC; @@ -805,7 +805,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUSparseMatrix::GetMatrixFromCSCFormat(GPUSPARSE_INDEX_TYPE*& h_CSCCol, GPUSPARSE_INDEX_TYPE*& h_Row, ElemType*& h_Val, size_t &nz, size_t &numRows, size_t &numCols) const { if (h_CSCCol != nullptr || h_Row != nullptr || h_Val != nullptr) - throw std::logic_error("GetMatrixFromCSCFormat: Passed pointers must be nullptr"); + LogicError("GetMatrixFromCSCFormat: Passed pointers must be nullptr"); nz = GetNumNZElements(); numRows = GetNumRows(); @@ -851,10 +851,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { const GPUSparseMatrix& rhs, const bool transposeB, ElemType beta, GPUMatrix& c) { if (lhs.GetComputeDeviceId() != rhs.GetComputeDeviceId() || (lhs.GetComputeDeviceId() != c.GetComputeDeviceId())) - throw std::runtime_error("MultiplyAndWeightedAdd: All matrices must be on the same GPU"); + RuntimeError("MultiplyAndWeightedAdd: All matrices must be on the same GPU"); if (lhs.IsEmpty() || rhs.IsEmpty()) - throw std::logic_error("MultiplyAndWeightedAdd: one of the input matrix is empty."); + LogicError("MultiplyAndWeightedAdd: one of the input matrix is empty."); int m = transposeA ? (int)lhs.GetNumCols() : (int)lhs.GetNumRows(); int k = transposeA ? (int)lhs.GetNumRows() : (int)lhs.GetNumCols(); @@ -865,7 +865,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert(k == l); if (k != l) { - throw std::invalid_argument("CPUSparseMatrix::MultiplyAndWeightedAdd: The inner dimensions of a and b must match."); + InvalidArgument("CPUSparseMatrix::MultiplyAndWeightedAdd: The inner dimensions of a and b must match."); } if (c.GetNumRows() != m || c.GetNumCols() != n) @@ -950,7 +950,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { const GPUSparseMatrix& rhs, const bool transposeB, GPUSparseMatrix& c) { if (lhs.GetComputeDeviceId()!=rhs.GetComputeDeviceId()) - throw std::runtime_error("GPUSparseMatrix::MultiplyAndAdd: All matrices must be on the same GPU"); + RuntimeError("GPUSparseMatrix::MultiplyAndAdd: All matrices must be on the same GPU"); int m = transposeA? (int)lhs.GetNumCols(): (int)lhs.GetNumRows(); int k = transposeA? (int)lhs.GetNumRows(): (int)lhs.GetNumCols(); @@ -961,7 +961,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert (k == l); if (k != l) { - throw std::invalid_argument("GPUSparseMatrix::MultiplyAndAdd: The inner dimensions of a and b must match."); + InvalidArgument("GPUSparseMatrix::MultiplyAndAdd: The inner dimensions of a and b must match."); } if (!transposeA && !transposeB) @@ -1095,10 +1095,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void GPUSparseMatrix::ScaleAndAdd(const ElemType alpha, const GPUSparseMatrix& lhs, GPUMatrix& rhs) { if (lhs.GetNumRows() != rhs.GetNumRows() || lhs.GetNumCols() != rhs.GetNumCols()) - throw std::logic_error("ScaleAndAdd: dimension mismatch"); + LogicError("ScaleAndAdd: dimension mismatch"); if (lhs.GetComputeDeviceId() != rhs.GetComputeDeviceId()) - throw std::runtime_error("GPUSparseMatrix::ScaleAndAdd: All matrices must be on the same GPU"); + RuntimeError("GPUSparseMatrix::ScaleAndAdd: All matrices must be on the same GPU"); if (lhs.m_format == matrixFormatSparseBlockCol || lhs.m_format == matrixFormatSparseBlockRow) { @@ -1269,7 +1269,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { NOT_IMPLEMENTED; if (a.GetComputeDeviceId()!=b.GetComputeDeviceId()||(b.GetComputeDeviceId()!=a.GetComputeDeviceId())) - throw std::runtime_error("MultiplyAndWeightedAdd: All matrices must be on the same GPU"); + RuntimeError("MultiplyAndWeightedAdd: All matrices must be on the same GPU"); a.PrepareDevice(); cusparseHandle_t cusparseHandle = 0; @@ -1416,7 +1416,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { NOT_IMPLEMENTED; if (S1.GetComputeDeviceId()!=S2.GetComputeDeviceId()) - throw std::runtime_error("Sparse matrix multiply: both matrices must be on the same device"); + RuntimeError("Sparse matrix multiply: both matrices must be on the same device"); S1.PrepareDevice(); cusparseHandle_t cusparseHandle = 0; @@ -1433,7 +1433,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { int k = int(transposeS1 ? S1.GetNumRows() : S1.GetNumCols()); int l = int(transposeS2 ? S2.GetNumCols() : S2.GetNumRows()); if (k!=l) - throw std::runtime_error("Sparse matrix multiply: dimensionality mismatch"); + RuntimeError("Sparse matrix multiply: dimensionality mismatch"); int nnzA = (int)S1.GetNumNZElements(); int nnzB = (int)S2.GetNumNZElements(); @@ -1486,9 +1486,9 @@ namespace Microsoft { namespace MSR { namespace CNTK { } if (a.GetNumCols() != b.GetNumCols() || a.GetNumRows() != b.GetNumRows()) - throw std::runtime_error("Dimensions mismatch in ScaleAndAdd"); + RuntimeError("Dimensions mismatch in ScaleAndAdd"); if (a.GetComputeDeviceId()!=b.GetComputeDeviceId()) - throw std::runtime_error("ScaleAndAdd: matrices must be on the same device"); + RuntimeError("ScaleAndAdd: matrices must be on the same device"); int m = (int)a.GetNumRows(); int n = (int)a.GetNumCols(); @@ -1538,9 +1538,9 @@ namespace Microsoft { namespace MSR { namespace CNTK { NOT_IMPLEMENTED; if (a.GetNumRows() != b.GetNumRows() || a.GetNumRows() != c.GetNumRows() || a.GetNumCols() != b.GetNumCols() || a.GetNumCols() != c.GetNumCols()) - throw std::logic_error("ScaleAndAdd: dimension mismatch"); + LogicError("ScaleAndAdd: dimension mismatch"); if (a.GetComputeDeviceId()!=b.GetComputeDeviceId()||a.GetComputeDeviceId()!=c.GetComputeDeviceId()) - throw std::runtime_error("ScaleAndAdd: matrices must be on the same device"); + RuntimeError("ScaleAndAdd: matrices must be on the same device"); b.PrepareDevice(); //copy b to c CUDA_CALL(cudaMemcpy(c.BufferPointer(),b.BufferPointer(),sizeof(ElemType)*b.GetNumElements(),cudaMemcpyDeviceToDevice)); @@ -1585,12 +1585,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (a.GetComputeDeviceId() != c.GetComputeDeviceId()) { - throw std::invalid_argument("All matrices must be on the same GPU"); + InvalidArgument("All matrices must be on the same GPU"); } else { if (a.IsEmpty()) - throw std::logic_error("ElementWisePower: The input matrix a is empty."); + LogicError("ElementWisePower: The input matrix a is empty."); c.ResizeAsAndCopyIndexFrom(a); @@ -1613,7 +1613,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { NOT_IMPLEMENTED; if (a.GetComputeDeviceId()!=b.GetComputeDeviceId()) - throw std::runtime_error("a and b must be on the same device"); + RuntimeError("a and b must be on the same device"); int m = (int)a.GetNumRows(); int n = (int)a.GetNumCols(); @@ -1791,7 +1791,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { NOT_IMPLEMENTED; if (a.GetNumRows()!=b.GetNumRows()||a.GetNumCols()!=b.GetNumCols()) - throw std::logic_error("ElementProductOf: matrix dimensions mismatch"); + LogicError("ElementProductOf: matrix dimensions mismatch"); b.PrepareDevice(); GPUMatrix c(b.GetNumRows(),b.GetNumCols(),b.GetComputeDeviceId()); @@ -1931,10 +1931,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUSparseMatrix& GPUSparseMatrix::AssignTransposeOf(const GPUSparseMatrix& a) { if (this == &a) - throw std::logic_error("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); + LogicError("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); if (a.IsEmpty()) - throw std::logic_error("AssignTransposeOf: Matrix a is empty."); + LogicError("AssignTransposeOf: Matrix a is empty."); *this = a.Transpose(); return *this; @@ -1956,7 +1956,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { int n = (int)GetNumCols(); //if (numCols == 0) - // throw std::logic_error("The slice cannot have 0 columns."); + // LogicError("The slice cannot have 0 columns."); if (startColumn + numCols > n) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int)startColumn, (int)numCols, (int)n); @@ -2020,7 +2020,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUSparseMatrix::SumOfAbsElements() const { if (IsEmpty()) - throw std::logic_error("SumOfAbsElements: Matrix is empty"); + LogicError("SumOfAbsElements: Matrix is empty"); cublasHandle_t cuHandle = GPUMatrix::GetCublasHandle(GetComputeDeviceId()); if (sizeof(ElemType)==sizeof(float)) @@ -2041,7 +2041,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUSparseMatrix::SumOfElements() const { if (IsEmpty()) - throw std::logic_error("SumOfElements: Matrix is empty"); + LogicError("SumOfElements: Matrix is empty"); PrepareDevice(); ElemType* d_sum = nullptr; @@ -2059,7 +2059,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUSparseMatrix::FrobeniusNorm() const { if (IsEmpty()) - throw std::logic_error("FrobeniusNorm: Matrix is empty."); + LogicError("FrobeniusNorm: Matrix is empty."); ElemType* d_sum = nullptr; ElemType h_sum=0; @@ -2078,7 +2078,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUSparseMatrix::MatrixNormInf() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm1: Matrix is empty."); + LogicError("MatrixNorm1: Matrix is empty."); ElemType* d_maxAbs = nullptr; ElemType h_maxAbs=0; @@ -2097,7 +2097,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType GPUSparseMatrix::MatrixNorm1() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm1: Matrix is empty."); + LogicError("MatrixNorm1: Matrix is empty."); return SumOfAbsElements(); } @@ -2109,7 +2109,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUSparseMatrix& GPUSparseMatrix::ElementInverse () { if (IsEmpty()) - throw std::logic_error("ElementInverse: Matrix is empty."); + LogicError("ElementInverse: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumNZElements(); int blocksPerGrid =(int)ceil(1.0*N/threadsPerBlock); @@ -2238,7 +2238,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUSparseMatrix& GPUSparseMatrix::InplaceTruncateBottom (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateBottom: Matrix is empty."); + LogicError("InplaceTruncateBottom: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumNZElements(); int blocksPerGrid =(int)ceil(N*1.0/threadsPerBlock); cudaEvent_t done = nullptr; @@ -2254,7 +2254,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUSparseMatrix& GPUSparseMatrix::AssignTruncateBottomOf (const GPUSparseMatrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateBottomOf: Matrix a is empty."); + LogicError("AssignTruncateBottomOf: Matrix a is empty."); if (this!=&a) { @@ -2276,7 +2276,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUSparseMatrix& GPUSparseMatrix::InplaceTruncateTop (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateTop: Matrix is empty."); + LogicError("InplaceTruncateTop: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumNZElements(); int blocksPerGrid =(int)ceil(N*1.0/threadsPerBlock); cudaEvent_t done = nullptr; @@ -2292,7 +2292,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUSparseMatrix& GPUSparseMatrix::AssignTruncateTopOf (const GPUSparseMatrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateTopOf: Matrix a is empty."); + LogicError("AssignTruncateTopOf: Matrix a is empty."); if (this!=&a) { @@ -2314,7 +2314,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { GPUSparseMatrix& GPUSparseMatrix::SetToZeroIfAbsLessThan (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("SetToZeroIfAbsLessThan: Matrix is empty."); + LogicError("SetToZeroIfAbsLessThan: Matrix is empty."); CUDA_LONG N=(CUDA_LONG)GetNumNZElements(); int blocksPerGrid =(int)ceil(N*1.0/threadsPerBlock); cudaEvent_t done = nullptr; @@ -2427,7 +2427,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { size_t elsize; stream>>elsize; if (sizeof(ElemType)!=elsize) - throw std::runtime_error("Template argument size doesn't match those in file"); + RuntimeError("Template argument size doesn't match those in file"); std::wstring matrixName; // now prepare this header to receive the data being read diff --git a/Math/Math/Matrix.cpp b/Math/Math/Matrix.cpp index 2129bf1ab..6a609e87d 100755 --- a/Math/Math/Matrix.cpp +++ b/Math/Math/Matrix.cpp @@ -64,7 +64,7 @@ } \ else \ { \ - throw std::runtime_error("Matrices do not exist in either CPU or GPU."); \ + RuntimeError("Matrices do not exist in either CPU or GPU."); \ } \ } @@ -104,7 +104,7 @@ } \ else \ { \ - throw std::runtime_error("Matrices do not exist in either CPU or GPU."); \ + RuntimeError("Matrices do not exist in either CPU or GPU."); \ } \ } @@ -161,7 +161,7 @@ } \ else \ { \ - throw std::runtime_error("Matrices do not exist in either CPU or GPU."); \ + RuntimeError("Matrices do not exist in either CPU or GPU."); \ } \ } @@ -296,7 +296,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix::Matrix(FILE* f, const char * matrixName, DEVICEID_TYPE deviceId, const MatrixType matrixType) { if (deviceId == MANAGEDEXTERN) - throw runtime_error("Externally Managed Matrix must use the basic constructor, then SetValue()\n"); + RuntimeError("Externally Managed Matrix must use the basic constructor, then SetValue()\n"); Init(deviceId); @@ -334,7 +334,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix::Matrix(const size_t numRows, const size_t numCols, DEVICEID_TYPE deviceId, const MatrixType matrixType, const MatrixFormat matrixFormat) { if (deviceId == MANAGEDEXTERN) - throw runtime_error("Externally Managed Matrix must use the basic constructor, then SetValue(), or the full constructor\n"); + RuntimeError("Externally Managed Matrix must use the basic constructor, then SetValue(), or the full constructor\n"); Init(deviceId); @@ -417,7 +417,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix::Matrix(const Matrix& deepCopyFrom, DEVICEID_TYPE deviceId) { if (deviceId == MANAGEDEXTERN) - throw runtime_error("Externally Managed Matrix must use the basic constructor, then SetValue(), or the full constructor\n"); + RuntimeError("Externally Managed Matrix must use the basic constructor, then SetValue(), or the full constructor\n"); int origCopyFromDeviceId = deepCopyFrom.GetDeviceId(); @@ -662,7 +662,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Unknown matrix type"); + RuntimeError("Unknown matrix type"); } } @@ -783,7 +783,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Unknown matrix type"); + RuntimeError("Unknown matrix type"); } return slice; @@ -888,7 +888,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Unknown matrix type"); + RuntimeError("Unknown matrix type"); } return diag; @@ -1061,7 +1061,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix Matrix::Transpose() { if (IsEmpty()) - throw std::logic_error("Transpose: Matrix is empty."); + LogicError("Transpose: Matrix is empty."); Matrix c(this->GetNumCols(), this->GetNumRows(), (DEVICEID_TYPE)this->GetDeviceId()); c.AssignTransposeOf(*this); @@ -1090,7 +1090,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (IsEmpty()) // if empty then we are done return; - //throw std::logic_error("SetValue: Matrix is empty."); + //LogicError("SetValue: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1106,13 +1106,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if (IsEmpty()) // if empty then we are done return; - //throw std::logic_error("SetValue: Matrix is empty."); + //LogicError("SetValue: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, this, m_CPUMatrix->SetValue(*db_number.ExposePointer2Value()), if (GetDeviceId()!=db_number.GetDeviceId()) - throw std::runtime_error("Matrix and device bound number must be on the same device"); + RuntimeError("Matrix and device bound number must be on the same device"); m_GPUMatrix->SetValue(db_number.ExposePointer2Value()), NOT_IMPLEMENTED, NOT_IMPLEMENTED @@ -1127,7 +1127,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SetColumn(const ElemType* colPointer, size_t colInd) { if (colPointer == nullptr) - throw std::invalid_argument("SetColumn: colPointer is null."); + InvalidArgument("SetColumn: colPointer is null."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1188,7 +1188,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SetValue(const size_t numRows, const size_t numCols, ElemType *pArray, const size_t matrixFlags, int deviceId) { if (pArray == nullptr) - throw std::invalid_argument("Invalid pArray."); + InvalidArgument("Invalid pArray."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1229,10 +1229,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SetDiagonalValue(const ElemType v) { if (IsEmpty()) - throw std::logic_error("SetDiagonalValue: Matrix is empty."); + LogicError("SetDiagonalValue: Matrix is empty."); if (GetNumRows() != GetNumCols()) - throw std::logic_error("SetDiagonalValue: NumRows and NumCols do not agree."); + LogicError("SetDiagonalValue: NumRows and NumCols do not agree."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1247,13 +1247,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SetDiagonalValue(const Matrix& vector) { if (IsEmpty() || vector.IsEmpty()) - throw std::logic_error("SetDiagonalValue: Matrix is empty."); + LogicError("SetDiagonalValue: Matrix is empty."); if (GetNumRows() != GetNumCols()) - throw std::logic_error("SetDiagonalValue: NumRows and NumCols do not agree."); + LogicError("SetDiagonalValue: NumRows and NumCols do not agree."); if (vector.GetNumRows() != 1 && vector.GetNumCols() != 1) - throw std::logic_error("SetDiagonalValue: input vector must be a vector."); + LogicError("SetDiagonalValue: input vector must be a vector."); DecideAndMoveToRightDevice(*this, vector); @@ -1268,7 +1268,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ); } else if (vector.GetNumRows() != GetNumRows()) - throw std::logic_error("SetDiagonalValue: input vector's dimension does not agree with [this]."); + LogicError("SetDiagonalValue: input vector's dimension does not agree with [this]."); else { //WARNING: we use this pointer to decide which function to call. However, vector may be stored in a different matrix type (DENSE, SPARSE) @@ -1286,7 +1286,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SetUniformRandomValue(const ElemType low, const ElemType high, unsigned long seed) { if (IsEmpty()) - throw std::logic_error("SetUniformRandomValue: Matrix is empty."); + LogicError("SetUniformRandomValue: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1301,10 +1301,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SetGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) - throw std::invalid_argument("SetUniformRandomValue: sigma must be a positive value."); + InvalidArgument("SetUniformRandomValue: sigma must be a positive value."); if (IsEmpty()) - throw std::logic_error("SetUniformRandomValue: Matrix is empty."); + LogicError("SetUniformRandomValue: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1319,10 +1319,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::AddGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) - throw std::invalid_argument("SetUniformRandomValue: sigma must be a positive value."); + InvalidArgument("SetUniformRandomValue: sigma must be a positive value."); if (IsEmpty()) - throw std::logic_error("SetUniformRandomValue: Matrix is empty."); + LogicError("SetUniformRandomValue: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1339,7 +1339,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SetUniformRandomMask(const ElemType maskRate, const ElemType scaleValue, unsigned long seed) { if (IsEmpty()) - throw std::logic_error("SetUniformRandomMask: Matrix is empty."); + LogicError("SetUniformRandomMask: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -1548,7 +1548,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignSumOf(const ElemType alpha, const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSumOf: Matrix a is empty."); + LogicError("AssignSumOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -1792,7 +1792,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else { - throw std::runtime_error("Matrices do not exist in either CPU or GPU."); + RuntimeError("Matrices do not exist in either CPU or GPU."); } return *this; @@ -1889,7 +1889,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignDifferenceOf(const ElemType alpha, const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignDifferenceOf: Matrix a is empty."); + LogicError("AssignDifferenceOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -1909,7 +1909,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignDifferenceOf(const Matrix& a, const ElemType alpha) { if (a.IsEmpty()) - throw std::logic_error("AssignDifferenceOf: Matrix a is empty."); + LogicError("AssignDifferenceOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -1932,7 +1932,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::operator-= (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("Minus Operation: Matrix a is empty."); + LogicError("Minus Operation: Matrix a is empty."); DecideAndMoveToRightDevice(*this, a); DISPATCH_MATRIX_ON_FLAG(this, @@ -2136,11 +2136,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignElementProductOf (const Matrix& a, const Matrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOf: Matrix is empty."); + LogicError("AssignElementProductOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); DecideAndMoveToRightDevice(a, b, *this); if (!(a.GetMatrixType() == b.GetMatrixType())) @@ -2162,14 +2162,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AddElementProductOf (const Matrix& a, const Matrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AddElementProductOf: Matrix is empty."); + LogicError("AddElementProductOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match [this]."); + InvalidArgument("The input matrix dimensions do not match [this]."); DecideAndMoveToRightDevice(*this, a, b); @@ -2192,11 +2192,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignElementDivisionOf (const Matrix& a, const Matrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementDivisionOf: Matrix is empty."); + LogicError("AssignElementDivisionOf: Matrix is empty."); assert (a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); DecideAndMoveToRightDevice(a, b, *this); //WARNING: a and b must have same type @@ -2221,10 +2221,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::ColumnElementMultiplyWith(const Matrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("ColumnElementMultiplyWith: Matrix is empty."); + LogicError("ColumnElementMultiplyWith: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) - throw std::invalid_argument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); + InvalidArgument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); DecideAndMoveToRightDevice(*this, a); //WARNING: a and this must have same type @@ -2248,10 +2248,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::RowElementMultiplyWith(const Matrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("RowElementMultiplyWith: Matrix is empty."); + LogicError("RowElementMultiplyWith: Matrix is empty."); if (!(a.GetNumCols() == GetNumCols() && a.GetNumRows() == 1)) - throw std::invalid_argument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); + InvalidArgument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); //WARNING: a and this must have same type if (! (GetMatrixType() == a.GetMatrixType())) @@ -2274,10 +2274,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::RowElementDivideBy(const Matrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("RowElementDivideBy: Matrix is empty."); + LogicError("RowElementDivideBy: Matrix is empty."); if (!(a.GetNumCols() == GetNumCols() && a.GetNumRows() == 1)) - throw std::invalid_argument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); + InvalidArgument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); //WARNING: a and this must have same type if (!(GetMatrixType() == a.GetMatrixType())) @@ -2301,10 +2301,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::ColumnElementDivideBy(const Matrix& a) { if (a.IsEmpty() || IsEmpty()) - throw std::logic_error("ColumnElementDivideBy: Matrix is empty."); + LogicError("ColumnElementDivideBy: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) - throw std::invalid_argument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); + InvalidArgument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); DecideAndMoveToRightDevice(*this, a); //WARNING: a and this must have same type @@ -2344,7 +2344,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignElementInverseOf (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignElementInverseOf: Matrix a is empty."); + LogicError("AssignElementInverseOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); this->SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2526,7 +2526,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignLogSoftmaxOf (const Matrix& a, const bool isColWise) { if (a.IsEmpty()) - throw std::logic_error("AssignLogSoftmaxOf: Matrix a is empty."); + LogicError("AssignLogSoftmaxOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2559,7 +2559,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignSqrtOf (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSqrtOf: Matrix a is empty."); + LogicError("AssignSqrtOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2595,7 +2595,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignExpOf (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignExpOf: Matrix a is empty."); + LogicError("AssignExpOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2630,7 +2630,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignAbsOf (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignAbsOf: Matrix a is empty."); + LogicError("AssignAbsOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2680,7 +2680,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignLogOf (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignLogOf: Matrix a is empty."); + LogicError("AssignLogOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2700,7 +2700,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignLog10Of (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignLogOf: Matrix a is empty."); + LogicError("AssignLogOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2735,7 +2735,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignCosineOf (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignCosineOf: Matrix a is empty."); + LogicError("AssignCosineOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2770,7 +2770,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignNegativeSineOf (const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignNegativeSineOf: Matrix a is empty."); + LogicError("AssignNegativeSineOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -2790,7 +2790,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::InplaceTruncate(const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncate: Matrix is empty."); + LogicError("InplaceTruncate: Matrix is empty."); if (sizeof(ElemType)==sizeof(float)) { @@ -2820,7 +2820,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { assert(threshold >= 0); if (IsEmpty()) - throw std::logic_error("InplaceSoftThreshold: Matrix is empty."); + LogicError("InplaceSoftThreshold: Matrix is empty."); if (threshold == 0) return *this; @@ -2840,7 +2840,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::InplaceTruncateBottom (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateBottom: Matrix is empty."); + LogicError("InplaceTruncateBottom: Matrix is empty."); if (sizeof(ElemType)==sizeof(float)) { @@ -2869,7 +2869,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignTruncateBottomOf (const Matrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateBottomOf: Matrix a is empty."); + LogicError("AssignTruncateBottomOf: Matrix a is empty."); if (sizeof(ElemType)==sizeof(float)) { @@ -2907,7 +2907,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::InplaceTruncateTop (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("InplaceTruncateTop: Matrix is empty."); + LogicError("InplaceTruncateTop: Matrix is empty."); if (sizeof(ElemType)==sizeof(float)) { @@ -2935,7 +2935,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignTruncateTopOf (const Matrix& a, const ElemType threshold) { if (a.IsEmpty()) - throw std::logic_error("AssignTruncateTopOf: Matrix a is empty."); + LogicError("AssignTruncateTopOf: Matrix a is empty."); if (sizeof(ElemType)==sizeof(float)) { @@ -2973,7 +2973,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::SetToZeroIfAbsLessThan (const ElemType threshold) { if (IsEmpty()) - throw std::logic_error("SetToZeroIfAbsLessThan: Matrix is empty."); + LogicError("SetToZeroIfAbsLessThan: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, this, @@ -2991,7 +2991,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::SumOfElements () const { if (IsEmpty()) - throw std::logic_error("SumOfElements: Matrix is empty."); + LogicError("SumOfElements: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, nullptr, @@ -3007,7 +3007,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignSumOfElements(const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSumOfElements: Matrix a is empty."); + LogicError("AssignSumOfElements: Matrix a is empty."); //WARNING: a and this must have same type if (!(GetMatrixType() == a.GetMatrixType())) @@ -3047,7 +3047,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::SumOfAbsElements () const { if (IsEmpty()) - throw std::logic_error("SumOfAbsElements: Matrix is empty."); + LogicError("SumOfAbsElements: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, nullptr, @@ -3063,7 +3063,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::LogAddSumOfElements() const { if (IsEmpty()) - throw std::logic_error("LogAddSumOfElements: Matrix is empty."); + LogicError("LogAddSumOfElements: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, nullptr, @@ -3100,7 +3100,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::VectorNorm1(Matrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNormInf: Matrix is empty."); + LogicError("VectorNormInf: Matrix is empty."); DecideAndMoveToRightDevice(*this, c); c.SwitchToMatrixType(GetMatrixType(), GetFormat(), false); @@ -3125,7 +3125,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::VectorNorm2(Matrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNorm2: Matrix is empty."); + LogicError("VectorNorm2: Matrix is empty."); DecideAndMoveToRightDevice(*this, c); c.SwitchToMatrixType(GetMatrixType(), GetFormat(), false); @@ -3150,7 +3150,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::VectorNormInf(Matrix& c, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorNormInf: Matrix is empty."); + LogicError("VectorNormInf: Matrix is empty."); DecideAndMoveToRightDevice(*this, c); c.SwitchToMatrixType(GetMatrixType(), GetFormat(), false); @@ -3183,11 +3183,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignKhatriRaoProductOf(const Matrix& a, const Matrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignKhatriRaoProductOf: Matrix is empty."); + LogicError("AssignKhatriRaoProductOf: Matrix is empty."); assert (a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("AssignKhatriRaoProductOf: The input matrix dimensions do not match."); + InvalidArgument("AssignKhatriRaoProductOf: The input matrix dimensions do not match."); DecideAndMoveToRightDevice(a, b, *this); //WARNING: a and b must have same type @@ -3217,11 +3217,11 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AddColumnReshapeProductOf(const Matrix& a, const Matrix& b, const bool transposeAColumn) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AddColumnReshapeProductOf: Matrix is empty."); + LogicError("AddColumnReshapeProductOf: Matrix is empty."); assert (a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("AddColumnReshapeProductOf: The input matrix dimensions do not match."); + InvalidArgument("AddColumnReshapeProductOf: The input matrix dimensions do not match."); DecideAndMoveToRightDevice(*this, a, b); //WARNING: a and b must have same type @@ -3250,7 +3250,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::FrobeniusNorm() const { if (IsEmpty()) - throw std::logic_error("FrobeniusNorm: Matrix is empty."); + LogicError("FrobeniusNorm: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, nullptr, @@ -3265,7 +3265,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignFrobeniusNormOf(const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignFrobeniusNormOf: Matrix a is empty."); + LogicError("AssignFrobeniusNormOf: Matrix a is empty."); this->Resize(1,1); @@ -3290,7 +3290,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::MatrixNormInf() const { if (IsEmpty()) - throw std::logic_error("MatrixNormInf: Matrix is empty."); + LogicError("MatrixNormInf: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, nullptr, @@ -3305,7 +3305,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::MatrixNorm1() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm1: Matrix is empty."); + LogicError("MatrixNorm1: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, nullptr, @@ -3321,7 +3321,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::MatrixNorm0() const { if (IsEmpty()) - throw std::logic_error("MatrixNorm0: Matrix is empty."); + LogicError("MatrixNorm0: Matrix is empty."); DISPATCH_MATRIX_ON_FLAG(this, nullptr, @@ -3336,7 +3336,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignSignOf(const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AssignSignOf: Matrix a is empty."); + LogicError("AssignSignOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); //WARNING: a and this must have same type @@ -3360,7 +3360,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AddSignOf(const Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("AddSignOf: Matrix a is empty."); + LogicError("AddSignOf: Matrix a is empty."); DecideAndMoveToRightDevice(a, *this); if (!(GetMatrixType() == a.GetMatrixType())) @@ -3382,7 +3382,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::VectorMax(Matrix& maxIndexes, Matrix& maxValues, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorMax: Matrix is empty."); + LogicError("VectorMax: Matrix is empty."); DecideAndMoveToRightDevice(*this, maxIndexes, maxValues); maxIndexes.SwitchToMatrixType(GetMatrixType(), GetFormat(), false); @@ -3402,7 +3402,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::VectorMin(Matrix& minIndexes, Matrix& minValues, const bool isColWise) const { if (IsEmpty()) - throw std::logic_error("VectorMin: Matrix is empty."); + LogicError("VectorMin: Matrix is empty."); DecideAndMoveToRightDevice(*this, minIndexes, minValues); minIndexes.SwitchToMatrixType(GetMatrixType(), GetFormat(), false); @@ -3545,7 +3545,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (this->OwnBuffer()) _transferFromDeviceToDevice(from_id, to_id, ismoved, emptyTransfer); else - throw std::runtime_error("Cannot move externally owned matrices to the preferred device."); + RuntimeError("Cannot move externally owned matrices to the preferred device."); } template @@ -3563,7 +3563,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (from_id == to_id) { if (from_id != GetDeviceId()) - throw std::runtime_error("Trying to transfer matrix from device to the same device while the matrix does not live in the from device."); + RuntimeError("Trying to transfer matrix from device to the same device while the matrix does not live in the from device."); return; } @@ -3592,7 +3592,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (from_id == CPUDEVICE) //from CPU to GPU { if (m_CPUSparseMatrix == NULL) - throw std::logic_error("Can't move from CPU because I'm not there!"); + LogicError("Can't move from CPU because I'm not there!"); if (m_GPUSparseMatrix == NULL) m_GPUSparseMatrix = new GPUSparseMatrix(m_CPUSparseMatrix->GetFormat(), to_id); @@ -3618,7 +3618,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else //from GPU { if (m_GPUSparseMatrix == NULL || m_GPUSparseMatrix->GetComputeDeviceId() != from_id) - throw std::logic_error("This matrix isn't on this (or any?) GPU"); + LogicError("This matrix isn't on this (or any?) GPU"); if (to_id < 0) //to CPU { @@ -3653,7 +3653,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { if (from_id == CPUDEVICE) //from CPU to GPU { if (m_CPUMatrix==NULL) - throw std::logic_error("Can't move from CPU because I'm not there!"); + LogicError("Can't move from CPU because I'm not there!"); if (m_GPUMatrix!=NULL) delete m_GPUMatrix; if (m_CPUMatrix->GetNumElements() !=0 && !emptyTransfer) @@ -3678,7 +3678,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { else //from GPU { if (m_GPUMatrix==NULL || m_GPUMatrix->GetComputeDeviceId()!=from_id) - throw std::logic_error("This matrix isn't on this (or any?) GPU"); + LogicError("This matrix isn't on this (or any?) GPU"); if (to_id < 0) //to CPU { @@ -3739,7 +3739,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::Print(const char* matrixName, size_t rowStart, size_t rowEnd, size_t colStart, size_t colEnd) const { if (IsEmpty()) - throw std::logic_error("Print: Matrix is empty."); + LogicError("Print: Matrix is empty."); DEVICEID_TYPE orgdevice = this->GetDeviceId(); DISPATCH_MATRIX_ON_FLAG(this, @@ -3931,7 +3931,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignNoiseContrastiveEstimation(const Matrix& a, const Matrix& b, const Matrix& c, const Matrix& bias, Matrix& tmp) { if (a.IsEmpty() || b.IsEmpty() || c.IsEmpty()) - throw std::logic_error("AssignNoiseContrastiveEstimation: one of the input matrices is empty."); + LogicError("AssignNoiseContrastiveEstimation: one of the input matrices is empty."); if (a.GetDeviceId() != b.GetDeviceId() || b.GetDeviceId() != c.GetDeviceId() || c.GetDeviceId() != this->GetDeviceId()) NOT_IMPLEMENTED; @@ -3959,7 +3959,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignNCEDerivative(const Matrix& tmp, const Matrix& a, const Matrix& b, const Matrix& c, size_t inputIndex) { if (a.IsEmpty() || b.IsEmpty() || c.IsEmpty()) - throw std::logic_error("AssignNoiseContrastiveEstimation: one of the input matrices is empty."); + LogicError("AssignNoiseContrastiveEstimation: one of the input matrices is empty."); if (a.GetDeviceId() != b.GetDeviceId() || b.GetDeviceId() != c.GetDeviceId() || c.GetDeviceId() != this->GetDeviceId()) NOT_IMPLEMENTED; @@ -4014,7 +4014,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::SVD(const Matrix& A, Matrix& SIGMA, Matrix& U, Matrix& VT, Matrix& W) { if (A.IsEmpty() ) - throw std::logic_error("SVD: the input matrix is empty."); + LogicError("SVD: the input matrix is empty."); DecideAndMoveToRightDevice(A, SIGMA, U); VT._transferToDevice(A.GetDeviceId()); @@ -4053,7 +4053,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType beta, Matrix& c) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("MultiplyAndWeightedAdd: one of the input matrix is empty."); + LogicError("MultiplyAndWeightedAdd: one of the input matrix is empty."); DecideAndMoveToRightDevice(a,b,c); @@ -4205,7 +4205,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { /*static*/void Matrix::ScaleAndAdd(ElemType alpha, const Matrix& a, Matrix& c) { if (a.IsEmpty() || c.IsEmpty()) - throw std::logic_error("ScaleAndAdd: one of the input matrices is empty."); + LogicError("ScaleAndAdd: one of the input matrices is empty."); DecideAndMoveToRightDevice(c, a); @@ -4444,7 +4444,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::Scale(ElemType alpha, Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("Scale: Input matrix a is empty."); + LogicError("Scale: Input matrix a is empty."); DISPATCH_MATRIX_ON_FLAG(&a, &a, @@ -4463,7 +4463,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::Scale(const Matrix& alpha, Matrix& a) { if (a.IsEmpty()) - throw std::logic_error("Scale: Input matrix a is empty."); + LogicError("Scale: Input matrix a is empty."); DecideAndMoveToRightDevice(a,alpha); @@ -4484,7 +4484,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::InnerProduct (const Matrix& a, const Matrix& b, Matrix& c, const bool isColWise) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProduct: one of the input matrix is empty."); + LogicError("InnerProduct: one of the input matrix is empty."); DecideAndMoveToRightDevice(a, b, c); @@ -4507,7 +4507,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { ElemType Matrix::InnerProductOfMatrices(const Matrix& a, const Matrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProductOfMatrices: one of the input matrices is empty."); + LogicError("InnerProductOfMatrices: one of the input matrices is empty."); DecideAndMoveToRightDevice(a,b); @@ -4537,7 +4537,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignInnerProductOfMatrices(const Matrix& a, const Matrix& b) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProductOfMatrices: one of the input matrices is empty."); + LogicError("InnerProductOfMatrices: one of the input matrices is empty."); this->Resize(1,1); @@ -4567,7 +4567,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::ElementWisePower (ElemType alpha, const Matrix& a, Matrix& c) { if (a.IsEmpty()) - throw std::logic_error("Scale: The input matrix a is empty."); + LogicError("Scale: The input matrix a is empty."); DecideAndMoveToRightDevice(a, c); c.SwitchToMatrixType(a.GetMatrixType(), a.GetFormat(), false); @@ -4585,7 +4585,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { bool Matrix::AreEqual(const Matrix& a, const Matrix& b, const ElemType threshold /*= 1e-8*/) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AreEqual: one of the input matrices is empty."); + LogicError("AreEqual: one of the input matrices is empty."); if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) return false; @@ -4619,7 +4619,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { bool Matrix::HasElement(const Matrix& a, const ElemType value) { if (a.IsEmpty()) - throw std::logic_error("HasElement: input matrix is empty."); + LogicError("HasElement: input matrix is empty."); DISPATCH_MATRIX_ON_FLAG(&a, &a, @@ -4693,7 +4693,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { { assert(y > 0); if (y <= 0) - throw std::logic_error("y is smaller than zero"); + LogicError("y is smaller than zero"); return x - y * floor(x / y); } @@ -4728,7 +4728,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::Shift(const Matrix& a, int shift) { if (a.IsEmpty()) - throw std::logic_error("Shift: Matrix is empty."); + LogicError("Shift: Matrix is empty."); else LogicError("Shift: BUGBUG This function currently leaves uninitialized values. Fix the code or contact fseide@microsoft.com."); @@ -4751,14 +4751,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignElementProductOfWithShiftNeg(const Matrix& a, const Matrix& b, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOfWithShiftNeg: Matrix is empty."); + LogicError("AssignElementProductOfWithShiftNeg: Matrix is empty."); assert(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); if (a.GetNumRows() != 1) - throw std::invalid_argument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); + InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); DecideAndMoveToRightDevice(a, b, *this); if (!(a.GetMatrixType() == b.GetMatrixType())) @@ -4787,7 +4787,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::InnerProductWithShiftNeg(const Matrix& a, const Matrix& b, Matrix& c, const bool isColWise, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProduct: one of the input matrix is empty."); + LogicError("InnerProduct: one of the input matrix is empty."); DecideAndMoveToRightDevice(a, b, c); @@ -4811,7 +4811,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::GetARowByIndex(const Matrix& a, size_t index) { if (a.IsEmpty()) - throw std::logic_error("GetARowByIndex: Matrix is empty."); + LogicError("GetARowByIndex: Matrix is empty."); //WARNING: a and this must have same type @@ -4836,7 +4836,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { void Matrix::ConductRowElementMultiplyWithShift(const Matrix& a, const Matrix& b, Matrix& c, size_t shift, bool bFirstmatrixfixed) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("InnerProduct: one of the input matrix is empty."); + LogicError("InnerProduct: one of the input matrix is empty."); DecideAndMoveToRightDevice(a, b, c); @@ -4859,14 +4859,14 @@ namespace Microsoft { namespace MSR { namespace CNTK { Matrix& Matrix::AssignElementProductOfWithShift(const Matrix& a, const Matrix& b, size_t shift) { if (a.IsEmpty() || b.IsEmpty()) - throw std::logic_error("AssignElementProductOfWithShift: Matrix is empty."); + LogicError("AssignElementProductOfWithShift: Matrix is empty."); assert(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) - throw std::invalid_argument("The input matrix dimensions do not match."); + InvalidArgument("The input matrix dimensions do not match."); if (a.GetNumRows() != 1) - throw std::invalid_argument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); + InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); DecideAndMoveToRightDevice(a, b, *this); if (!(a.GetMatrixType() == b.GetMatrixType())) @@ -4951,7 +4951,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { DecideAndMoveToRightDevice(*this, label, gamma); if (label.GetNumCols() != gamma.GetNumCols() || label.GetNumRows() != gamma.GetNumRows()) - throw std::logic_error("DropFrame: label matrix is not in the same size as gamm matrix."); + LogicError("DropFrame: label matrix is not in the same size as gamm matrix."); this->SwitchToMatrixType(label.GetMatrixType(), label.GetFormat(), false); DISPATCH_MATRIX_ON_FLAG(this, diff --git a/Math/Math/MatrixQuantizerGPU.cu b/Math/Math/MatrixQuantizerGPU.cu index 4c5f59bae..f65e3cb34 100644 --- a/Math/Math/MatrixQuantizerGPU.cu +++ b/Math/Math/MatrixQuantizerGPU.cu @@ -24,7 +24,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { bool dieoncudafailure = true; if (!dieoncudafailure) { - throw std::runtime_error(msg); + RuntimeError(msg); } fprintf(stderr, "%s\n", msg); fprintf(stderr, "cudafail: terminating\n"), fflush(stderr); diff --git a/Math/Math/MatrixQuantizer_kernel.cu b/Math/Math/MatrixQuantizer_kernel.cu index a10d3c71f..02c23cdd8 100644 --- a/Math/Math/MatrixQuantizer_kernel.cu +++ b/Math/Math/MatrixQuantizer_kernel.cu @@ -218,10 +218,10 @@ namespace Microsoft { namespace MSR { namespace CNTK { /* verify buffer allocation size if (msra::math::matrixquantizer::buffersize(bits, rows(), cols()) != gpubuffer.size()) - throw std::logic_error("quantizestripe: dimension of patch to be quantized does not match allocated buffer size for quantized data"); + LogicError("quantizestripe: dimension of patch to be quantized does not match allocated buffer size for quantized data"); if (rows() != curresidual.rows() || cols() != curresidual.cols() || rows() != newresidual.rows() || cols() != newresidual.cols()) - throw std::logic_error("quantizestripe: dimension of patch to be quantized does not match residual buffer"); + LogicError("quantizestripe: dimension of patch to be quantized does not match residual buffer"); if (gpubuffer.size() == 0) // empty buffer: empty matrix, we are done (explicit test needed since launch will fail with 0 threads) return;*/ // determine mean and variance -> value range (stored in quant package) --for 1 bit, refine it in a second pass @@ -283,13 +283,13 @@ namespace Microsoft { namespace MSR { namespace CNTK { { // verify buffer allocation size /*if (msra::math::matrixquantizer::buffersize(bits, rows(), cols()) != gpubuffer.size()) - throw std::logic_error("unquantizestripe: dimension of patch to be unquantized does not match size of quantized data"); + LogicError("unquantizestripe: dimension of patch to be unquantized does not match size of quantized data"); if (gpubuffer.size() == 0) // empty buffer: empty matrix, we are done (explicit test needed since launch will fail with 0 threads) return; */ size_t qSize = QuantizedColumn::QuantizedColumnSize(nBits, M)*N; if (qSize != gpuBufferSize) - throw std::logic_error("unquantizestripe: dimension of patch to be unquantized does not match size of quantized data"); + LogicError("unquantizestripe: dimension of patch to be unquantized does not match size of quantized data"); if (gpuBufferSize == 0) // empty buffer: empty matrix, we are done (explicit test needed since launch will fail with 0 threads) return; diff --git a/Math/Math/QuantizedMatrix.cpp b/Math/Math/QuantizedMatrix.cpp index 449431c24..5acad69f1 100644 --- a/Math/Math/QuantizedMatrix.cpp +++ b/Math/Math/QuantizedMatrix.cpp @@ -11,7 +11,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { m_qColSize = QuantizedColumn::QuantizedColumnSize(m_numBits, m_numRows); if (((QWordNumBits / m_numBits) * m_numBits) != QWordNumBits) { - throw std::logic_error("Quantization: 'nbits' must be a divisor of 64"); + LogicError("Quantization: 'nbits' must be a divisor of 64"); } if (m_allocator == nullptr) @@ -59,7 +59,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { m_qColSize = QuantizedColumn::QuantizedColumnSize(m_numBits, m_numRows); if (((QWordNumBits / m_numBits) * m_numBits) != QWordNumBits) { - throw std::logic_error("Quantization: 'nbits' must be a divisor of 64"); + LogicError("Quantization: 'nbits' must be a divisor of 64"); } // Make sure that the data matrix has enough space @@ -113,12 +113,12 @@ namespace Microsoft { namespace MSR { namespace CNTK { { if ((GetNumRows() == 0) || (GetNumCols() == 0)) { - throw std::logic_error("Print: QuantizedMatrix is empty."); + LogicError("Print: QuantizedMatrix is empty."); } if (rowEnd >= GetNumRows() || colEnd >= GetNumCols()) { - throw std::invalid_argument("Index out of range."); + InvalidArgument("Index out of range."); } DEVICEID_TYPE orgdevice = this->GetDeviceId(); diff --git a/Math/Math/ValueQuantizer.h b/Math/Math/ValueQuantizer.h index fb5d5c5e2..5aa77d802 100644 --- a/Math/Math/ValueQuantizer.h +++ b/Math/Math/ValueQuantizer.h @@ -177,7 +177,7 @@ namespace Microsoft { namespace MSR { namespace CNTK { } else if (v & 1) // not a power of two { - throw std::runtime_error("ld: 'bits' must be a power of two"); + RuntimeError("ld: 'bits' must be a power of two"); } else { diff --git a/Math/Math/cudalattice.cpp b/Math/Math/cudalattice.cpp index 06c2c1d47..6128581c2 100644 --- a/Math/Math/cudalattice.cpp +++ b/Math/Math/cudalattice.cpp @@ -60,7 +60,7 @@ public: void fetch (elemtype * p, size_t nelem, bool synchronize) const { if (nelem != size()) // fetch() cannot resize the target; caller must do that - throw std::logic_error ("fetch: vector size mismatch"); + LogicError("fetch: vector size mismatch"); ondevice no (deviceid); // switch to desired CUDA card if (nelem > 0) memcpy (p, this->get(), 0, nelem); diff --git a/Math/Math/cudalatticeops.cu b/Math/Math/cudalatticeops.cu index 96b82a106..1a066436c 100644 --- a/Math/Math/cudalatticeops.cu +++ b/Math/Math/cudalatticeops.cu @@ -3,6 +3,7 @@ // F. Seide, V-hansu #include +#include "Basics.h" #include "BestGpu.h" #ifndef CPUONLY @@ -18,7 +19,7 @@ namespace msra { namespace cuda { { char buf[1000]; sprintf(buf, "%s: launch failure: %s (cuda error %d)", fn, cudaGetErrorString (rc), rc); - throw std::runtime_error (buf); + RuntimeError(buf); } } diff --git a/Math/Math/cudalatticeops.cu.h b/Math/Math/cudalatticeops.cu.h index fa2d84c5a..8027fe40b 100644 --- a/Math/Math/cudalatticeops.cu.h +++ b/Math/Math/cudalatticeops.cu.h @@ -43,7 +43,7 @@ namespace msra { namespace cuda { { #ifdef _WIN32 if (!QueryPerformanceFrequency (&freq)) // count ticks per second - throw std::runtime_error ("auto_timer: QueryPerformanceFrequency failure"); + RuntimeError("auto_timer: QueryPerformanceFrequency failure"); QueryPerformanceCounter (&start); #endif #ifdef __unix__ diff --git a/Math/Math/cudalib.cpp b/Math/Math/cudalib.cpp index 86526ccb4..3ee89a214 100644 --- a/Math/Math/cudalib.cpp +++ b/Math/Math/cudalib.cpp @@ -5,6 +5,7 @@ #define _CRT_SECURE_NO_WARNINGS 1 // so we can use getenv()... +#include "Basics.h" #include // for CUDA API #include // for device API #include "cudalib.h" @@ -32,7 +33,7 @@ static void operator|| (cudaError_t rc, const char * msg) { char buf[1000]; sprintf(buf, "%s: %s (cuda error %d)", msg, cudaGetErrorString (rc), rc); - throw std::runtime_error (buf); + RuntimeError(buf); } }