2020-08-20 02:03:22 +00:00
|
|
|
# Copyright The PyTorch Lightning team.
|
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
|
2020-10-07 11:28:23 +00:00
|
|
|
import os
|
2020-06-12 15:23:18 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
2020-10-07 11:28:23 +00:00
|
|
|
import fsspec
|
2020-03-30 22:28:31 +00:00
|
|
|
import torch
|
2020-10-07 11:28:23 +00:00
|
|
|
from pytorch_lightning.utilities.cloud_io import get_filesystem
|
2020-08-14 21:52:43 +00:00
|
|
|
from torch import Tensor
|
2020-03-30 22:28:31 +00:00
|
|
|
|
|
|
|
|
2020-04-08 12:35:47 +00:00
|
|
|
class TensorRunningAccum(object):
|
|
|
|
"""Tracks a running accumulation values (min, max, mean) without graph
|
|
|
|
references.
|
2020-03-30 22:28:31 +00:00
|
|
|
|
|
|
|
Examples:
|
2020-04-08 12:35:47 +00:00
|
|
|
>>> accum = TensorRunningAccum(5)
|
2020-03-30 22:28:31 +00:00
|
|
|
>>> accum.last(), accum.mean()
|
|
|
|
(None, None)
|
|
|
|
>>> accum.append(torch.tensor(1.5))
|
|
|
|
>>> accum.last(), accum.mean()
|
|
|
|
(tensor(1.5000), tensor(1.5000))
|
|
|
|
>>> accum.append(torch.tensor(2.5))
|
|
|
|
>>> accum.last(), accum.mean()
|
|
|
|
(tensor(2.5000), tensor(2.))
|
|
|
|
>>> accum.reset()
|
|
|
|
>>> _= [accum.append(torch.tensor(i)) for i in range(13)]
|
2020-04-08 12:35:47 +00:00
|
|
|
>>> accum.last(), accum.mean(), accum.min(), accum.max()
|
|
|
|
(tensor(12.), tensor(10.), tensor(8.), tensor(12.))
|
2020-03-30 22:28:31 +00:00
|
|
|
"""
|
2020-04-10 15:43:06 +00:00
|
|
|
|
2020-03-30 22:28:31 +00:00
|
|
|
def __init__(self, window_length: int):
|
|
|
|
self.window_length = window_length
|
2020-11-02 23:44:11 +00:00
|
|
|
self.memory = torch.zeros(self.window_length)
|
2020-03-30 22:28:31 +00:00
|
|
|
self.current_idx: int = 0
|
2020-06-12 15:23:18 +00:00
|
|
|
self.last_idx: Optional[int] = None
|
2020-03-30 22:28:31 +00:00
|
|
|
self.rotated: bool = False
|
|
|
|
|
|
|
|
def reset(self) -> None:
|
2020-04-08 12:35:47 +00:00
|
|
|
"""Empty the accumulator."""
|
|
|
|
self = TensorRunningAccum(self.window_length)
|
2020-03-30 22:28:31 +00:00
|
|
|
|
|
|
|
def last(self):
|
2020-04-08 12:35:47 +00:00
|
|
|
"""Get the last added element."""
|
2020-03-30 22:28:31 +00:00
|
|
|
if self.last_idx is not None:
|
|
|
|
return self.memory[self.last_idx]
|
|
|
|
|
|
|
|
def append(self, x):
|
2020-04-08 12:35:47 +00:00
|
|
|
"""Add an element to the accumulator."""
|
2020-04-07 00:29:55 +00:00
|
|
|
# ensure same device and type
|
|
|
|
if self.memory.device != x.device or self.memory.type() != x.type():
|
|
|
|
x = x.to(self.memory)
|
2020-03-30 22:28:31 +00:00
|
|
|
|
|
|
|
# store without grads
|
|
|
|
with torch.no_grad():
|
|
|
|
self.memory[self.current_idx] = x
|
|
|
|
self.last_idx = self.current_idx
|
|
|
|
|
|
|
|
# increase index
|
|
|
|
self.current_idx += 1
|
|
|
|
|
|
|
|
# reset index when hit limit of tensor
|
|
|
|
self.current_idx = self.current_idx % self.window_length
|
|
|
|
if self.current_idx == 0:
|
|
|
|
self.rotated = True
|
|
|
|
|
|
|
|
def mean(self):
|
2020-04-08 12:35:47 +00:00
|
|
|
"""Get mean value from stored elements."""
|
|
|
|
return self._agg_memory('mean')
|
|
|
|
|
|
|
|
def max(self):
|
|
|
|
"""Get maximal value from stored elements."""
|
|
|
|
return self._agg_memory('max')
|
|
|
|
|
|
|
|
def min(self):
|
|
|
|
"""Get minimal value from stored elements."""
|
|
|
|
return self._agg_memory('min')
|
|
|
|
|
|
|
|
def _agg_memory(self, how: str):
|
2020-03-30 22:28:31 +00:00
|
|
|
if self.last_idx is not None:
|
2020-04-08 12:35:47 +00:00
|
|
|
if self.rotated:
|
|
|
|
return getattr(self.memory, how)()
|
|
|
|
else:
|
2020-10-07 11:28:23 +00:00
|
|
|
return getattr(self.memory[: self.current_idx], how)()
|
2020-07-20 23:00:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Accumulator(object):
|
|
|
|
def __init__(self):
|
|
|
|
self.num_values = 0
|
|
|
|
self.total = 0
|
|
|
|
|
|
|
|
def accumulate(self, x):
|
|
|
|
with torch.no_grad():
|
|
|
|
self.total += x
|
|
|
|
self.num_values += 1
|
|
|
|
|
|
|
|
def mean(self):
|
|
|
|
return self.total / self.num_values
|
2020-08-14 21:52:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
class PredictionCollection(object):
|
|
|
|
def __init__(self, global_rank: int, world_size: int):
|
|
|
|
self.global_rank = global_rank
|
|
|
|
self.world_size = world_size
|
|
|
|
self.predictions = {}
|
|
|
|
self.num_predictions = 0
|
|
|
|
|
|
|
|
def _add_prediction(self, name, values, filename):
|
|
|
|
if filename not in self.predictions:
|
|
|
|
self.predictions[filename] = {name: values}
|
|
|
|
elif name not in self.predictions[filename]:
|
|
|
|
self.predictions[filename][name] = values
|
|
|
|
elif isinstance(values, Tensor):
|
2020-10-07 11:28:23 +00:00
|
|
|
self.predictions[filename][name] = torch.cat(
|
|
|
|
(self.predictions[filename][name], values)
|
|
|
|
)
|
2020-08-14 21:52:43 +00:00
|
|
|
elif isinstance(values, list):
|
|
|
|
self.predictions[filename][name].extend(values)
|
|
|
|
|
|
|
|
def add(self, predictions):
|
|
|
|
|
|
|
|
if predictions is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
for filename, pred_dict in predictions.items():
|
|
|
|
for feature_name, values in pred_dict.items():
|
|
|
|
self._add_prediction(feature_name, values, filename)
|
|
|
|
|
2020-10-07 11:28:23 +00:00
|
|
|
def to_disk(self) -> None:
|
2020-08-14 21:52:43 +00:00
|
|
|
"""Write predictions to file(s).
|
|
|
|
"""
|
2020-10-07 11:28:23 +00:00
|
|
|
for filepath, predictions in self.predictions.items():
|
|
|
|
fs = get_filesystem(filepath)
|
|
|
|
# normalize local filepaths only
|
|
|
|
if fs.protocol == "file":
|
|
|
|
filepath = os.path.realpath(filepath)
|
|
|
|
if self.world_size > 1:
|
|
|
|
stem, extension = os.path.splitext(filepath)
|
|
|
|
filepath = f"{stem}_rank_{self.global_rank}{extension}"
|
|
|
|
dirpath = os.path.split(filepath)[0]
|
|
|
|
fs.mkdirs(dirpath, exist_ok=True)
|
2020-08-14 21:52:43 +00:00
|
|
|
|
|
|
|
# Convert any tensor values to list
|
2020-10-07 11:28:23 +00:00
|
|
|
predictions = {
|
|
|
|
k: v if not isinstance(v, Tensor) else v.tolist()
|
|
|
|
for k, v in predictions.items()
|
|
|
|
}
|
2020-08-14 21:52:43 +00:00
|
|
|
|
|
|
|
# Check if all features for this file add up to same length
|
|
|
|
feature_lens = {k: len(v) for k, v in predictions.items()}
|
|
|
|
if len(set(feature_lens.values())) != 1:
|
2020-10-07 11:28:23 +00:00
|
|
|
raise ValueError(
|
|
|
|
"Mismatching feature column lengths found in stored EvalResult predictions."
|
|
|
|
)
|
2020-08-14 21:52:43 +00:00
|
|
|
|
|
|
|
# Switch predictions so each entry has its own dict
|
|
|
|
outputs = []
|
|
|
|
for values in zip(*predictions.values()):
|
|
|
|
output_element = {k: v for k, v in zip(predictions.keys(), values)}
|
|
|
|
outputs.append(output_element)
|
|
|
|
|
|
|
|
# Write predictions for current file to disk
|
2020-10-07 11:28:23 +00:00
|
|
|
with fs.open(filepath, "wb") as fp:
|
|
|
|
torch.save(outputs, fp)
|