Class NeuralProgramSynthesizer<T>
- Namespace
- AiDotNet.ProgramSynthesis.Engines
- Assembly
- AiDotNet.dll
Neural network-based program synthesizer that generates programs from specifications.
public class NeuralProgramSynthesizer<T> : NeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, IProgramSynthesizer<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>
Type Parameters
TThe numeric type used for calculations (e.g., double, float).
- Inheritance
-
NeuralProgramSynthesizer<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
NeuralProgramSynthesizer uses deep learning to generate programs from natural language descriptions, input-output examples, or formal specifications. It employs an encoder-decoder architecture similar to CodeT5 but optimized for program synthesis tasks.
For Beginners: This AI can write programs for you automatically!
Imagine describing what you want a program to do, or showing examples of inputs and outputs, and an AI writes the actual code. That's what this does!
You can provide:
- A description: "Write a function that sorts a list of numbers"
- Examples: Input [3,1,2] → Output [1,2,3]
- Or both!
The AI learns from training and generates working code that solves your problem. It's like having an AI programmer that can code based on your requirements!
Constructors
NeuralProgramSynthesizer(CodeSynthesisArchitecture<T>, ICodeModel<T>, ILossFunction<T>?, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, IProgramExecutionEngine?)
Initializes a new instance of the NeuralProgramSynthesizer<T> class.
public NeuralProgramSynthesizer(CodeSynthesisArchitecture<T> architecture, ICodeModel<T> codeModel, ILossFunction<T>? lossFunction = null, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, IProgramExecutionEngine? executionEngine = null)
Parameters
architectureCodeSynthesisArchitecture<T>The synthesis architecture configuration.
codeModelICodeModel<T>The underlying code model (CodeT5 recommended).
lossFunctionILossFunction<T>Optional loss function.
optimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optional optimizer.
executionEngineIProgramExecutionEngine
Remarks
Creates a new neural program synthesizer. Uses a code model (like CodeT5) as the backbone for understanding requirements and generating code.
For Beginners: This sets up the AI program writer.
You need to provide:
- Architecture: The blueprint for how it works
- Code model: The brain that understands and generates code (usually CodeT5)
- Optional: Loss function and optimizer for training
Once set up, you can ask it to write programs for you!
Properties
MaxProgramLength
Gets the maximum allowed length for synthesized programs.
public int MaxProgramLength { get; }
Property Value
Remarks
This limits the complexity and size of generated programs, measured in tokens or abstract syntax tree nodes.
For Beginners: This limits how long/complex the generated code can be.
Like a word limit on an essay, this prevents the AI from generating programs that are too large or complex. Helps ensure the code stays manageable.
SynthesisType
Gets the type of synthesis approach used by this synthesizer.
public SynthesisType SynthesisType { get; }
Property Value
Remarks
Different synthesis approaches have different strengths. Neural methods are creative, symbolic methods are precise, and hybrid methods combine both.
For Beginners: This tells you how the AI generates programs.
Different approaches are like different problem-solving strategies:
- Neural: Learns from examples (like learning by watching)
- Symbolic: Uses logic and rules (like following instructions)
- Genetic: Evolves solutions (like natural selection)
TargetLanguage
Gets the target programming language for synthesis.
public ProgramLanguage TargetLanguage { get; }
Property Value
Remarks
Specifies which programming language the synthesized programs will be written in.
For Beginners: This is the language the AI will write code in.
Just like you choose whether to write in English or Spanish, this specifies which programming language the generated code will use (Python, Java, etc.).
Methods
CreateNewInstance()
Creates a new instance of the same type as this neural network.
protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()
Returns
- IFullModel<T, Tensor<T>, Tensor<T>>
A new instance of the same neural network type.
Remarks
For Beginners: This creates a blank version of the same type of neural network.
It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.
DeserializeNetworkSpecificData(BinaryReader)
Deserializes network-specific data that was not covered by the general deserialization process.
protected override void DeserializeNetworkSpecificData(BinaryReader reader)
Parameters
readerBinaryReaderThe BinaryReader to read the data from.
Remarks
This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.
For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.
EvaluateProgram(Program<T>, ProgramInput<T>)
Evaluates how well a program satisfies the input specification.
public double EvaluateProgram(Program<T> program, ProgramInput<T> testCases)
Parameters
programProgram<T>The program to evaluate.
testCasesProgramInput<T>Test cases to evaluate the program against.
Returns
- double
A fitness score indicating how well the program meets requirements (0-1).
Remarks
Runs the program against test cases and calculates a fitness score based on how many tests pass and how well the outputs match expectations.
For Beginners: This grades how well the program works.
Tests the program and gives it a score (like a percentage grade):
- 1.0 = Perfect! Passes all tests
- 0.5 = Passes half the tests
- 0.0 = Doesn't work at all
The score helps us know if the program is good enough or needs improvement.
GetModelMetadata()
Gets the metadata for this neural network model.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
InitializeLayers()
Initializes the layers of the neural network based on the architecture.
protected override void InitializeLayers()
Remarks
For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.
Predict(Tensor<T>)
Makes a prediction using the neural network.
public override Tensor<T> Predict(Tensor<T> input)
Parameters
inputTensor<T>The input data to process.
Returns
- Tensor<T>
The network's prediction.
Remarks
For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).
RefineProgram(Program<T>, ProgramInput<T>)
Refines an existing program to better meet the specification.
public Program<T> RefineProgram(Program<T> program, ProgramInput<T> feedback)
Parameters
programProgram<T>The program to refine.
feedbackProgramInput<T>Feedback or test cases that failed.
Returns
- Program<T>
A refined version of the program.
Remarks
Takes an existing program and improves it based on feedback from failed tests or user corrections. Uses the neural network to generate a better version.
For Beginners: This improves a program based on feedback.
If the first version isn't quite right:
- Look at what went wrong (failed tests)
- Generate an improved version
- Keep the good parts, fix the problems
Like editing a draft based on reviewer comments to make it better.
SerializeNetworkSpecificData(BinaryWriter)
Serializes network-specific data that is not covered by the general serialization process.
protected override void SerializeNetworkSpecificData(BinaryWriter writer)
Parameters
writerBinaryWriterThe BinaryWriter to write the data to.
Remarks
This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.
For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.
SynthesizeProgram(ProgramInput<T>)
Synthesizes a program from the given input specification.
public Program<T> SynthesizeProgram(ProgramInput<T> input)
Parameters
inputProgramInput<T>The input specification containing requirements or examples.
Returns
- Program<T>
A synthesized program that meets the specification.
Remarks
This is the main synthesis method. It processes the input specification through the neural network and generates code that satisfies the requirements.
For Beginners: This is where the magic happens - it writes code for you!
You provide what you want (description, examples, constraints), and this method generates actual working code. The process:
- Understand your requirements
- Generate candidate code
- Validate the code
- Return the best solution
Like asking an AI chef for a recipe and getting step-by-step instructions!
Train(Tensor<T>, Tensor<T>)
Trains the neural network on a single input-output pair.
public override void Train(Tensor<T> input, Tensor<T> expectedOutput)
Parameters
inputTensor<T>The input data.
expectedOutputTensor<T>The expected output for the given input.
Remarks
This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.
For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)
The network then:
- Makes a prediction based on the input
- Compares its prediction to the expected output
- Calculates how wrong it was (the loss)
- Adjusts its internal values to do better next time
After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.
UpdateParameters(Vector<T>)
Updates the network's parameters with new values.
public override void UpdateParameters(Vector<T> parameters)
Parameters
parametersVector<T>The new parameter values to set.
Remarks
For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.
This is typically used by optimization algorithms that calculate better parameter values based on training data.
ValidateProgram(Program<T>)
Validates whether a synthesized program is correct and well-formed.
public bool ValidateProgram(Program<T> program)
Parameters
programProgram<T>The program to validate.
Returns
- bool
True if the program is valid, false otherwise.
Remarks
Checks if the program is syntactically correct and can potentially be executed. This includes parsing, syntax checking, and basic semantic validation.
For Beginners: This checks if the generated code will work.
Before using generated code, we check:
- Is the syntax correct? (no typos)
- Does it make logical sense?
- Will it compile/run?
Like proofreading an essay before submitting it.