aboutsummaryrefslogtreecommitdiffstats
path: root/model-integration/src/main/javacc/ModelParser.jj
blob: 2e5560c944f9fa263f81d7ae3002467cfc04f4ea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// --------------------------------------------------------------------------------
//
// JavaCC options. When this file is changed, run "mvn generate-sources" to rebuild
// the parser classes.
//
// --------------------------------------------------------------------------------
options {
    UNICODE_INPUT = true;
    CACHE_TOKENS  = false;
    DEBUG_PARSER = false;
    ERROR_REPORTING = true;
    FORCE_LA_CHECK = true;
    USER_CHAR_STREAM = true;
}

// --------------------------------------------------------------------------------
//
// Parser body.
//
// --------------------------------------------------------------------------------
PARSER_BEGIN(ModelParser)

package ai.vespa.rankingexpression.importer.vespa.parser;

import java.io.File;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
import java.util.ArrayList;
import ai.vespa.rankingexpression.importer.ImportedModel;
import com.yahoo.io.IOUtils;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.IndexedTensor;
import com.yahoo.tensor.MixedTensor;
import com.yahoo.tensor.TensorAddress;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.serialization.JsonFormat;
import com.yahoo.searchlib.rankingexpression.RankingExpression;

/**
 * Parser of Vespa ML model files: Ranking expression functions enclosed in brackets.
 *
 * @author bratseth
 */
public class ModelParser {

    /** The model we are importing into */
    private ImportedModel model;

    /** Creates a parser of a string */
    public ModelParser(String input, ImportedModel model) {
        this(new SimpleCharStream(input), model);
    }

    /** Creates a parser */
    public ModelParser(SimpleCharStream input, ImportedModel model) {
        this(input);
        this.model = model;
    }

}

PARSER_END(ModelParser)


// --------------------------------------------------------------------------------
//
// Token declarations.
//
// --------------------------------------------------------------------------------

// Declare white space characters. These do not include newline because it has
// special meaning in several of the production rules.
SKIP :
{
  " " | "\t" | "\r" | "\f"
}

// Declare all tokens to be recognized. When a word token is added it MUST be
// added to the identifier() production rule.
TOKEN :
{
  < NL: "\n" >
| < FUNCTION: "function" >
| < TENSOR_TYPE: "tensor" ("<" (~["<",">"])+ ">")? "(" (~["(",")"])* ")" >
| < TENSOR_VALUE_SL: "value" (" ")* ":" (" ")* ("{"<BRACE_SL_LEVEL_1>) ("\n")? >
| < TENSOR_VALUE_ML: "value" (<SEARCHLIB_SKIP>)? "{" (["\n"," "])* ("{"<BRACE_ML_LEVEL_1>) (["\n"," "])* "}" ("\n")? >
| < LBRACE: "{" >
| < RBRACE: "}" >
| < COLON: ":" >
| < DOT: "." >
| < COMMA: "," >
| < DOUBLE_KEYWORD: "double" >
| < INPUTS: "inputs" >
| < MODEL: "model" >
| < TYPE: "type" >
| < EXPRESSION_SL: "expression" (" ")* ":" (("{"<BRACE_SL_LEVEL_1>)|<BRACE_SL_CONTENT>)* ("\n")? >
| < EXPRESSION_ML: "expression" (<SEARCHLIB_SKIP>)? "{" (("{"<BRACE_ML_LEVEL_1>)|<BRACE_ML_CONTENT>)* "}" >
| < #BRACE_SL_LEVEL_1: (("{"<BRACE_SL_LEVEL_2>)|<BRACE_SL_CONTENT>)* "}" >
| < #BRACE_SL_LEVEL_2: (("{"<BRACE_SL_LEVEL_3>)|<BRACE_SL_CONTENT>)* "}" >
| < #BRACE_SL_LEVEL_3: <BRACE_SL_CONTENT> "}" >
| < #BRACE_SL_CONTENT: (~["{","}","\n"])* >
| < #BRACE_ML_LEVEL_1: (("{"<BRACE_ML_LEVEL_2>)|<BRACE_ML_CONTENT>)* "}" >
| < #BRACE_ML_LEVEL_2: (("{"<BRACE_ML_LEVEL_3>)|<BRACE_ML_CONTENT>)* "}" >
| < #BRACE_ML_LEVEL_3: <BRACE_ML_CONTENT> "}" >
| < #BRACE_ML_CONTENT: (~["{","}"])* >
| < #SEARCHLIB_SKIP: ([" ","\f","\n","\r","\t"])+ >
| < CONSTANT: "constant" >
| < CONSTANTS: "constants" >
| < FILE: "file" >
| < URI: "uri" >
| < IDENTIFIER:           ["a"-"z","A"-"Z", "_"] (["a"-"z","A"-"Z","0"-"9","_"])* >
| < DOUBLEQUOTEDSTRING: "\"" ( ~["\""] )* "\"" >
| < SINGLEQUOTEDSTRING: "'" ( ~["'"] )* "'" >
| < CONTEXT: ["a"-"z","A"-"Z"] (["a"-"z", "A"-"Z", "0"-"9"])* >
| < DOUBLE: ("-")? (["0"-"9"])+ "." (["0"-"9"])+ >
| < INTEGER: ("-")? (["0"-"9"])+ >
| < LONG: ("-")? (["0"-"9"])+"L" >
| < STRING: (["a"-"z","A"-"Z","_","0"-"9","."])+ >
| < FILE_PATH: ["a"-"z","A"-"Z", "_"] (["a"-"z","A"-"Z","0"-"9","_","-", "/", "."])+ >
| < HTTP: ["h","H"] ["t","T"] ["t","T"] ["p","P"] (["s","S"])? >
| < URI_PATH: <HTTP> <COLON> ("//")? (["a"-"z","A"-"Z","0"-"9","_","-", "/", ".",":"])+ >
}

