FocusedColumnModule.cpp 5.18 KB
Newer Older
1
#include "FocusedColumnModule.hpp"
Franck Dary's avatar
Franck Dary committed
2

Franck Dary's avatar
Franck Dary committed
3
FocusedColumnModuleImpl::FocusedColumnModuleImpl(std::string name, const std::string & definition)
Franck Dary's avatar
Franck Dary committed
4
{
Franck Dary's avatar
Franck Dary committed
5
  setName(name);
Franck Dary's avatar
Franck Dary committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  std::regex regex("(?:(?:\\s|\\t)*)Column\\{(.*)\\}(?:(?:\\s|\\t)*)NbElem\\{(.*)\\}(?:(?:\\s|\\t)*)Buffer\\{(.*)\\}(?:(?:\\s|\\t)*)Stack\\{(.*)\\}(?:(?:\\s|\\t)*)(\\S+)\\{(.*)\\}(?:(?:\\s|\\t)*)In\\{(.*)\\}(?:(?:\\s|\\t)*)Out\\{(.*)\\}(?:(?:\\s|\\t)*)");
  if (!util::doIfNameMatch(regex, definition, [this,&definition](auto sm)
        {
          try
          {
            column = sm.str(1);
            maxNbElements = std::stoi(sm.str(2));

            for (auto & index : util::split(sm.str(3), ' '))
              focusedBuffer.emplace_back(std::stoi(index));

            for (auto & index : util::split(sm.str(4), ' '))
              focusedStack.emplace_back(std::stoi(index));

            auto subModuleType = sm.str(5);
            auto subModuleArguments = util::split(sm.str(6), ' ');

            auto options = MyModule::ModuleOptions(true)
              .bidirectional(std::stoi(subModuleArguments[0]))
              .num_layers(std::stoi(subModuleArguments[1]))
              .dropout(std::stof(subModuleArguments[2]))
              .complete(std::stoi(subModuleArguments[3]));

29
            inSize = std::stoi(sm.str(7));
Franck Dary's avatar
Franck Dary committed
30
31
32
33
34
35
            int outSize = std::stoi(sm.str(8));

            if (subModuleType == "LSTM")
              myModule = register_module("myModule", LSTM(inSize, outSize, options));
            else if (subModuleType == "GRU")
              myModule = register_module("myModule", GRU(inSize, outSize, options));
Franck Dary's avatar
Franck Dary committed
36
37
            else if (subModuleType == "Concat")
              myModule = register_module("myModule", Concat(inSize));
Franck Dary's avatar
Franck Dary committed
38
39
40
41
42
43
            else
              util::myThrow(fmt::format("unknown sumodule type '{}'", subModuleType));

          } catch (std::exception & e) {util::myThrow(fmt::format("{} in '{}'",e.what(),definition));}
        }))
    util::myThrow(fmt::format("invalid definition '{}'", definition));
Franck Dary's avatar
Franck Dary committed
44
45
}

Franck Dary's avatar
Franck Dary committed
46
torch::Tensor FocusedColumnModuleImpl::forward(torch::Tensor input)
Franck Dary's avatar
Franck Dary committed
47
48
49
{
  std::vector<torch::Tensor> outputs;
  for (unsigned int i = 0; i < focusedBuffer.size()+focusedStack.size(); i++)
Franck Dary's avatar
Franck Dary committed
50
    outputs.emplace_back(myModule->forward(wordEmbeddings(input.narrow(1, firstInputIndex+i*maxNbElements, maxNbElements))));
Franck Dary's avatar
Franck Dary committed
51
52
53
54

  return torch::cat(outputs, 1);
}

Franck Dary's avatar
Franck Dary committed
55
std::size_t FocusedColumnModuleImpl::getOutputSize()
Franck Dary's avatar
Franck Dary committed
56
{
57
  return (focusedBuffer.size()+focusedStack.size())*myModule->getOutputSize(maxNbElements);
Franck Dary's avatar
Franck Dary committed
58
59
}

Franck Dary's avatar
Franck Dary committed
60
std::size_t FocusedColumnModuleImpl::getInputSize()
Franck Dary's avatar
Franck Dary committed
61
62
63
64
{
  return (focusedBuffer.size()+focusedStack.size()) * maxNbElements;
}

Franck Dary's avatar
Franck Dary committed
65
void FocusedColumnModuleImpl::addToContext(std::vector<std::vector<long>> & context, const Config & config)
Franck Dary's avatar
Franck Dary committed
66
{
Franck Dary's avatar
Franck Dary committed
67
  auto & dict = getDict();
Franck Dary's avatar
Franck Dary committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
  std::vector<long> focusedIndexes;

  for (int index : focusedBuffer)
    focusedIndexes.emplace_back(config.getRelativeWordIndex(index));

  for (int index : focusedStack)
    if (config.hasStack(index))
      focusedIndexes.emplace_back(config.getStack(index));
    else
      focusedIndexes.emplace_back(-1);

  for (auto & contextElement : context)
  {
    for (auto index : focusedIndexes)
    {
      if (index == -1)
      {
        for (int i = 0; i < maxNbElements; i++)
          contextElement.emplace_back(dict.getIndexOrInsert(Dict::nullValueStr));
        continue;
      }

      std::vector<std::string> elements;
      if (column == "FORM")
      {
        auto asUtf8 = util::splitAsUtf8(config.getAsFeature(column, index).get());

        for (int i = 0; i < maxNbElements; i++)
          if (i < (int)asUtf8.size())
            elements.emplace_back(fmt::format("{}", asUtf8[i]));
          else
            elements.emplace_back(Dict::nullValueStr);
      }
      else if (column == "FEATS")
      {
        auto splited = util::split(config.getAsFeature(column, index).get(), '|');

        for (int i = 0; i < maxNbElements; i++)
          if (i < (int)splited.size())
            elements.emplace_back(fmt::format("FEATS({})", splited[i]));
          else
            elements.emplace_back(Dict::nullValueStr);
      }
      else if (column == "ID")
      {
        if (config.isTokenPredicted(index))
          elements.emplace_back("ID(TOKEN)");
        else if (config.isMultiwordPredicted(index))
          elements.emplace_back("ID(MULTIWORD)");
        else if (config.isEmptyNodePredicted(index))
          elements.emplace_back("ID(EMPTYNODE)");
      }
120
121
122
123
124
      else if (column == "EOS")
      {
        bool isEOS = config.getAsFeature(Config::EOSColName, index) == Config::EOSSymbol1;
        elements.emplace_back(fmt::format("EOS({})", isEOS));
      }
Franck Dary's avatar
Franck Dary committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
      else
      {
        elements.emplace_back(config.getAsFeature(column, index));
      }

      if ((int)elements.size() != maxNbElements)
        util::myThrow(fmt::format("elements.size ({}) != maxNbElements ({})", elements.size(), maxNbElements));

      for (auto & element : elements)
        contextElement.emplace_back(dict.getIndexOrInsert(element));
    }
  }
}

139
void FocusedColumnModuleImpl::registerEmbeddings(std::filesystem::path path)
140
{
Franck Dary's avatar
Franck Dary committed
141
  wordEmbeddings = register_module("embeddings", torch::nn::Embedding(torch::nn::EmbeddingOptions(getDict().size(), inSize)));
142
  loadPretrainedW2vEmbeddings(wordEmbeddings, path);
143
144
}