Replaced all bare throw calls with Centralized exception functions that print the call stack

This commit is contained in:
Amit Agarwal 2015-10-10 18:07:19 -07:00
Родитель 8147d001ab
Коммит 8e32979259
71 изменённых файлов: 1148 добавлений и 1125 удалений

Просмотреть файл

@ -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<ComputationNodePtr> && 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<ComputationNodePtr> & 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<ComputationNodePtr> && 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<ComputationNodePtr> & 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<ComputationNodePtr> && 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<ComputationNodePtr> && 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<ComputationNodePtr> && 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<vector<ComputationNodePtr>()> 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<ComputationNodePtr> 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<ErrorPredictionNode>(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<DelayNode>([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<typename T>
static ConfigValuePtr CompOp(const ExpressionPtr & e, const T & left, const T & right, const IConfigRecordPtr &, const wstring & exprPath)
{
template<typename T>
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<Double>();
let right = rightVal.AsRef<Double>();
@ -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<double>(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<String>();
let right = rightVal.AsRef<String>();
if (e->op == L"+") return ConfigValuePtr(make_shared<String>(left + right), MakeFailFn(e->location), exprPath);
else return CompOp<wstring>(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<Bool>();
//let right = rightVal.AsRef<Bool>(); // 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<ConfigRecord>(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<wstring, InfixOps> 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<Object> 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<Object> EvaluateField(ExpressionPtr e, const wstring & id)
{
//let record = AsPtr<ConfigRecord>(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);

Просмотреть файл

@ -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); }

Просмотреть файл

@ -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<TextLocation> 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); }
};

Просмотреть файл

@ -208,7 +208,7 @@ namespace Microsoft { namespace MSR { namespace BS {
break;
}
}
catch (const ConfigError & err)
catch (const ConfigException & err)
{
err.PrintError();
}

Просмотреть файл

@ -471,7 +471,7 @@ std::vector<int> 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,

Просмотреть файл

@ -25,7 +25,7 @@ template<> std::string GetEvalName(double) {std::string name = "GetEvalD"; retur
template<class ElemType>
void Eval<ElemType>::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
}

Просмотреть файл

@ -10,6 +10,7 @@
#include "Platform.h"
#include "DebugUtil.h"
#include <string>
#include <vector>
#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<class E>
__declspec_noreturn static inline void ThrowFormatted()
{
Microsoft::MSR::CNTK::DebugUtil::PrintCallStack();
throw E();
}
template<class E>
__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<E>(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<std::logic_error>(forward<_Types>(_Args)...); }
template<class... _Types>
__declspec_noreturn static inline void InvalidArgument(_Types&&... _Args) { ThrowFormatted<std::invalid_argument>(forward<_Types>(_Args)...); }
template<class... _Types>
__declspec_noreturn static inline void BadExceptionError(_Types&&... _Args) { ThrowFormatted<std::bad_exception>(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.

Просмотреть файл

@ -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;

Просмотреть файл

@ -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<typename M>
ScriptingError(const M & msg) : runtime_error(msg) { }
ScriptingException(const M & msg) : runtime_error(msg) { }
virtual void PrintError() const = 0;
};

Просмотреть файл

@ -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());

Просмотреть файл

@ -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));
}
// ----------------------------------------------------------------------------

Просмотреть файл

@ -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<edgeinfo> edges2; // TODO: rename these
std::vector<aligninfo> 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<class SYMMAP> 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;
};

Просмотреть файл

@ -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();
}

Просмотреть файл

@ -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 <string> // for the error message in checkoverflow() only
#include <stdexcept>
#include <stdint.h>
@ -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);
}
}

Просмотреть файл

@ -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

Просмотреть файл

@ -48,7 +48,7 @@ template <typename FUNCTION> 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<LONG/*unsigned int*/,256> 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 <typename FUNCTION> 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

Просмотреть файл

@ -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)

Просмотреть файл

@ -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 ssematrixbase> 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<typename T> 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);

Просмотреть файл

@ -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

Просмотреть файл