// Declare a special skip token for comments.
SPECIAL_TOKEN :
{
  <SINGLE_LINE_COMMENT: "#" (~["\n","\r"])* >
}


// --------------------------------------------------------------------------------
//
// Production rules.
//
// --------------------------------------------------------------------------------

void model() :
{
    String name;
}
{
    (<NL>)*
    <MODEL>
    (<NL>)*
    name = identifier()
    (<NL>)*
    <LBRACE> modelContent() <RBRACE>
    (<NL>)*
    <EOF>
    {
        if ( ! model.name().endsWith(name))
            throw new IllegalArgumentException("Unexpected model name '" + model.name() +
                                               "': Model '" + name + "' must be saved in a file named '" + name + ".model'");
    }
}

void modelContent() :
{}
{
    ( <NL> |
      constants() |
      largeConstant() |
      function() |
      inputs() |
      input()
    )*
}

void inputs() :
{}
{
    <INPUTS> (<NL>)* <LBRACE> (<NL>)*
    ( input() (<NL>)* )*
    <RBRACE>
}

/** Declared input variables (aka features). All non-scalar inputs must be declared. */
void input() :
{
    String name;
    TensorType type;
}
{
    name = identifier() <COLON> type = tensorType("Input parameter '" + name + "'")
    { model.input(name, type); }
}

/** A function */
void function() :
{
    String name, expression, parameter;
    List< String > parameters = new ArrayList< String >();
}
{
    (  <FUNCTION> name = identifier()
      "("
          [ parameter = identifier()         { parameters.add(parameter); }
          ( <COMMA> parameter = identifier() { parameters.add(parameter); } )* ]
      ")"
      lbrace() expression = expression() (<NL>)* <RBRACE> )
    {
        model.expression(name, expression);
    }
}

/** Consumes the constants of this model. */
void constants() :
{
    String name;
}
{
    <CONSTANTS> <LBRACE> (<NL>)*
    ( constant() (<NL>)* )*
    <RBRACE>
}

String constantTensorErrorMessage(String constantTensorName) : {}
{
    { return "For constant tensor '" + constantTensorName + "' in '" + model + "'"; }
}

void constant() :
{
    String name = null;
    TensorType type = TensorType.empty;
    Tensor value = null;
    String valuePath = null;
}
{
    (
      name = identifier() (<COLON>)?
      (
        LOOKAHEAD(4) ( ( type = valueType(name) )? (<COLON>)? (<NL>)* ( value = tensorValue(type) | valuePath = fileItem())
        {
            if (value != null) {
                model.smallConstant(name, value);
            }
            else {
                try {
                    value = JsonFormat.decode(type, IOUtils.readFileBytes(model.relativeFile(valuePath, "constant '" + name + "'")));
                    model.largeConstant(name, value);
                }
                catch (Exception e) {
                    throw new IllegalArgumentException("Could not read constant '" + name + "'", e);
                }
            }
        }
        )
        | // Deprecated forms (TODO: Vespa > 8: Add warning ):
        ( constantValue(name) | constantTensor(name) )
      )
    )
}

// Deprecated form
void constantValue(String name) :
{
    Token value;
}
{
    <COLON> ( value = <DOUBLE> | value = <INTEGER> | value = <IDENTIFIER> )
    { model.smallConstant(name, Tensor.from(value.image)); }
}

