from megengine.logger import get_logger
logger = get_logger(__name__)
try:
from tensorboardX import SummaryWriter
from tensorboardX.proto.attr_value_pb2 import AttrValue
from tensorboardX.proto.graph_pb2 import GraphDef
from tensorboardX.proto.node_def_pb2 import NodeDef
from tensorboardX.proto.plugin_text_pb2 import TextPluginData
from tensorboardX.proto.step_stats_pb2 import (
DeviceStepStats,
RunMetadata,
StepStats,
)
from tensorboardX.proto.summary_pb2 import Summary, SummaryMetadata
from tensorboardX.proto.tensor_pb2 import TensorProto
from tensorboardX.proto.tensor_shape_pb2 import TensorShapeProto
from tensorboardX.proto.versions_pb2 import VersionDef
except ImportError:
logger.error(
"TensorBoard and TensorboardX are required for visualize.", exc_info=True,
)
def tensor_shape_proto(shape):
return TensorShapeProto(dim=[TensorShapeProto.Dim(size=d) for d in shape])
def attr_value_proto(shape, dtype, attr):
attr_proto = {}
if shape is not None:
shapeproto = tensor_shape_proto(shape)
attr_proto["_output_shapes"] = AttrValue(
list=AttrValue.ListValue(shape=[shapeproto])
)
if dtype is not None:
attr_proto["dtype"] = AttrValue(s=dtype.encode(encoding="utf-8"))
if attr is not None:
for key in attr.keys():
attr_proto[key] = AttrValue(s=attr[key].encode(encoding="utf-8"))
return attr_proto
def node_proto(
name, op="UnSpecified", input=None, outputshape=None, dtype=None, attributes={}
):
if input is None:
input = []
if not isinstance(input, list):
input = [input]
return NodeDef(
name=name.encode(encoding="utf_8"),
op=op,
input=input,
attr=attr_value_proto(outputshape, dtype, attributes),
)
def node(
name, op="UnSpecified", input=None, outputshape=None, dtype=None, attributes={}
):
return node_proto(name, op, input, outputshape, dtype, attributes)
def graph(node_list):
graph_def = GraphDef(node=node_list, versions=VersionDef(producer=22))
stepstats = RunMetadata(
step_stats=StepStats(dev_stats=[DeviceStepStats(device="/device:CPU:0")])
)
return graph_def, stepstats
def text(tag, text):
plugin_data = SummaryMetadata.PluginData(
plugin_name="text", content=TextPluginData(version=0).SerializeToString()
)
smd = SummaryMetadata(plugin_data=plugin_data)
string_val = []
for item in text:
string_val.append(item.encode(encoding="utf_8"))
tensor = TensorProto(
dtype="DT_STRING",
string_val=string_val,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=len(text))]),
)
return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)])
class NodeRaw:
def __init__(self, name, op, input, outputshape, dtype, attributes):
self.name = name
self.op = op
self.input = input
self.outputshape = outputshape
self.dtype = dtype
self.attributes = attributes
class SummaryWriterExtend(SummaryWriter):
def __init__(
self,
logdir=None,
comment="",
purge_step=None,
max_queue=10,
flush_secs=120,
filename_suffix="",
write_to_disk=True,
log_dir=None,
**kwargs
):
self.node_raw_dict = {}
super().__init__(
logdir,
comment,
purge_step,
max_queue,
flush_secs,
filename_suffix,
write_to_disk,
log_dir,
**kwargs,
)
def add_text(self, tag, text_string_list, global_step=None, walltime=None):
self._get_file_writer().add_summary(
text(tag, text_string_list), global_step, walltime
)
def add_node_raw(
self,
name,
op="UnSpecified",
input=[],
outputshape=None,
dtype=None,
attributes={},
):
self.node_raw_dict[name] = NodeRaw(
name, op, input, outputshape, dtype, dict(attributes)
)
def add_node_raw_name_suffix(self, name, suffix):
old_name = self.node_raw_dict[name].name
new_name = old_name + suffix
self.node_raw_dict[name].name = new_name
for node_name, node in self.node_raw_dict.items():
node.input = [new_name if x == old_name else x for x in node.input]
def add_node_raw_attributes(self, name, attributes):
for key, value in attributes.items():
self.node_raw_dict[name].attributes[key] = value
def add_graph_by_node_raw_list(self):
node_raw_list = []
for key, value in self.node_raw_dict.items():
node_raw_list.append(
node(
value.name,
value.op,
value.input,
value.outputshape,
value.dtype,
value.attributes,
)
)
self._get_file_writer().add_graph(graph(node_raw_list))