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



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/informers/pipelines.rb', line 229

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