// Deprecated form
void constantTensor(String name) :
{
    String tensorString = "";
    TensorType type = null;
}
{
    <LBRACE> (<NL>)*
      (( tensorString = tensorValuePrefixedByValue() |
         type = tensorTypeWithPrefix(constantTensorErrorMessage(name)) ) (<NL>)* )* <RBRACE>
    { model.smallConstant(name, type != null ? Tensor.from(type, tensorString) : Tensor.from(tensorString)); }
}

TensorType valueType(String name) :
{
    TensorType type;

}
{
    (
      ( type = tensorType("Type of " + name) )
      |
      ( <DOUBLE_KEYWORD> { type = TensorType.empty; } )
    )
    { return type; }
}

TensorType tensorType(String errorMessage) :
{
    String tensorTypeString;
}
{
    <TENSOR_TYPE> { tensorTypeString = token.image; }
    {
        TensorType tensorType;
        try {
            tensorType = TensorType.fromSpec(tensorTypeString);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(errorMessage + ": Illegal tensor type spec: " + e.getMessage());
        }
        return tensorType;
    }
}

/**
 * Parses a tensor written in a tensor literal form,
 * https://docs.vespa.ai/en/reference/tensor.html#tensor-literal-form
 */
Tensor tensorValue(TensorType type) :
{
    Tensor.Builder builder = Tensor.Builder.of(type);
    Number doubleValue = null;
}
{
    ( mappedTensorValue(builder) | indexedTensorValues(builder) |  doubleValue = number() )
    {
        if (doubleValue != null) {
            if (type.rank() > 0)
                throw new IllegalArgumentException("A tensor of type " + type + " cannot be a number");
            builder.cell(doubleValue.doubleValue());
        }
        return builder.build();
    }
}

/** A mapped or mixed tensor value. */
void mappedTensorValue(Tensor.Builder builder) : {}
{
    "{"
    ( mappedTensorBlock(builder) )*
    ( <COMMA> (<NL>)* mappedTensorBlock(builder) )*
    "}"
}


void mappedTensorBlock(Tensor.Builder builder) :
{
    TensorAddress mappedAddress;
}
{
    mappedAddress = tensorAddress(builder.type()) <COLON> (<NL>)*
    ( mappedTensorCellValue(mappedAddress, builder) | indexedTensorBlockValues(mappedAddress, builder) )
}

void indexedTensorBlockValues(TensorAddress mappedAddress, Tensor.Builder builder) :
{
    List<Double> values = new ArrayList<Double>();
}
{
    arrayTensorValues(values)
    {
        MixedTensor.BoundBuilder boundBuilder = (MixedTensor.BoundBuilder)builder;
        double[] arrayValues = new double[values.size()];
        for (int i = 0; i < values.size(); i++ ) {
            arrayValues[i] = values.get(i);
        }
        boundBuilder.block(mappedAddress, arrayValues);
    }
}

void indexedTensorValues(Tensor.Builder builder) :
{
    List<Double> values = new ArrayList<Double>();
}
{
    arrayTensorValues(values)
    {
        IndexedTensor.BoundBuilder boundBuilder = (IndexedTensor.BoundBuilder)builder;
        double[] arrayValues = new double[values.size()];
        for (int i = 0; i < values.size(); i++ ) {
            arrayValues[i] = values.get(i);
        }
        boundBuilder.fill(arrayValues);
    }
}

/** Tensor array values. Using sub-bracketing for multiple dimensions is optional and therefore ignored here. */
void arrayTensorValues(List<Double> values) : {}
{
    "[" (                 ( indexedTensorValue(values) | arrayTensorValues(values)) )*
        ( <COMMA> (<NL>)* ( indexedTensorValue(values) | arrayTensorValues(values)) )*
    "]"
}

void indexedTensorValue(List<Double> values) :
{
    Number value;
}
{
    value = number()
    { values.add(value.doubleValue()); }
}

void mappedTensorCellValue(TensorAddress address, Tensor.Builder builder) :
{
    double value;
}
{
    value = tensorCellValue()
    { builder.cell(address, value); }
}

TensorAddress tensorAddress(TensorType type) :
{
    TensorAddress.Builder builder = new TensorAddress.PartialBuilder(type);
    String label;
}
{
    (
        label = tensorAddressLabel() { builder.add(label); }
        |
        ( "{" ( tensorAddressElement(builder) )* ( <COMMA> tensorAddressElement(builder) )* "}" )
    )
    { return builder.build(); }
}

void tensorAddressElement(TensorAddress.Builder builder) :
{
    String dimension;
    String label;
}
{
    dimension = identifier() <COLON> (<NL>)* label = tensorAddressLabel()
    { builder.add(dimension, label); }
}

