aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/xla/text_literal_reader.cc
blob: cdde88c1359416d423685f330e9cbdf77948034f (plain)
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
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/text_literal_reader.h"

#include <limits>
#include <string>
#include <utility>
#include <vector>

#include "absl/memory/memory.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"

namespace xla {

StatusOr<Literal> TextLiteralReader::ReadPath(absl::string_view path) {
  CHECK(!absl::EndsWith(path, ".gz"))
      << "TextLiteralReader no longer supports reading .gz files";
  std::unique_ptr<tensorflow::RandomAccessFile> file;
  Status s =
      tensorflow::Env::Default()->NewRandomAccessFile(std::string(path), &file);
  if (!s.ok()) {
    return s;
  }

  TextLiteralReader reader(file.release());
  return reader.ReadAllLines();
}

TextLiteralReader::TextLiteralReader(tensorflow::RandomAccessFile* file)
    : file_(file) {}

StatusOr<Literal> TextLiteralReader::ReadAllLines() {
  tensorflow::io::RandomAccessInputStream stream(file_.get());
  tensorflow::io::BufferedInputStream buf(&stream, 65536);
  string shape_string;
  Status s = buf.ReadLine(&shape_string);
  if (!s.ok()) {
    return s;
  }

  absl::StripAsciiWhitespace(&shape_string);
  TF_ASSIGN_OR_RETURN(Shape shape, ShapeUtil::ParseShapeString(shape_string));
  if (shape.element_type() != F32) {
    return Unimplemented(
        "unsupported element type for text literal reading: %s",
        ShapeUtil::HumanString(shape));
  }

  Literal result(shape);
  const float fill = std::numeric_limits<float>::quiet_NaN();
  result.PopulateWithValue<float>(fill);
  std::vector<absl::string_view> pieces;
  std::vector<absl::string_view> coordinates;
  std::vector<int64> coordinate_values;
  string line;
  while (buf.ReadLine(&line).ok()) {
    pieces = absl::StrSplit(line, ':');
    absl::string_view coordinates_string =
        absl::StripAsciiWhitespace(pieces[0]);
    absl::string_view value_string = absl::StripAsciiWhitespace(pieces[1]);
    if (!absl::ConsumePrefix(&coordinates_string, "(")) {
      return InvalidArgument(
          "expected '(' at the beginning of coordinates: \"%s\"", line);
    }
    if (!absl::ConsumeSuffix(&coordinates_string, ")")) {
      return InvalidArgument("expected ')' at the end of coordinates: \"%s\"",
                             line);
    }
    float value;
    if (!absl::SimpleAtof(value_string, &value)) {
      return InvalidArgument("could not parse value as float: \"%s\"",
                             value_string);
    }
    coordinates = absl::StrSplit(coordinates_string, ',');
    coordinate_values.clear();
    for (absl::string_view piece : coordinates) {
      int64 coordinate_value;
      if (!absl::SimpleAtoi(piece, &coordinate_value)) {
        return InvalidArgument(
            "could not parse coordinate member as int64: \"%s\"",
            std::string(piece));
      }
      coordinate_values.push_back(coordinate_value);
    }
    if (coordinate_values.size() != shape.dimensions_size()) {
      return InvalidArgument(
          "line did not have expected number of coordinates; want %d got %u: "
          "\"%s\"",
          shape.dimensions_size(), coordinate_values.size(), line);
    }
    result.Set<float>(coordinate_values, value);
  }
  return std::move(result);
}

}  // namespace xla