File size: 2,648 Bytes
25ed21e | 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 | import random
import numpy as np
from contextlib import contextmanager
from omegaconf import OmegaConf
import dataclasses
@contextmanager
def all_seed(seed):
random_state = random.getstate()
np_random_state = np.random.get_state()
try:
random.seed(seed)
np.random.seed(seed)
yield
finally:
random.setstate(random_state)
np.random.set_state(np_random_state)
def register_resolvers():
try:
OmegaConf.register_new_resolver("mul", lambda x, y: x * y)
OmegaConf.register_new_resolver("int_div", lambda x, y: int(float(x) / float(y)))
OmegaConf.register_new_resolver("not", lambda x: not x)
except:
pass # already registered
@dataclasses.dataclass
class GenerationsLogger:
def log(self, loggers, samples, step, _type='val'):
if 'wandb' in loggers:
self.log_generations_to_wandb(samples, step, _type)
if 'swanlab' in loggers:
self.log_generations_to_swanlab(samples, step, _type)
def log_generations_to_wandb(self, samples, step, _type='val'):
"""Log samples to wandb as a table"""
import wandb
# Create column names for all samples
columns = ["step"] + sum([[f"input_{i+1}", f"output_{i+1}", f"score_{i+1}"] for i in range(len(samples))], [])
if not hasattr(self, 'table'):
# Initialize the table on first call
self.table = wandb.Table(columns=columns)
# Create a new table with same columns and existing data
# Workaround for https://github.com/wandb/wandb/issues/2981#issuecomment-1997445737
new_table = wandb.Table(columns=columns, data=self.table.data)
# Add new row with all data
row_data = []
row_data.append(step)
for sample in samples:
row_data.extend(sample)
new_table.add_data(*row_data)
# Update reference and log
wandb.log({f"{_type}/generations": new_table}, step=step)
self.table = new_table
def log_generations_to_swanlab(self, samples, step, _type='val'):
"""Log samples to swanlab as text"""
import swanlab
swanlab_text_list = []
for i, sample in enumerate(samples):
row_text = f"""
input: {sample[0]}
---
output: {sample[1]}
---
score: {sample[2]}
"""
swanlab_text_list.append(swanlab.Text(row_text, caption=f"sample {i+1}"))
# Log to swanlab
swanlab.log({f"{_type}/generations": swanlab_text_list}, step=step)
|