String tensorAddressLabel() :
{
    String label;
}
{
    ( label = identifier() | label = quotedString() )
    { return label; }
}

double tensorCellValue() :
{
    Number value;
}
{
    value = number()
    { return value.doubleValue(); }
}

/** Undocumented syntax for supplying a tensor constant value by a string prefixed by "value" */
String tensorValuePrefixedByValue() :
{
    String tensor;
}
{
    ( <TENSOR_VALUE_SL> { tensor = token.image.substring(token.image.indexOf(":") + 1); } |
      <TENSOR_VALUE_ML> { tensor = token.image.substring(token.image.indexOf("{") + 1,
                                                         token.image.lastIndexOf("}")); } )
    {
        return tensor;
    }
}

TensorType tensorTypeWithPrefix(String errorMessage) :
{
    String tensorTypeString;
}
{
    <TENSOR_TYPE> { tensorTypeString = token.image; }
    {
        TensorType tensorType;
        try {
            tensorType = TensorType.fromSpec(tensorTypeString);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(errorMessage + ": Illegal tensor type spec: " + e.getMessage());
        }
        return tensorType;
    }
}

/** Consumes a large constant. */ // TODO: Remove on Vespa 9
void largeConstant() :
{
    String name;
    Tensor value;
}
{
    ( <CONSTANT> name = identifier() lbrace() value = largeConstantBody(name) <RBRACE> )
    { model.largeConstant(name, value); }
}

// TODO: Add support in ImportedModel for passing a large tensor through as a file/Uri pointer instead of reading it here
Tensor largeConstantBody(String name) :
{
    String path = null;
    TensorType type = null;
}
{
    (   <FILE> <COLON> path = filePath()
//      | (<URI> <COLON> path = uriPath() TODO
      | <TYPE> <COLON> type = tensorType("Constant '" + name + "'")
      | <NL>
    )+
    {
        try {
            return JsonFormat.decode(type, IOUtils.readFileBytes(model.relativeFile(path, "constant '" + name + "'")));
        }
        catch (Exception e) {
            throw new IllegalArgumentException("Could not read constant '" + name + "'", e);
        }
    }
}

String filePath() : { }
{
    ( <FILE_PATH> | <STRING> | <IDENTIFIER>)
    { return token.image; }
}

String uriPath() : { }
{
    ( <URI_PATH> )
    { return token.image; }
}

/** Consumes an expression token and returns its image. */
String expression() :
{
    String exp;
}
{
    ( <EXPRESSION_SL> { exp = token.image.substring(token.image.indexOf(":") + 1); } |
      <EXPRESSION_ML> { exp = token.image.substring(token.image.indexOf("{") + 1,
                                                    token.image.lastIndexOf("}")); } )
    { return exp; }
}

/** Consumes an identifier. This must be kept in sync with all word tokens that should be parseable as identifiers. */
String identifier() : { }
{
    (
      <CONSTANT> |
      <CONSTANTS> |
      <DOUBLE_KEYWORD> |
      <FILE> |
      <IDENTIFIER> |
      <INPUTS> |
      <INTEGER> |
      <MODEL> |
      <TYPE> |
      <URI>
    )
    { return token.image; }
}

Number number() :
{
    Number num;
}
{
    (num = floatValue() | num = longValue() ) { return num; }
}

/** Consumes a long or integer token and returns its numeric value. */
long longValue() : { }
{
    ( <INTEGER> { return Long.parseLong(token.image); } |
      <LONG>    { return Long.parseLong(token.image.substring(0, token.image.length()-1)); }
    )
}

/** Consumes a floating-point token and returns its numeric value. */
double floatValue() : { }
{
    <DOUBLE> { return Double.valueOf(token.image); }
}

/** Consumes an opening brace with leading and trailing newline tokens. */
void lbrace() : { }
{
    (<NL>)* <LBRACE> (<NL>)*
}

String fileItem() :
{
   String path;
}
{
  (<FILE> <COLON> ( <FILE_PATH> | <STRING> | <IDENTIFIER>) { path = com.yahoo.path.Path.fromString(token.image).getRelative(); } { } (<NL>)*) { return path; }
}

/**
 * Consumes a quoted string token and returns the token image minus the quotes. This does not perform
 * unescaping of the content, it simply removes the first and last character of the image. However, the token itself can
 * contain anything but a double quote.
 *
 * @return the unquoted token image
 */
String quotedString() : { }
{
    ( <DOUBLEQUOTEDSTRING> | <SINGLEQUOTEDSTRING> )
    { return token.image.substring(1, token.image.length() - 1); }
}