1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/compiler/xla/sharding_op_util.h"
17
18 #include <string>
19 #include <vector>
20
21 #include "absl/strings/str_cat.h"
22 #include "absl/strings/str_join.h"
23 #include "absl/strings/string_view.h"
24 #include "absl/types/span.h"
25 #include "tensorflow/compiler/xla/service/hlo_lexer.h"
26 #include "tensorflow/compiler/xla/status_macros.h"
27
28 namespace xla {
29 namespace sharding_op_util {
30
EncodeAttributes(absl::Span<const int64_t> unspecified_dims)31 std::string EncodeAttributes(absl::Span<const int64_t> unspecified_dims) {
32 if (unspecified_dims.empty()) {
33 return "";
34 }
35 return absl::StrCat("unspecified_dims=[",
36 absl::StrJoin(unspecified_dims, ","), "]");
37 }
38
ParseAttributes(absl::string_view opaque,std::vector<int64_t> * unspecified_dims)39 Status ParseAttributes(absl::string_view opaque,
40 std::vector<int64_t>* unspecified_dims) {
41 HloLexer lexer(opaque);
42 while (lexer.Lex() != TokKind::kEof) {
43 if (lexer.GetKind() != TokKind::kAttributeName) {
44 return InvalidArgumentStrCat("Cannot parse sharding op attributes: ",
45 opaque);
46 }
47 std::string attr_name = lexer.GetStrVal();
48 if (attr_name == "unspecified_dims") {
49 TF_RET_CHECK(lexer.Lex() == TokKind::kLsquare);
50 while (lexer.Lex() == TokKind::kInt) {
51 unspecified_dims->push_back(lexer.GetInt64Val());
52 if (lexer.Lex() != TokKind::kComma) {
53 break;
54 }
55 }
56 TF_RET_CHECK(lexer.GetKind() == TokKind::kRsquare);
57 } else {
58 return InvalidArgumentStrCat("Unknown attribute name in sharding op: ",
59 attr_name);
60 }
61 }
62 return OkStatus();
63 }
64
65 } // namespace sharding_op_util
66 } // namespace xla
67