@ -98,7 +98,7 @@ void BinaryReader<ElemType>::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<ElemType>::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<ElemType>::GetMinibatch(std::map<std::wstring, Matrix<ElemType
}
if (!categoryLabelFound)
{
throw runtime_error("Category Labels not saved in file, either save, or support creation in BinaryReader");
RuntimeError("Category Labels not saved in file, either save, or support creation in BinaryReader");
}
}
}
@ -300,7 +300,7 @@ bool BinaryReader<ElemType>::GetMinibatch(std::map<std::wstring, Matrix<ElemType
// make sure we are good now
if (dataType != sectionDataFloat || dataSize != sizeof(ElemType))
{
throw runtime_error("Category Labels not saved in file, either save, or support creation in BinaryReader");
RuntimeError("Category Labels not saved in file, either save, or support creation in BinaryReader");
}
}
size_t size = rows*dataSize*actualmbsize;
@ -349,12 +349,12 @@ const std::map<typename BinaryReader<ElemType>::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<typename BinaryReader<ElemType>::LabelIdType, typename BinaryRead
template<class ElemType>
void BinaryReader<ElemType>::SetLabelMapping(const std::wstring& /*sectionName*/, const std::map<typename BinaryReader<ElemType>::LabelIdType, typename BinaryReader<ElemType>::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<ElemType>::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

Просмотреть файл

@ -110,7 +110,7 @@ Section* BinaryWriter<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>::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

Просмотреть файл

@ -435,7 +435,7 @@ void DSSMReader<ElemType>::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<ElemType>::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<ElemType>::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

Просмотреть файл

@ -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<ElemType>::ReadLabelToTargetMappingFile (const std::wstring& labelToTargetMappingFile, const std::wstring& labelListFile, std::vector<std::vector<ElemType>>& 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<std::wstring> labelList;
size_t count, numLabels;
@ -1665,7 +1665,7 @@ namespace Microsoft { namespace MSR { namespace CNTK {
template<class ElemType>
bool HTKMLFReader<ElemType>::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)

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -25,7 +25,7 @@ protected: // fix this later
size_t n; // number of elements
std::vector<std::unique_ptr<BLOCKTYPE>> 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:

Просмотреть файл

@ -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<float> 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<float> 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<float> v (&feat(0,t), &feat(0,t) + feat.rows());

Просмотреть файл

@ -34,7 +34,6 @@
#include <errno.h>
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<wstring> & 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
{

Просмотреть файл

@ -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));
}
// ----------------------------------------------------------------------------

Просмотреть файл

@ -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<string> params = msra::strfun::split (str, ";");
if (params.empty())
throw std::runtime_error ("parsekind: invalid param kind string");
RuntimeError("parsekind: invalid param kind string");
vector<string> 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<float> & 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<float> & 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<char*> & toks, const unordered_map<std::string, size_t> & statelisthash, const double htkTimeToFrame,
std::unordered_map<std::string, size_t> & hmmnamehash)
std::unordered_map<std::string, size_t> & 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<char*> & 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<wstring,vector<ENTRY>> // [key][i] the data
wstring curpath; // for error messages
unordered_map<std::string, size_t> statelistmap; // for state <=> index
map<wstring,WORDSEQUENCE> wordsequences; // [key] word sequences (if we are building word entries as well, for MMI)
std::unordered_map<std::string, size_t> symmap;
std::unordered_map<std::string, size_t> symmap;
void strtok (char * s, const char * delim, vector<char*> & toks)
{
@ -716,7 +716,7 @@ class htkmlfreader : public map<wstring,vector<ENTRY>> // [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<char*> readlines (const wstring & path, vector<char> & buffer)
@ -821,12 +821,12 @@ class htkmlfreader : public map<wstring,vector<ENTRY>> // [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<wstring,vector<ENTRY>> // [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<wstring,vector<ENTRY>> // [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<wstring> & paths, const set<wstring> & 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<typename WORDSYMBOLTABLE, typename UNITSYMBOLTABLE>
htkmlfreader(const vector<wstring> & paths, const set<wstring> & 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<typename WORDSYMBOLTABLE, typename UNITSYMBOLTABLE>
htkmlfreader(const vector<wstring> & paths, const set<wstring> & 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<typename WORDSYMBOLTABLE, typename UNITSYMBOLTABLE>
@ -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());
}
}

Просмотреть файл

@ -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::nodecontext> 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::nodecontext> 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::nodecontext> 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::nodecontext> 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<std
vector<char> 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<std
{
if (strncmp (*iter, "lmscale=", 8) == 0) // note: HTK sometimes generates extra garbage space at the end of this line
if (sscanf_s (*iter, "lmscale=%f wdpenalty=%f%c", &info.lmf, &info.wp, &dummychar, sizeof (dummychar)) != 2 && dummychar != ' ')
throw std::runtime_error ("lattice: mal-formed lmscale/wdpenalty line in lattice: " + string (*iter));
RuntimeError("lattice: mal-formed lmscale/wdpenalty line in lattice: " + string (*iter));
}
// parse N and L
@ -547,13 +547,13 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_map<std
{
unsigned long N, L;
if (sscanf_s (*iter, "N=%lu L=%lu %c", &N, &L, &dummychar, sizeof (dummychar)) != 2)
throw std::runtime_error ("lattice: mal-formed N=/L= line in lattice: " + string (*iter));
RuntimeError("lattice: mal-formed N=/L= line in lattice: " + string (*iter));
info.numnodes = N;
info.numedges = L;
iter++;
}
else
throw std::runtime_error ("lattice: mal-formed before parse N=/L= line in lattice.");
RuntimeError("lattice: mal-formed before parse N=/L= line in lattice.");
ASSERT(info.numnodes > 0);
nodes.reserve (info.numnodes);
@ -561,13 +561,13 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_map<std
for (size_t i = 0; i < info.numnodes; i++, iter++)
{
if (iter == lines.end())
throw std::runtime_error ("lattice: not enough I lines in lattice");
RuntimeError("lattice: not enough I lines in lattice");
unsigned long itest;
float t;
if (sscanf_s (*iter, "I=%lu t=%f%c", &itest, &t, &dummychar, sizeof (dummychar)) < 2)
throw std::runtime_error ("lattice: mal-formed node line in lattice: " + string (*iter));
RuntimeError("lattice: mal-formed node line in lattice: " + string (*iter));
if (i != (size_t) itest)
throw std::runtime_error ("lattice: out-of-sequence node line in lattice: " + string (*iter));
RuntimeError("lattice: out-of-sequence node line in lattice: " + string (*iter));
nodes.push_back (nodeinfo ((unsigned int) (t / info.frameduration + 0.5)));
info.numframes = max (info.numframes, (size_t) nodes.back().t);
}
@ -579,7 +579,7 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_map<std
for (size_t j = 0; j < info.numedges; j++, iter++)
{
if (iter == lines.end())
throw std::runtime_error ("lattice: not enough J lines in lattice");
RuntimeError("lattice: not enough J lines in lattice");
unsigned long jtest;
unsigned long S, E;
float a, l;
@ -590,37 +590,37 @@ void lattice::fromhtklattice (const wstring & path, const std::unordered_map<std
if (nvals == 5 && j == info.numedges - 1) // special case: last edge is a !NULL and thus may have the d= record missing
strcpy (d, ":");
else if (nvals != 6)
throw std::runtime_error ("lattice: mal-formed edge line in lattice: " + string (*iter));
RuntimeError("lattice: mal-formed edge line in lattice: " + string (*iter));
if (j != (size_t) jtest)
throw std::runtime_error ("lattice: out-of-sequence edge line in lattice: " + string (*iter));
RuntimeError("lattice: out-of-sequence edge line in lattice: " + string (*iter));
edges.push_back (edgeinfowithscores (S, E, a, l, align.size()));
// build align array
size_t edgeframes = 0; // (for checking whether the alignment sums up right)
const char * p = d;
if (p[0] != ':' || (p[1] == 0 && j < info.numedges-1)) // last edge may be empty
throw std::runtime_error ("lattice: alignment info must start with a colon and must have at least one entry: " + string (*iter));
RuntimeError("lattice: alignment info must start with a colon and must have at least one entry: " + string (*iter));
p++;
while (*p)
{
// p points to an entry of the form TRIPHONE,DURATION
const char * q = strchr (p, ',');
if (q == NULL)
throw std::runtime_error ("lattice: alignment entry lacking a comma: " + string (*iter));
RuntimeError("lattice: alignment entry lacking a comma: " + string (*iter));
if (q == p)
throw std::runtime_error ("lattice: alignment entry label empty: " + string (*iter));
RuntimeError("lattice: alignment entry label empty: " + string (*iter));
label.assign (p, q-p); // the triphone label
q++;
char * ep;
double duration = strtod (q, &ep); // (weird--returns a non-const ptr in ep to a const object)
p = ep;
if (*p != ':')
throw std::runtime_error ("lattice: alignment entry not ending with a colon: " + string (*iter));
RuntimeError("lattice: alignment entry not ending with a colon: " + string (*iter));
p++;
// create the alignment entry
const size_t frames = (unsigned int) (duration / info.frameduration + 0.5);
auto it = unitmap.find (label);
if (it == unitmap.end())
throw std::runtime_error ("lattice: unit in alignment that is not in model: " + label);
RuntimeError("lattice: unit in alignment that is not in model: " + label);
const size_t unitid = it->second;
//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_map<std
{
char msg[128];
sprintf (msg, "\n-- where edgeframes=%d != (nodes[E].t - nodes[S].t=%d), the gap is %d.", edgeframes, nodes[E].t - (size_t) nodes[S].t, edgeframes + nodes[S].t - nodes[E].t);
throw std::runtime_error ("lattice: alignment info duration mismatches edge duration: " + string (*iter) + msg);
RuntimeError("lattice: alignment info duration mismatches edge duration: " + string (*iter) + msg);
}
}
if (iter != lines.end())
throw std::runtime_error ("lattice: unexpected garbage at end of lattice: " + string (*iter));
RuntimeError("lattice: unexpected garbage at end of lattice: " + string (*iter));
checklattice();
// create more efficient storage for alignments
@ -655,10 +655,10 @@ void lattice::frommlf (const wstring & key, const std::unordered_map<std::string
// get the labels (state and word)
auto iter = transcripts.find (key);
if (iter == transcripts.end())
throw std::runtime_error ("frommlf: no reference word sequence in MLF for lattice with key " + strfun::utf8 (key));
RuntimeError("frommlf: no reference word sequence in MLF for lattice with key " + strfun::utf8 (key));
const auto & transcript = iter->second;
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<float> lmscores (transcript.words.size());
@ -681,7 +681,7 @@ void lattice::frommlf (const wstring & key, const std::unordered_map<std::string
e.S = j;
e.E = j+1;
if (e.E != j+1)
throw std::runtime_error (msra::strfun::strprintf ("frommlf: too many tokens to be represented as edgeinfo::E in label set: %S", key.c_str()));
RuntimeError(msra::strfun::strprintf ("frommlf: too many tokens to be represented as edgeinfo::E in label set: %S", key.c_str()));
e.a = 0.0f; // no ac score
// LM score
@ -690,12 +690,12 @@ void lattice::frommlf (const wstring & key, const std::unordered_map<std::string
if (wid == sentstart)
{
if (j != 0)
throw std::logic_error ("frommlf: found an !sent_start token not at the first position");
LogicError("frommlf: found an !sent_start token not at the first position");
}
else if (wid == sentend)
{
if (j != (int) transcript.words.size()-1)
throw std::logic_error ("frommlf: found an !sent_end token not at the end position");
LogicError("frommlf: found an !sent_end token not at the end position");
wid = lmend; // use </s> for score lookup
}
const int iwid = (int) wid;
@ -711,7 +711,7 @@ void lattice::frommlf (const wstring & key, const std::unordered_map<std::string
}
nodes[transcript.words.size()].t = (unsigned short) numframes;
if (nodes[transcript.words.size()].t != numframes)
throw std::runtime_error (msra::strfun::strprintf ("frommlf: too many frames to be represented as nodeinfo::t in label set: %S", key.c_str()));
RuntimeError(msra::strfun::strprintf ("frommlf: too many frames to be represented as nodeinfo::t in label set: %S", key.c_str()));
info.lmf = -1.0f; // indicates not set
info.wp = 0.0f; // not set indicated by lmf < 0
info.numedges = edges.size();

Просмотреть файл

@ -146,12 +146,12 @@ private:
foreach_index (i, lattices)
totalframes += lattices[i]->getnumframes();
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)

Просмотреть файл

@ -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

Просмотреть файл

@ -17,7 +17,6 @@
#include <math.h>
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 unsigned char *> const_uint24_ref; // const version (only read)
class uint24_ref : public uint24_ref_t<unsigned char *> // 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<int24_vector> ids; // [M+1][i] ([0] = not used)
bool level1nonsparse; // true: level[1] can be directly looked up
std::vector<index_t> 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<int> w2id; // w -> id
@ -825,7 +821,7 @@ public:
template<class DATATYPE> class mgram_data
{
std::vector<std::vector<DATATYPE>> 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["<UNK>"]; // or -1 -- -1 is OK
if (startId == -1 || endId == -1) // if filtering, these must be given
throw runtime_error ("read: <s> and/or </s> missing in vocabulary");
RuntimeError("read: <s> and/or </s> missing in vocabulary");
// if filtering but no <UNK>, we use (vocabsize) as the id, and have
// estimate() prune it
@ -2021,7 +2017,7 @@ public:
void estimate (int startId, const std::vector<unsigned int> & minObs, vector<bool> 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<int> 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 <s>
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);
}
};

Просмотреть файл

@ -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<size_t> & unitcounts() const { throw logic_error ("unitcounts: not implemented for this feature source"); static std::vector<size_t> x; return x;/*keep compiler happy*/ }
/*implement*/ const std::vector<size_t> & unitcounts() const { LogicError("unitcounts: not implemented for this feature source"); static std::vector<size_t> 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::vector<size_t>framesaccum;
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<shared_ptr<const latticesource::latticepair>> & /*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<size_t> & unitcounts() const { throw logic_error ("unitcounts: not implemented for this feature source"); }
/*implement*/ const std::vector<size_t> & unitcounts() const { LogicError("unitcounts: not implemented for this feature source"); }
};
};};

Просмотреть файл

@ -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<const latticesource::latticepair> 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<biggrowablevector<CLASSIDTYPE>> ((*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<biggrowablevector<CLASSIDTYPE>>((*phoneboundaries[i]), classidsbegin, n)));
}
return allphoneboundaries; // nothing to return
@ -361,14 +360,14 @@ public:
uttduration = std::vector<size_t>(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<typename VECTOR> 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<shared_ptr<const latticesource::latticepair>> & /*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);

Просмотреть файл

@ -697,13 +697,13 @@ bool BatchLUSequenceReader<ElemType>::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));

Просмотреть файл

@ -429,7 +429,7 @@ void LibSVMBinaryReader<ElemType>::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<ElemType>::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<ElemType>::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<double>;

Просмотреть файл

@ -120,7 +120,7 @@ void SparsePCReader<ElemType>::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<ElemType>::GetMinibatch(std::map<std::wstring, Matrix<ElemTy
if (verifCode != VERIFICATION_CODE)
{
throw runtime_error("Verification code did not match - error in reading data");
RuntimeError("Verification code did not match - error in reading data");
return false;
}

Просмотреть файл

@ -62,7 +62,7 @@ public:
void CopyMBLayoutTo(MBLayoutPtr pMBLayout) { pMBLayout->CopyFrom(m_pMBLayout); NOT_IMPLEMENTED; }
virtual const std::map<LabelIdType, LabelType>& GetLabelMapping(const std::wstring& sectionName);
virtual void SetLabelMapping(const std::wstring& sectionName, const std::map<LabelIdType, typename LabelType>& 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);
};
}}}

Просмотреть файл

@ -946,7 +946,7 @@ void UCIFastReader<ElemType>::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<ElemType>::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<class ElemType>

Просмотреть файл

@ -7,6 +7,7 @@
//
#include "stdafx.h"
#include "Basics.h"
#include "UCIParser.h"
#include <stdexcept>
#include <stdint.h>
@ -367,10 +368,10 @@ void UCIParser<NumType, LabelType>::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<NumType, LabelType>::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<NumType, LabelType>::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<NumType, LabelType>::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;
}

Просмотреть файл

@ -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)

Просмотреть файл

@ -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<FUNCTION>, 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()
//{

Просмотреть файл

@ -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();

Просмотреть файл

@ -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<ElemType>::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.");
}
}

Просмотреть файл

@ -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<std::wstring, Matrix<ElemType>*> inputMatrices;

Просмотреть файл

@ -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)
{

Просмотреть файл

@ -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)

Просмотреть файл

@ -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());

Просмотреть файл

@ -91,7 +91,7 @@ int wmain(int argc, wchar_t* argv[])
else if (type == "double")
DoCommand<double>(config);
else
throw runtime_error("invalid precision specified: " + type);
RuntimeError("invalid precision specified: " + type);
}
catch(std::exception &err)
{

Просмотреть файл

@ -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);

Просмотреть файл

@ -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<class ElemType>
@ -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]);

Просмотреть файл

@ -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);
}
}

Просмотреть файл

@ -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();
}

Просмотреть файл

@ -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<float> 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<typename FLOAT> 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<typename FLOAT> 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<typename FLOAT> 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<typename FLOAT> 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());

Просмотреть файл

@ -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

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -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<ElemType> CPUSparseMatrix<ElemType>::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<ElemType> CPUSparseMatrix<ElemType>::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<ElemType>& rhs, const bool transposeB, CPUSparseMatrix<ElemType>& 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<ElemType>::AreEqual(const CPUSparseMatrix<ElemType>& a, const CPUSparseMatrix<ElemType>& 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<ElemType>::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<ElemType>::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<ElemType>::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

Просмотреть файл

@ -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)

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -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;

Просмотреть файл

@ -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<ElemType>::GetBestGPUDeviceId() : computeDevice; //current GPU device Id
@ -376,9 +376,9 @@ namespace Microsoft { namespace MSR { namespace CNTK {
void GPUSparseMatrix<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>& rhs, const bool transposeB, ElemType beta, GPUMatrix<ElemType>& 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<ElemType>& rhs, const bool transposeB, GPUSparseMatrix<ElemType>& 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<ElemType>::ScaleAndAdd(const ElemType alpha, const GPUSparseMatrix<ElemType>& lhs, GPUMatrix<ElemType>& 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<ElemType> c(b.GetNumRows(),b.GetNumCols(),b.GetComputeDeviceId());
@ -1931,10 +1931,10 @@ namespace Microsoft { namespace MSR { namespace CNTK {
GPUSparseMatrix<ElemType>& GPUSparseMatrix<ElemType>::AssignTransposeOf(const GPUSparseMatrix<ElemType>& 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<ElemType>::SumOfAbsElements() const
{
if (IsEmpty())
throw std::logic_error("SumOfAbsElements: Matrix is empty");
LogicError("SumOfAbsElements: Matrix is empty");
cublasHandle_t cuHandle = GPUMatrix<ElemType>::GetCublasHandle(GetComputeDeviceId());
if (sizeof(ElemType)==sizeof(float))
@ -2041,7 +2041,7 @@ namespace Microsoft { namespace MSR { namespace CNTK {
ElemType GPUSparseMatrix<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>& GPUSparseMatrix<ElemType>::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<ElemType>& GPUSparseMatrix<ElemType>::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<ElemType>& GPUSparseMatrix<ElemType>::AssignTruncateBottomOf (const GPUSparseMatrix<ElemType>& 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<ElemType>& GPUSparseMatrix<ElemType>::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<ElemType>& GPUSparseMatrix<ElemType>::AssignTruncateTopOf (const GPUSparseMatrix<ElemType>& 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<ElemType>& GPUSparseMatrix<ElemType>::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

Просмотреть файл

@ -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<ElemType>::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<ElemType>::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<ElemType>::Matrix(const Matrix<ElemType>& 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<ElemType> Matrix<ElemType>::Transpose()
{
if (IsEmpty())
throw std::logic_error("Transpose: Matrix is empty.");
LogicError("Transpose: Matrix is empty.");
Matrix<ElemType> 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<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>::SetDiagonalValue(const Matrix<ElemType>& 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<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>& Matrix<ElemType>::AssignSumOf(const ElemType alpha, const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignDifferenceOf(const ElemType alpha, const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignDifferenceOf(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::operator-= (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignElementProductOf (const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AddElementProductOf (const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignElementDivisionOf (const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::ColumnElementMultiplyWith(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::RowElementMultiplyWith(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::RowElementDivideBy(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::ColumnElementDivideBy(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignElementInverseOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignLogSoftmaxOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignSqrtOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignExpOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignAbsOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignLogOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignLog10Of (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignCosineOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignNegativeSineOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::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<ElemType>& Matrix<ElemType>::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<ElemType>& Matrix<ElemType>::AssignTruncateBottomOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::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<ElemType>& Matrix<ElemType>::AssignTruncateTopOf (const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::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<ElemType>::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<ElemType>& Matrix<ElemType>::AssignSumOfElements(const Matrix<ElemType>& 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<ElemType>::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<ElemType>::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<ElemType>::VectorNorm1(Matrix<ElemType>& 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<ElemType>::VectorNorm2(Matrix<ElemType>& 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<ElemType>::VectorNormInf(Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignKhatriRaoProductOf(const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AddColumnReshapeProductOf(const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>::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<ElemType>& Matrix<ElemType>::AssignFrobeniusNormOf(const Matrix<ElemType>& 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<ElemType>::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<ElemType>::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<ElemType>::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<ElemType>& Matrix<ElemType>::AssignSignOf(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AddSignOf(const Matrix<ElemType>& 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<ElemType>::VectorMax(Matrix<ElemType>& maxIndexes, Matrix<ElemType>& 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<ElemType>::VectorMin(Matrix<ElemType>& minIndexes, Matrix<ElemType>& 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<class ElemType>
@ -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<ElemType>(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<ElemType>::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<ElemType>& Matrix<ElemType>::AssignNoiseContrastiveEstimation(const Matrix<ElemType>& a, const Matrix<ElemType>& b, const Matrix<ElemType>& c, const Matrix<ElemType>& bias, Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignNCEDerivative(const Matrix<ElemType>& tmp, const Matrix<ElemType>& a, const Matrix<ElemType>& b, const Matrix<ElemType>& 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<ElemType>::SVD(const Matrix<ElemType>& A, Matrix<ElemType>& SIGMA, Matrix<ElemType>& U, Matrix<ElemType>& VT, Matrix<ElemType>& 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<ElemType>& 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<ElemType>::ScaleAndAdd(ElemType alpha, const Matrix<ElemType>& a, Matrix<ElemType>& 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<ElemType>::Scale(ElemType alpha, Matrix<ElemType>& 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<ElemType>::Scale(const Matrix<ElemType>& alpha, Matrix<ElemType>& 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<ElemType>::InnerProduct (const Matrix<ElemType>& a, const Matrix<ElemType>& b, Matrix<ElemType>& 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<ElemType>::InnerProductOfMatrices(const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignInnerProductOfMatrices(const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>::ElementWisePower (ElemType alpha, const Matrix<ElemType>& a, Matrix<ElemType>& 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<ElemType>::AreEqual(const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>::HasElement(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::Shift(const Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignElementProductOfWithShiftNeg(const Matrix<ElemType>& a, const Matrix<ElemType>& 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<ElemType>::InnerProductWithShiftNeg(const Matrix<ElemType>& a, const Matrix<ElemType>& b, Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::GetARowByIndex(const Matrix<ElemType>& 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<ElemType>::ConductRowElementMultiplyWithShift(const Matrix<ElemType>& a, const Matrix<ElemType>& b, Matrix<ElemType>& 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<ElemType>& Matrix<ElemType>::AssignElementProductOfWithShift(const Matrix<ElemType>& a, const Matrix<ElemType>& 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,

Просмотреть файл

@ -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);

Просмотреть файл

@ -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<ElemType>::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;

Просмотреть файл

@ -11,7 +11,7 @@ namespace Microsoft { namespace MSR { namespace CNTK {
m_qColSize = QuantizedColumn<ElemType>::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<ElemType>::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();

Просмотреть файл

@ -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
{

Просмотреть файл

@ -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);

Просмотреть файл

@ -3,6 +3,7 @@
// F. Seide, V-hansu
#include <stdexcept>
#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);
}
}

Просмотреть файл

@ -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__

Просмотреть файл

@ -5,6 +5,7 @@
#define _CRT_SECURE_NO_WARNINGS 1 // so we can use getenv()...
#include "Basics.h"
#include <cuda_runtime_api.h> // for CUDA API
#include <cuda.h> // 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);
}
}