Class: Informers::QuestionAnsweringPipeline

Inherits:
Pipeline
  • Object
show all
Defined in:
lib/informers/pipelines.rb

Instance Method Summary collapse

Methods inherited from Pipeline

#initialize

Constructor Details

This class inherits a constructor from Informers::Pipeline

Instance Method Details

#call(question, context, top_k: 1) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/informers/pipelines.rb', line 195

def call(question, context, top_k: 1)
  # Run tokenization
  inputs = @tokenizer.(question,
    text_pair: context,
    padding: true,
    truncation: true,
    return_offsets: true
  )

  output = @model.(inputs)

  to_return = []
  output.start_logits.length.times do |j|
    ids = inputs[:input_ids][j]
    sep_index = ids.index(@tokenizer.sep_token_id)
    offsets = inputs[:offsets][j]

    s1 = Utils.softmax(output.start_logits[j])
      .map.with_index
      .select { |x| x[1] > sep_index }
    e1 = Utils.softmax(output.end_logits[j])
      .map.with_index
      .select { |x| x[1] > sep_index }

    options = s1.product(e1)
      .select { |x| x[0][1] <= x[1][1] }
      .map { |x| [x[0][1], x[1][1], x[0][0] * x[1][0]] }
      .sort_by { |v| -v[2] }

    [options.length, top_k].min.times do |k|
      start, end_, score = options[k]

      answer_tokens = ids.slice(start, end_ + 1)

      answer = @tokenizer.decode(answer_tokens,
        skip_special_tokens: true
      )

      to_return << {
        answer:,
        score:,
        start: offsets[start][0],
        end: offsets[end_][1]
      }
    end
  end

  question.is_a?(Array) ? to_return : to_return[0]
end