Certainly! Below is a C# class representing an editable config file structure with the defaults initialized as per your YAML config. The class uses properties reflecting the config file structure and default values:
csharp
using System.Collections.Generic;
namespace FishSpeechConfig
{
public class Config
{
public List<string> Defaults { get; set; } = new List<string> { "base", "_self_" };
public string Project { get; set; } = "text2semantic_finetune_dual_ar";
public int MaxLength { get; set; } = 1024;
public string PretrainedCkptPath { get; set; } = "checkpoints/fish-speech-1.5";
public TrainerConfig Trainer { get; set; } = new TrainerConfig();
public TokenizerConfig Tokenizer { get; set; }
public DatasetConfig TrainDataset { get; set; }
public DatasetConfig ValDataset { get; set; }
public DataConfig Data { get; set; }
public ModelConfig Model { get; set; }
public CallbacksConfig Callbacks { get; set; }
public Config()
{
// Initialize Tokenizer with reference to PretrainedCkptPath
Tokenizer = new TokenizerConfig
{
Target = "fish_speech.tokenizer.FishTokenizer",
ModelPath = $"{PretrainedCkptPath}/tokenizer.tiktoken"
};
// Initialize Train and Val Datasets with reference to Tokenizer and MaxLength
TrainDataset = new DatasetConfig
{
Target = "fish_speech.datasets.semantic.AutoTextSemanticInstructionIterableDataset",
ProtoFiles = new List<string> { "data/protos" },
Tokenizer = Tokenizer,
Causal = true,
MaxLength = MaxLength,
UseSpeaker = false,
InteractiveProb = 0.7
};
ValDataset = new DatasetConfig
{
Target = "fish_speech.datasets.semantic.AutoTextSemanticInstructionIterableDataset",
ProtoFiles = new List<string> { "data/protos" },
Tokenizer = Tokenizer,
Causal = true,
MaxLength = MaxLength,
UseSpeaker = false,
InteractiveProb = 0.7
};
// Data config referencing train/val datasets and tokenizer
Data = new DataConfig
{
Target = "fish_speech.datasets.semantic.SemanticDataModule",
TrainDataset = TrainDataset,
ValDataset = ValDataset,
NumWorkers = 8,
BatchSize = 3,
Tokenizer = Tokenizer,
MaxLength = MaxLength
};
// Model config with nested objects and references
Model = new ModelConfig
{
Target = "fish_speech.models.text2semantic.lit_module.TextToSemantic",
InnerModel = new InnerModelConfig
{
Target = "fish_speech.models.text2semantic.llama.BaseTransformer.from_pretrained",
Path = PretrainedCkptPath,
LoadWeights = true,
MaxLength = MaxLength,
LoraConfig = null
},
Optimizer = new OptimizerConfig
{
Target = "torch.optim.AdamW",
Partial = true,
Lr = 1e-4,
WeightDecay = 0,
Betas = new double[] { 0.9, 0.95 },
Eps = 1e-5
},
LrScheduler = new LrSchedulerConfig
{
Target = "torch.optim.lr_scheduler.LambdaLR",
Partial = true,
LrLambda = new LrLambdaConfig
{
Target = "fish_speech.scheduler.get_constant_schedule_with_warmup_lr_lambda",
Partial = true,
NumWarmupSteps = 10
}
}
};
// Callbacks referencing Trainer val_check_interval
Callbacks = new CallbacksConfig
{
ModelCheckpoint = new ModelCheckpointConfig
{
EveryNTrainSteps = Trainer.ValCheckInterval
}
};
}
}
public class TrainerConfig
{
public int AccumulateGradBatches { get; set; } = 1;
public float GradientClipVal { get; set; } = 1.0f;
public string GradientClipAlgorithm { get; set; } = "norm";
public int MaxSteps { get; set; } = 10000;
public int Precision { get; set; } = 16;
public int LimitValBatches { get; set; } = 10;
public int ValCheckInterval { get; set; } = 500;
public int Devices { get; set; } = 1;
public string Accelerator { get; set; } = "gpu";
public string Strategy { get; set; } = "auto";
}
public class TokenizerConfig
{
public string Target { get; set; }
public string ModelPath { get; set; }
}
public class DatasetConfig
{
public string Target { get; set; }
public List<string> ProtoFiles { get; set; }
public TokenizerConfig Tokenizer { get; set; }
public bool Causal { get; set; }
public int MaxLength { get; set; }
public bool UseSpeaker { get; set; }
public double InteractiveProb { get; set; }
}
public class DataConfig
{
public string Target { get; set; }
public DatasetConfig TrainDataset { get; set; }
public DatasetConfig ValDataset { get; set; }
public int NumWorkers { get; set; }
public int BatchSize { get; set; }
public TokenizerConfig Tokenizer { get; set; }
public int MaxLength { get; set; }
}
public class ModelConfig
{
public string Target { get; set; }
public InnerModelConfig InnerModel { get; set; }
public OptimizerConfig Optimizer { get; set; }
public LrSchedulerConfig LrScheduler { get; set; }
}
public class InnerModelConfig
{
public string Target { get; set; }
public string Path { get; set; }
public bool LoadWeights { get; set; }
public int MaxLength { get; set; }
public object LoraConfig { get; set; }
}
public class OptimizerConfig
{
public string Target { get; set; }
public bool Partial { get; set; }
public double Lr { get; set; }
public double WeightDecay { get; set; }
public double[] Betas { get; set; }
public double Eps { get; set; }
}
public class LrSchedulerConfig
{
public string Target { get; set; }
public bool Partial { get; set; }
public LrLambdaConfig LrLambda { get; set; }
}
public class LrLambdaConfig
{
public string Target { get; set; }
public bool Partial { get; set; }
public int NumWarmupSteps { get; set; }
}
public class CallbacksConfig
{
public ModelCheckpointConfig ModelCheckpoint { get; set; }
}
public class ModelCheckpointConfig
{
public int EveryNTrainSteps { get; set; }
}
}
Explanation:
Properties represent all fields from the YAML, using C# naming conventions.
Default values are assigned in the constructor or inline to mirror your YAML defaults.
For references like ${pretrained_ckpt_path} or ${tokenizer}, the constructor initializes objects accordingly.
Nullable field LoraConfig is typed object to represent null.
Nested structures reflect the nested YAML contents.
You can easily edit properties of the Config object in C# code, then serialize/deserialize to YAML or JSON as needed.
If you want, I can also provide serialization/deserialization helpers using e.g. YamlDotNet or System.Text.Json.
Certainly! Below is an example demonstrating how you might create, modify, and use the Config class in a C# application:
csharp
using System;
using FishSpeechConfig;
class Program
{
static void Main()
{
// Create a new config instance with defaults
var config = new Config();
// Access some default values
Console.WriteLine("Project: " + config.Project);
Console.WriteLine("Max Length: " + config.MaxLength);
Console.WriteLine("Pretrained Checkpoint Path: " + config.PretrainedCkptPath);
Console.WriteLine("Trainer max steps: " + config.Trainer.MaxSteps);
Console.WriteLine("Model optimizer learning rate: " + config.Model.Optimizer.Lr);
// Modify some values
config.MaxLength = 2048;
config.Trainer.MaxSteps = 20000;
config.Data.BatchSize = 6;
config.Model.Optimizer.Lr = 5e-5;
// The Tokenizer model path depends on PretrainedCkptPath - manually update if PretrainedCkptPath changed
config.PretrainedCkptPath = "checkpoints/fish-speech-2.0";
config.Tokenizer.ModelPath = $"{config.PretrainedCkptPath}/tokenizer.tiktoken";
// Also need to update dependent objects manually if you want them in sync
config.TrainDataset.Tokenizer = config.Tokenizer;
config.ValDataset.Tokenizer = config.Tokenizer;
config.TrainDataset.MaxLength = config.MaxLength;
config.ValDataset.MaxLength = config.MaxLength;
config.Data.Tokenizer = config.Tokenizer;
config.Data.MaxLength = config.MaxLength;
config.Model.InnerModel.Path = config.PretrainedCkptPath;
config.Model.InnerModel.MaxLength = config.MaxLength;
// Display updated config info:
Console.WriteLine("\nUpdated Config:");
Console.WriteLine($"Max Length: {config.MaxLength}");
Console.WriteLine($"Trainer max steps: {config.Trainer.MaxSteps}");
Console.WriteLine($"Batch Size: {config.Data.BatchSize}");
Console.WriteLine($"Optimizer LR: {config.Model.Optimizer.Lr}");
Console.WriteLine($"Tokenizer model path: {config.Tokenizer.ModelPath}");
Console.WriteLine($"Inner Model path: {config.Model.InnerModel.Path}");
}
}
Explanation:
Instantiates the Config object with default values.
Reads and prints out some default property values.
Modifies a handful of properties to new values.
Demonstrates that changing a base property like PretrainedCkptPath requires manually updating related fields (Tokenizer.ModelPath, dataset tokenizer references, etc.) since this example class does not automatically propagate changes.
Prints the updated values to show the modifications.
Next steps / Improvements:
If you want automatic cascading of changes (e.g., updating PretrainedCkptPath automatically updates tokenizer paths etc.), you could implement property setters with custom logic or a method to refresh related dependent properties.
You can serialize/deserialize this config with e.g. YamlDotNet or System.Text.Json to save/load configs from files.
If you'd like, I can provide an example for saving/loading to/from YAML or JSON files!
Right, the class I provided is just an in-memory representation and does not include saving/loading functionality.
If you want to save (serialize) and load (deserialize) this config as a YAML file, you can use the popular YamlDotNet library for C#.
Example: Serialize and Save the Config to YAML, Then Load it Back
First, add YamlDotNet to your project:
bash
dotnet add package YamlDotNet
1. Sample code to serialize and save:
csharp
using System;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using FishSpeechConfig;
class Program
{
static void Main()
{
// Create and modify config as before
var config = new Config();
// Modify some values (optional)
config.BatchSize = 5; // example, not actually on root; fix if you want
// Create a YamlDotNet serializer with camel case naming convention to match YAML style
var serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
string yaml = serializer.Serialize(config);
Console.WriteLine("--- Serialized YAML ---");
Console.WriteLine(yaml);
// Save YAML to file
string filePath = "config.yaml";
File.WriteAllText(filePath, yaml);
Console.WriteLine($"Config saved to {filePath}");
}
}
2. Sample code to load and deserialize:
csharp
using System;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using FishSpeechConfig;
class Program
{
static void Main()
{
string filePath = "config.yaml";
if (!File.Exists(filePath))
{
Console.WriteLine("Config file does not exist! Please save one first.");
return;
}
string yamlContent = File.ReadAllText(filePath);
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
Config config = deserializer.Deserialize<Config>(yamlContent);
Console.WriteLine("Config loaded from YAML:");
Console.WriteLine($"Project: {config.Project}");
Console.WriteLine($"Trainer max steps: {config.Trainer.MaxSteps}");
}
}
Important:
Naming conventions: The CamelCaseNamingConvention is used to match your YAML snake_case keys (you may want to customize naming conventions or use attributes).
Property naming: To properly map between C# PascalCase and YAML snake_case, you might want to use serialization attributes or a custom naming convention to convert between them correctly; otherwise, your YAML keys will be maxLength, pretrainedCkptPath, etc.
Nullables and complex types: Make sure your classes can be properly serialized and deserialized. Public properties with get/set are essential.
Optional: Use YamlMember naming attributes for snake_case
If you want exact match for snake_case in the YAML keys, decorate your fields with [YamlMember(Alias = "snake_case_name")].
Example:
csharp
using YamlDotNet.Serialization;
public class TrainerConfig
{
[YamlMember(Alias = "accumulate_grad_batches")]
public int AccumulateGradBatches { get; set; } = 1;
[YamlMember(Alias = "gradient_clip_val")]
public float GradientClipVal { get; set; } = 1.0f;
// ... and so on for other properties
}
You would do this for all properties whose YAML key uses snake_case.
Would you like me to generate the YamlMember decorated version of the config classes to fully support saving/loading to your exact YAML layout?