1//===- TrainingLogger.cpp - mlgo feature/reward logging -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements logging infrastructure for extracting features and
10// rewards for mlgo policy training.
11//
12//===----------------------------------------------------------------------===//
13#include "llvm/Analysis/TensorSpec.h"
14#include "llvm/Config/config.h"
15
16#include "llvm/ADT/Twine.h"
17#include "llvm/Analysis/Utils/TrainingLogger.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/JSON.h"
20#include "llvm/Support/raw_ostream.h"
21
22#include <cassert>
23
24using namespace llvm;
25
26void Logger::writeHeader(std::optional<TensorSpec> AdviceSpec) {
27 json::OStream JOS(*OS);
28 JOS.object(Contents: [&]() {
29 JOS.attributeArray(Key: "features", Contents: [&]() {
30 for (const auto &TS : FeatureSpecs)
31 TS.toJSON(OS&: JOS);
32 });
33 if (IncludeReward) {
34 JOS.attributeBegin(Key: "score");
35 RewardSpec.toJSON(OS&: JOS);
36 JOS.attributeEnd();
37 }
38 if (AdviceSpec.has_value()) {
39 JOS.attributeBegin(Key: "advice");
40 AdviceSpec->toJSON(OS&: JOS);
41 JOS.attributeEnd();
42 }
43 });
44 *OS << "\n";
45}
46
47void Logger::switchContext(StringRef Name) {
48 CurrentContext = Name.str();
49 json::OStream JOS(*OS);
50 JOS.object(Contents: [&]() { JOS.attribute(Key: "context", Contents: Name); });
51 *OS << "\n";
52}
53
54void Logger::startObservation() {
55 auto I = ObservationIDs.insert(KV: {CurrentContext, 0});
56 size_t NewObservationID = I.second ? 0 : ++I.first->second;
57 json::OStream JOS(*OS);
58 JOS.object(Contents: [&]() {
59 JOS.attribute(Key: "observation", Contents: static_cast<int64_t>(NewObservationID));
60 });
61 *OS << "\n";
62}
63
64void Logger::endObservation() { *OS << "\n"; }
65
66void Logger::logRewardImpl(const char *RawData) {
67 assert(IncludeReward);
68 json::OStream JOS(*OS);
69 JOS.object(Contents: [&]() {
70 JOS.attribute(Key: "outcome", Contents: static_cast<int64_t>(
71 ObservationIDs.find(Key: CurrentContext)->second));
72 });
73 *OS << "\n";
74 writeTensor(Spec: RewardSpec, RawData);
75 *OS << "\n";
76}
77
78Logger::Logger(std::unique_ptr<raw_ostream> OS,
79 const std::vector<TensorSpec> &FeatureSpecs,
80 const TensorSpec &RewardSpec, bool IncludeReward,
81 std::optional<TensorSpec> AdviceSpec)
82 : OS(std::move(OS)), FeatureSpecs(FeatureSpecs), RewardSpec(RewardSpec),
83 IncludeReward(IncludeReward) {
84 writeHeader(AdviceSpec);
85}
86