diff --git a/.buildinfo b/.buildinfo
new file mode 100644
index 0000000..afc97b4
--- /dev/null
+++ b/.buildinfo
@@ -0,0 +1,4 @@
+# Sphinx build info version 1
+# This file records the configuration used when building these files. When it is not found, a full rebuild will be done.
+config: c5116bd8006bfc41e0314f4cbe68c127
+tags: 645f666f9bcd5a90fca523b33c5a78b7
diff --git a/.nojekyll b/.nojekyll
new file mode 100644
index 0000000..e69de29
diff --git a/_modules/index.html b/_modules/index.html
new file mode 100644
index 0000000..d0adc01
--- /dev/null
+++ b/_modules/index.html
@@ -0,0 +1,128 @@
+
+
+
+
+
+[docs]
+@dataclass
+classConv2DConfig:
+"""
+ Configuration for 2D Convolutional layer.
+
+ Parameters
+ ----------
+ activation : str
+ Activation function to use.
+ kernel_size : tuple
+ Size of the convolution kernels.
+ strides : tuple
+ Stride length of the convolution.
+ filters : int
+ Number of output filters in the convolution.
+ """
+ activation:str
+ kernel_size:tuple
+ strides:tuple
+ filters:int
+
+
+
+
+[docs]
+@dataclass
+classPooling2DConfig:
+"""
+ Configuration for 2D Pooling layer.
+
+ Parameters
+ ----------
+ pool_type : str
+ Type of pooling operation (e.g., 'max', 'average').
+ pool_size : tuple
+ Size of the pooling window.
+ strides : tuple
+ Stride length of the pooling operation.
+ """
+ pool_type:str
+ pool_size:tuple
+ strides:tuple
+
+
+
+
+[docs]
+@dataclass
+classDenseConfig:
+"""
+ Configuration for Dense (Fully Connected) layer.
+
+ Parameters
+ ----------
+ activation : str
+ Activation function to use.
+ units : int
+ Number of neurons in the dense layer.
+ """
+ activation:str
+ units:int
+
+
+
+
+[docs]
+@dataclass
+classRNNConfig:
+"""
+ Configuration for Recurrent Neural Network layer.
+
+ Parameters
+ ----------
+ units : int
+ Number of RNN units.
+ return_sequences : bool
+ Whether to return the last output or the full sequence.
+ go_backwards : bool
+ If True, process the input sequence backwards.
+ dropout : float
+ Fraction of the units to drop for the linear transformation of the inputs.
+ recurrent_dropout : float
+ Fraction of the units to drop for the linear transformation of the recurrent state.
+ rnn_type : str, optional
+ Type of RNN (e.g., 'simple', 'lstm', 'gru').
+ bidirectional : bool, optional
+ If True, create a bidirectional RNN.
+ """
+ units:int
+ return_sequences:bool
+ go_backwards:bool
+ dropout:float
+ recurrent_dropout:float
+ rnn_type:str=None
+ bidirectional:bool=False
+
+
+
+[docs]
+@dataclass
+classDropoutConfig:
+"""
+ Configuration for Dropout layer.
+
+ Parameters
+ ----------
+ rate : float
+ Fraction of the input units to drop.
+ """
+ rate:float
+
+
+
+
+[docs]
+@dataclass
+classReshapeConfig:
+"""
+ Configuration for Reshape layer.
+
+ Parameters
+ ----------
+ target_shape : tuple
+ Target shape of the output.
+ """
+ target_shape:tuple
+
+
+
+
+[docs]
+@dataclass
+classInputConfig:
+"""
+ Configuration for Input layer.
+
+ Parameters
+ ----------
+ batch_size : int
+ Size of the batches of data.
+ depth : int
+ Depth of the input (for 3D inputs).
+ height : int
+ Height of the input.
+ width : int
+ Width of the input.
+ channels : int
+ Number of channels in the input.
+ """
+ batch_size:int
+ depth:int
+ height:int
+ width:int
+ channels:int
+
+
+
+[docs]
+@dataclass
+classActivationConfig:
+"""
+ Configuration for Activation layer.
+
+ Parameters
+ ----------
+ activation : str
+ Activation function to use.
+ """
+ activation:str
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/core/factory.html b/_modules/vgslify/core/factory.html
new file mode 100644
index 0000000..ce5e2fe
--- /dev/null
+++ b/_modules/vgslify/core/factory.html
@@ -0,0 +1,926 @@
+
+
+
+
+
+
+
+ vgslify.core.factory — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+classLayerFactory(ABC):
+"""
+ Abstract base class for creating neural network layers from VGSL specifications.
+
+ This class defines the interface that must be implemented by concrete factories
+ for different frameworks (e.g., TensorFlow, PyTorch). It also provides common
+ methods for output shape calculations to be used by subclasses.
+
+ Parameters
+ ----------
+ input_shape : tuple of int, optional
+ The initial input shape for the model.
+ data_format : str, default 'channels_last'
+ The data format for the input tensor. Either 'channels_last' or 'channels_first'.
+
+ Attributes
+ ----------
+ layers : list
+ A list to store the created layers.
+ data_format : str
+ The data format for the input tensor.
+ shape : tuple of int
+ The current shape of the output tensor.
+ _input_shape : tuple of int
+ The initial input shape for the model.
+
+ Notes
+ -----
+ This is an abstract base class. Use a concrete implementation like
+ `TensorFlowLayerFactory` or `PyTorchLayerFactory` in your code.
+
+ This class uses a naming convention where public methods for creating layers
+ (e.g., conv2d) have corresponding private methods with an underscore prefix
+ (e.g., _conv2d) that handle the actual layer creation.
+
+ Examples
+ --------
+ >>> # Assuming we have a TensorFlowLayerFactory implementation
+ >>> factory = TensorFlowLayerFactory(input_shape=(224, 224, 3))
+ >>> factory.conv2d('Cr3,3,32')
+ >>> factory.pooling2d('Mp2,2,2,2')
+ >>> factory.flatten('Flt')
+ >>> factory.dense('Fs128')
+ >>> model = factory.build('my_model')
+ """
+
+ def__init__(self,input_shape:Tuple[int,...]=None,data_format:str='channels_last'):
+ self.layers=[]
+ self.data_format=data_format
+
+ # Make sure the input shape is valid
+ ifinput_shapeisnotNoneandnotall(isinstance(dim,int)fordimininput_shape):
+ raiseValueError("Input shape must be a tuple of integers.")
+
+ # Set the input shape if provided
+ self.shape=input_shape
+ self._input_shape=input_shape
+
+
+[docs]
+ @abstractmethod
+ defbuild(self,name:str):
+"""
+ Abstract method to build the final model using the created layers.
+
+ Parameters
+ ----------
+ name : str
+ The name of the model.
+
+ Returns
+ -------
+ Any
+ The final built model.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(28, 28, 1))
+ >>> factory.conv2d('Cr3,3,32')
+ >>> factory.flatten('Flt')
+ >>> factory.dense('Fs10')
+ >>> model = factory.build('my_model')
+ """
+ pass
+
+
+ # Layer creation methods
+
+[docs]
+ definput(self,spec:str):
+"""
+ Create an Input layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the Input layer.
+
+ Returns
+ -------
+ Any
+ The created Input layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory()
+ >>> factory.input('1,28,28,1')
+ """
+ config=parse_input_spec(spec)
+
+ # Adjust input shape based on the parsed dimensions
+ ifconfig.channelsisnotNoneandconfig.depthisnotNone:
+ # 4D input: shape = (depth, height, width, channels)
+ input_shape=(config.depth,config.height,
+ config.width,config.channels)
+ elifconfig.channelsisnotNone:
+ # 3D input: shape = (height, width, channels)
+ input_shape=(config.height,config.width,config.channels)
+ elifconfig.heightisnotNone:
+ # 2D input: shape = (height, width)
+ input_shape=(config.height,config.width)
+ else:
+ # 1D input: shape = (width,)
+ input_shape=(config.width,)
+
+ # Adjust for data format
+ ifself.data_format=='channels_first':
+ iflen(input_shape)==3:
+ input_shape=(input_shape[2],input_shape[0],input_shape[1])
+ eliflen(input_shape)==4:
+ input_shape=(input_shape[3],input_shape[0],
+ input_shape[1],input_shape[2])
+
+ self.shape=input_shape
+ self._input_shape=input_shape
+
+ input_layer=self._input(config,input_shape)
+ ifinput_layerisnotNone:
+ # Some backends may not return the layer
+ self._add_layer(input_layer)
+
+ returninput_layer
+
+
+
+[docs]
+ defconv2d(self,spec:str):
+"""
+ Create a 2D Convolutional layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the Conv2D layer.
+
+ Returns
+ -------
+ Any
+ The created Conv2D layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(28, 28, 1))
+ >>> factory.conv2d('Cr3,3,32')
+ """
+ config=parse_conv2d_spec(spec)
+ self._validate_input_shape()
+
+ conv_layer=self._conv2d(config)
+ self._add_layer(conv_layer)
+
+ # Add activation if needed
+ ifconfig.activation:
+ activation_layer=self._activation(config.activation)
+ self._add_layer(activation_layer)
+
+ # Update shape
+ new_shape=self._compute_conv_output_shape(self.shape,config)
+ self._update_shape(new_shape)
+
+ returnconv_layer
+
+
+
+[docs]
+ defpooling2d(self,spec:str):
+"""
+ Create a 2D Pooling layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the Pooling2D layer.
+
+ Returns
+ -------
+ Any
+ The created Pooling2D layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(28, 28, 32))
+ >>> factory.pooling2d('Mp2,2,2,2')
+ """
+ config=parse_pooling2d_spec(spec)
+ self._validate_input_shape()
+
+ pool_layer=self._pooling2d(config)
+ self._add_layer(pool_layer)
+
+ # Update shape
+ new_shape=self._compute_pool_output_shape(self.shape,config)
+ self._update_shape(new_shape)
+
+ returnpool_layer
+
+
+
+[docs]
+ defdense(self,spec:str):
+"""
+ Create a Dense (Fully Connected) layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the Dense layer.
+
+ Returns
+ -------
+ Any
+ The created Dense layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(7*7*32,))
+ >>> factory.dense('Fs128')
+ """
+ config=parse_dense_spec(spec)
+ self._validate_input_shape()
+
+ dense_layer=self._dense(config)
+ self._add_layer(dense_layer)
+
+ # Add activation if needed
+ ifconfig.activation:
+ activation_layer=self._activation(config.activation)
+ self._add_layer(activation_layer)
+
+ # Update shape
+ self._update_shape((config.units,))
+
+ returndense_layer
+
+
+
+[docs]
+ defrnn(self,spec:str):
+"""
+ Create an RNN layer (LSTM or GRU), either unidirectional or bidirectional, based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the RNN layer.
+
+ Returns
+ -------
+ Any
+ The created RNN layer (either unidirectional or bidirectional).
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(28, 28))
+ >>> factory.rnn('Ls128') # Unidirectional LSTM
+ >>> factory.rnn('Bl128') # Bidirectional LSTM
+ """
+ config=parse_rnn_spec(spec)
+ self._validate_input_shape()
+
+ rnn_layer=self._rnn(config)
+ self._add_layer(rnn_layer)
+
+ # Update shape
+ ifconfig.return_sequences:
+ ifconfig.bidirectional:
+ self._update_shape((self.shape[0],config.units*2))
+ else:
+ self._update_shape((self.shape[0],config.units))
+ else:
+ ifconfig.bidirectional:
+ self._update_shape((config.units*2,))
+ else:
+ self._update_shape((config.units,))
+
+ returnrnn_layer
+
+
+
+[docs]
+ defbatchnorm(self,spec:str):
+"""
+ Create a BatchNormalization layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the BatchNormalization layer.
+
+ Returns
+ -------
+ Any
+ The created BatchNormalization layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(28, 28, 32))
+ >>> factory.batchnorm('Bn')
+ """
+ ifspec!='Bn':
+ raiseValueError(
+ f"BatchNormalization layer spec '{spec}' is incorrect. Expected 'Bn'.")
+
+ self._validate_input_shape()
+
+ batchnorm_layer=self._batchnorm()
+ self._add_layer(batchnorm_layer)
+
+ # Shape remains the same
+ returnbatchnorm_layer
+
+
+
+[docs]
+ defdropout(self,spec:str):
+"""
+ Create a Dropout layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the Dropout layer.
+
+ Returns
+ -------
+ Any
+ The created Dropout layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(128,))
+ >>> factory.dropout('D50')
+ """
+ config=parse_dropout_spec(spec)
+ layer=self._dropout(config)
+ self.layers.append(layer)
+ # Shape remains the same
+ returnlayer
+
+
+
+[docs]
+ defactivation(self,spec:str):
+"""
+ Create an Activation layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the Activation layer.
+
+ Returns
+ -------
+ Any
+ The created Activation layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(128,))
+ >>> factory.activation('Ar')
+ """
+ activation_function=parse_activation_spec(spec)
+ layer=self._activation(activation_function)
+ self.layers.append(layer)
+ # Shape remains the same
+ returnlayer
+
+
+
+[docs]
+ defreshape(self,spec:str):
+"""
+ Create a Reshape layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification string for the Reshape layer. Can be:
+ - 'Rc(2|3)': Collapse spatial dimensions (height, width, and channels).
+ - 'R<x>,<y>,<z>': Reshape to the specified target shape.
+
+ Returns
+ -------
+ Any
+ The created Reshape layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(28, 28, 1))
+ >>> factory.reshape('Rc3')
+ """
+ ifself.shapeisNone:
+ raiseValueError("Input shape must be set before adding layers.")
+
+ # Handle 'Rc' (collapse spatial dimensions) specification
+ ifspec.startswith('Rc'):
+ ifspec=='Rc2':
+ # Flatten to (batch_size, -1)
+ layer=self._flatten()
+ self.layers.append(layer)
+ self.shape=(int(self._compute_flatten_shape(self.shape)),)
+ returnlayer
+
+ elifspec=='Rc3':
+ # Reshape to (batch_size, seq_length, features)
+ iflen(self.shape)!=3:
+ raiseValueError(
+ f"Expected a 3D input shape for 'Rc3', got {self.shape}")
+
+ ifself.data_format=='channels_first':
+ C,H,W=self.shape
+ else:# channels_last
+ H,W,C=self.shape
+
+ # Handle variable height
+ ifHisNone:
+ seq_length=None
+ else:
+ seq_length=H*WifWisnotNoneelseNone
+
+ features=C
+ config=ReshapeConfig(target_shape=(seq_length,features))
+ layer=self._reshape(config)
+ self.layers.append(layer)
+ self.shape=(seq_length,features)
+ returnlayer
+
+ else:
+ raiseValueError(f"Unsupported Rc variant: {spec}")
+
+ # Handle regular reshape (e.g., 'R64,64,3')
+ config=parse_reshape_spec(spec)
+ layer=self._reshape(config)
+ self.layers.append(layer)
+ self.shape=config.target_shape
+ returnlayer
+
+
+
+[docs]
+ defflatten(self,spec:str):
+"""
+ Create a Flatten layer based on the VGSL specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for the Flatten layer.
+
+ Returns
+ -------
+ Any
+ The created Flatten layer.
+
+ Examples
+ --------
+ >>> # Using a hypothetical concrete implementation
+ >>> factory = SomeConcreteLayerFactory(input_shape=(7, 7, 64))
+ >>> factory.flatten('Flt')
+ """
+ ifspec!="Flt":
+ raiseValueError(
+ f"Flatten layer spec '{spec}' is incorrect. Expected 'Flt'.")
+
+ layer=self._flatten()
+ self.layers.append(layer)
+ # Update shape
+ self.shape=(self._compute_flatten_shape(self.shape),)
+ returnlayer
+
+
+ # Abstract methods
+ @abstractmethod
+ def_input(self,config:InputConfig,input_shape:Tuple[int,...]):
+"""
+ Abstract method to create an Input layer.
+
+ Parameters
+ ----------
+ config : InputConfig
+ The configuration object returned by parse_input_spec.
+ input_shape : tuple of int
+ The input shape.
+
+ Returns
+ -------
+ Any
+ The created Input layer.
+ """
+ pass
+
+ @abstractmethod
+ def_conv2d(self,config:Conv2DConfig):
+"""
+ Abstract method to create a Conv2D layer.
+
+ Parameters
+ ----------
+ config : Conv2DConfig
+ The configuration object returned by parse_conv2d_spec.
+
+ Returns
+ -------
+ Any
+ The created Conv2D layer.
+ """
+ pass
+
+ @abstractmethod
+ def_pooling2d(self,config:Pooling2DConfig):
+"""
+ Abstract method to create a Pooling2D layer.
+
+ Parameters
+ ----------
+ config : Pooling2DConfig
+ The configuration object returned by parse_pooling2d_spec.
+
+ Returns
+ -------
+ Any
+ The created Pooling2D layer.
+ """
+ pass
+
+ @abstractmethod
+ def_dense(self,config:DenseConfig):
+"""
+ Abstract method to create a Dense (Fully Connected) layer.
+
+ Parameters
+ ----------
+ config : DenseConfig
+ The configuration object returned by parse_dense_spec.
+
+ Returns
+ -------
+ Any
+ The created Dense layer.
+ """
+ pass
+
+ @abstractmethod
+ def_rnn(self,config:RNNConfig):
+"""
+ Abstract method to create an RNN layer (LSTM or GRU).
+
+ Parameters
+ ----------
+ config : RNNConfig
+ The configuration object returned by parse_rnn_spec.
+
+ Returns
+ -------
+ Any
+ The created RNN layer.
+ """
+ pass
+
+ @abstractmethod
+ def_batchnorm(self):
+"""
+ Abstract method to create a BatchNormalization layer.
+
+ Returns
+ -------
+ Any
+ The created BatchNormalization layer.
+ """
+ pass
+
+ @abstractmethod
+ def_dropout(self,config:DropoutConfig):
+"""
+ Abstract method to create a Dropout layer.
+
+ Parameters
+ ----------
+ config : DropoutConfig
+ The configuration object returned by parse_dropout_spec.
+
+ Returns
+ -------
+ Any
+ The created Dropout layer.
+ """
+ pass
+
+ @abstractmethod
+ def_activation(self,activation_function:str):
+"""
+ Abstract method to create an Activation layer.
+
+ Parameters
+ ----------
+ activation_function : str
+ Name of the activation function.
+
+ Returns
+ -------
+ Any
+ The created Activation layer.
+ """
+ pass
+
+ @abstractmethod
+ def_reshape(self,config:ReshapeConfig):
+"""
+ Abstract method to create a Reshape layer.
+
+ Parameters
+ ----------
+ config : ReshapeConfig
+ The configuration object returned by parse_reshape_spec.
+
+ Returns
+ -------
+ Any
+ The created Reshape layer.
+ """
+ pass
+
+ @abstractmethod
+ def_flatten(self):
+"""
+ Abstract method to create a Flatten layer.
+
+ Returns
+ -------
+ Any
+ The created Flatten layer.
+ """
+ pass
+
+ # Helper methods
+ def_compute_conv_output_shape(self,
+ input_shape:Tuple[int,...],
+ config:Conv2DConfig)->Tuple[int,...]:
+"""
+ Computes the output shape of a convolutional layer.
+
+ Parameters
+ ----------
+ input_shape : tuple
+ The input shape.
+ config : Conv2DConfig
+ The configuration object returned by parse_conv2d_spec.
+
+ Returns
+ -------
+ tuple
+ The output shape after the convolution.
+ """
+ ifself.data_format=='channels_last':
+ H_in,W_in,C_in=input_shape
+ else:
+ C_in,H_in,W_in=input_shape
+
+ # Compute output dimensions based on padding and strides
+ # Adjust calculations based on the backend's handling of padding
+
+ # Example computation for 'same' padding
+ H_out=math.ceil(H_in/config.strides[0]) \
+ ifH_inisnotNoneelseNone
+ W_out=math.ceil(W_in/config.strides[1]) \
+ ifW_inisnotNoneelseNone
+ C_out=config.filters
+
+ ifself.data_format=='channels_last':
+ return(H_out,W_out,C_out)
+ else:
+ return(C_out,H_out,W_out)
+
+ def_compute_pool_output_shape(self,
+ input_shape:Tuple[int,...],
+ config:Pooling2DConfig)->Tuple[int,...]:
+"""
+ Computes the output shape of a pooling layer.
+
+ Parameters
+ ----------
+ input_shape : tuple
+ The input shape.
+ config : Pooling2DConfig
+ The configuration object returned by parse_pooling2d_spec.
+
+ Returns
+ -------
+ tuple
+ The output shape after pooling.
+ """
+ ifself.data_format=='channels_last':
+ H_in,W_in,C_in=input_shape
+ else:
+ C_in,H_in,W_in=input_shape
+
+ # Compute output dimensions based on pooling size and strides
+ H_out=(H_in+config.strides[0]-1)//config.strides[0] \
+ ifH_inisnotNoneelseNone
+ W_out=(W_in+config.strides[1]-1)//config.strides[1]if \
+ W_inisnotNoneelseNone
+
+ ifself.data_format=='channels_last':
+ return(H_out,W_out,C_in)
+ else:
+ return(C_in,H_out,W_out)
+
+ def_compute_flatten_shape(self,shape:Tuple[int,...])->int:
+"""
+ Computes the shape after flattening the input.
+
+ Parameters
+ ----------
+ shape : tuple
+ The input shape.
+
+ Returns
+ -------
+ int
+ The product of all dimensions.
+ """
+ fromfunctoolsimportreduce
+ fromoperatorimportmul
+ returnreduce(mul,shape)
+
+ def_validate_input_shape(self):
+"""
+ Validates that the input shape has been set before adding layers.
+
+ Raises
+ ------
+ ValueError
+ If the input shape has not been set.
+ """
+ ifself.shapeisNone:
+ raiseValueError("Input shape must be set before adding layers.")
+
+ def_add_layer(self,layer:Any):
+"""
+ Adds a layer to the list of layers.
+
+ Parameters
+ ----------
+ layer : Any
+ The layer to be added.
+ """
+ self.layers.append(layer)
+
+ def_update_shape(self,new_shape:Tuple[int,...]):
+"""
+ Updates the current shape of the output tensor.
+
+ Parameters
+ ----------
+ new_shape : tuple of int
+ The new shape to set.
+ """
+ self.shape=new_shape
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/core/parser.html b/_modules/vgslify/core/parser.html
new file mode 100644
index 0000000..17635cf
--- /dev/null
+++ b/_modules/vgslify/core/parser.html
@@ -0,0 +1,606 @@
+
+
+
+
+
+
+
+ vgslify.core.parser — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+defparse_spec(model_spec:str)->list:
+"""
+ Parse the full model spec string into a list of individual layer specs.
+
+ Parameters
+ ----------
+ model_spec : str
+ The VGSL specification string defining the model architecture.
+
+ Returns
+ -------
+ list
+ A list of layer specification strings.
+ """
+ returnmodel_spec.split()
+
+
+
+
+[docs]
+defparse_conv2d_spec(spec:str)->Conv2DConfig:
+"""
+ Parses a VGSL specification string for a Conv2D layer and returns the parsed configuration.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the convolutional layer. Expected format:
+ `C(s|t|r|l|m)<x>,<y>,[<s_x>,<s_y>,]<d>`
+ - (s|t|r|l|m): Activation type.
+ - <x>,<y>: Kernel size.
+ - <s_x>,<s_y>: Optional strides (defaults to (1, 1) if not provided).
+ - <d>: Number of filters (depth).
+
+ Returns
+ -------
+ Conv2DConfig
+ Parsed configuration for the Conv2D layer.
+
+ Raises
+ ------
+ ValueError:
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> from vgslify.core.parser import parse_conv2d_spec
+ >>> config = parse_conv2d_spec("Cr3,3,64")
+ >>> print(config)
+ Conv2DConfig(activation='relu', kernel_size=(3, 3), strides=(1, 1), filters=64)
+ """
+
+ # Extract convolutional parameters
+ conv_filter_params=[int(match)formatchinre.findall(r'\d+',spec)]
+
+ # Check if the layer format is as expected
+ iflen(conv_filter_params)<3:
+ raiseValueError(f"Conv layer {spec} has too few parameters. "
+ "Expected format: C(s|t|r|l|m)<x>,<y>,<d> or "
+ "C(s|t|r|l|m)<x>,<y>,<s_x>,<s_y>,<d>")
+ iflen(conv_filter_params)>5:
+ raiseValueError(f"Conv layer {spec} has too many parameters. "
+ "Expected format: C(s|t|r|l|m)<x>,<y>,<d> or "
+ "C(s|t|r|l|m)<x>,<y>,<s_x>,<s_y>,<d>")
+
+ # Extract activation function
+ try:
+ activation=get_activation_function(spec[1])
+ exceptValueError:
+ activation=None# Fall back to default activation
+
+ # Check parameter length and assign kernel size, strides, and filters
+ iflen(conv_filter_params)==3:
+ x,y,d=conv_filter_params
+ strides=(1,1)# Default stride
+ eliflen(conv_filter_params)==5:
+ x,y,s_x,s_y,d=conv_filter_params
+ strides=(s_x,s_y)
+ else:
+ raiseValueError(f"Invalid number of parameters in {spec}")
+
+ kernel_size=(y,x)
+
+ # Return the parsed configuration
+ returnConv2DConfig(
+ activation=activation,
+ kernel_size=kernel_size,
+ strides=strides,
+ filters=d
+ )
+
+
+
+
+[docs]
+defparse_pooling2d_spec(spec:str)->Pooling2DConfig:
+"""
+ Parses a VGSL specification string for a Pooling2D layer and returns the parsed configuration.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the pooling layer. Expected format:
+ `Mp<x>,<y>[,<s_x>,<s_y>]` or `Ap<x>,<y>[,<s_x>,<s_y>]`
+ - <x>,<y>: Pool size.
+ - <s_x>,<s_y>: Strides. If not specified, defaults to pool size.
+
+ Returns
+ -------
+ Pooling2DConfig
+ Parsed configuration for the Pooling2D layer.
+
+ Raises
+ ------
+ ValueError:
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> config = parse_pooling2d_spec("Mp2,2")
+ >>> print(config)
+ Pooling2DConfig(pool_size=(2, 2), strides=(2, 2))
+ >>> config = parse_pooling2d_spec("Mp2,2,1,1")
+ >>> print(config)
+ Pooling2DConfig(pool_size=(2, 2), strides=(1, 1))
+ """
+
+ # Extract pooling type
+ pool_type=spec[:2]
+ ifpool_typenotin['Mp','Ap']:
+ raiseValueError(f"Invalid pooling type '{pool_type}' in {spec}. "
+ "Expected 'Mp' for MaxPooling or 'Ap' for AveragePooling.")
+
+ pool_type='max'ifpool_type=='Mp'else'avg'
+
+ # Extract pooling and stride parameters
+ pool_stride_params=[int(match)formatchinre.findall(r'-?\d+',spec)]
+
+ # Check if the parameters are as expected
+ iflen(pool_stride_params)notin[2,4]:
+ raiseValueError(f"Pooling layer {spec} does not have the expected number of parameters. "
+ "Expected format: <p><x>,<y>[,<stride_x>,<stride_y>]")
+
+ pool_x,pool_y=pool_stride_params[:2]
+
+ # If strides are not specified, set them equal to the pool size
+ iflen(pool_stride_params)==2:
+ stride_x,stride_y=pool_x,pool_y
+ else:
+ stride_x,stride_y=pool_stride_params[2:]
+
+ # Check if pool and stride values are valid
+ ifpool_x<=0orpool_y<=0orstride_x<=0orstride_y<=0:
+ raiseValueError(f"Invalid values for pooling or stride in {spec}. "
+ "All values should be positive integers.")
+
+ returnPooling2DConfig(pool_type=pool_type,
+ pool_size=(pool_x,pool_y),
+ strides=(stride_x,stride_y))
+
+
+
+
+[docs]
+defparse_dense_spec(spec:str)->DenseConfig:
+"""
+ Parses a VGSL specification string for a Dense layer and returns the parsed configuration.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the dense layer. Expected format: `F(s|t|r|l|m)<d>`
+ - `(s|t|r|l|m)`: Non-linearity type. One of sigmoid, tanh, relu,
+ linear, or softmax.
+ - `<d>`: Number of outputs (units).
+
+ Returns
+ -------
+ DenseConfig
+ Parsed configuration for the Dense layer.
+
+ Raises
+ ------
+ ValueError
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> config = parse_dense_spec("Fr64")
+ >>> print(config)
+ DenseConfig(activation='relu', units=64)
+ """
+
+ # Ensure the layer string format is as expected
+ ifnotre.match(r'^F[a-z]-?\d+$',spec):
+ raiseValueError(
+ f"Dense layer {spec} is of unexpected format. Expected format: F(s|t|r|l|m)<d>."
+ )
+
+ # Extract the activation function
+ try:
+ activation=get_activation_function(spec[1])
+ exceptValueErrorase:
+ raiseValueError(
+ f"Invalid activation function '{spec[1]}' for Dense layer {spec}. "
+ "Expected one of 's', 't', 'r', 'l', or 'm'.")frome
+
+ # Extract the number of neurons (units)
+ units=int(spec[2:])
+ ifunits<=0:
+ raiseValueError(
+ f"Invalid number of neurons {units} for Dense layer {spec}.")
+
+ # Return the parsed configuration
+ returnDenseConfig(
+ activation=activation,
+ units=units
+ )
+
+
+
+
+[docs]
+defparse_rnn_spec(spec:str)->RNNConfig:
+"""
+ Parses a VGSL specification string for an RNN layer (LSTM, GRU, Bidirectional)
+ and returns the parsed configuration.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the RNN layer. Expected format:
+ For LSTM/GRU: `(L|G)(f|r)[s]<n>[,D<rate>,Rd<rate>]`
+ For Bidirectional: `B(g|l)<n>[,D<rate>,Rd<rate>]`
+
+ Returns
+ -------
+ RNNConfig
+ Parsed configuration for the RNN layer.
+
+ Raises
+ ------
+ ValueError
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> config = parse_rnn_spec("Lf64,D50,Rd25")
+ >>> print(config)
+ RNNConfig(units=64, return_sequences=True, go_backwards=False, dropout=0.5,
+ recurrent_dropout=0.25)
+ """
+
+ match=re.match(
+ r'([LGB])([frgl])(s?)(-?\d+),?(D-?\d+)?,?(Rd-?\d+)?$',spec)
+ ifnotmatch:
+ raiseValueError(
+ f"RNN layer {spec} is of unexpected format. Expected format: "
+ "L(f|r)[s]<n>[,D<rate>,Rd<rate>], G(f|r)[s]<n>[,D<rate>,Rd<rate>], "
+ "or B(g|l)<n>[,D<rate>,Rd<rate>]."
+ )
+
+ layer_type,rnn_type,summarize,units,dropout,recurrent_dropout=match.groups()
+
+ units=int(units)
+ dropout=0ifdropoutisNoneelseint(dropout.replace('D',""))/100
+ recurrent_dropout=0ifrecurrent_dropoutisNoneelseint(
+ recurrent_dropout.replace("Rd",""))/100
+
+ # Validation
+ ifunits<=0:
+ raiseValueError(
+ f"Invalid number of units {units} for RNN layer {spec}.")
+ ifdropout<0ordropout>1:
+ raiseValueError("Dropout rate must be between 0 and 1.")
+ ifrecurrent_dropout<0orrecurrent_dropout>1:
+ raiseValueError("Recurrent dropout rate must be between 0 and 1.")
+
+ # Return RNNConfig with parsed parameters
+ returnRNNConfig(
+ units=units,
+ return_sequences=bool(summarize)iflayer_type=='L'elseTrue,
+ go_backwards=rnn_type=='r',
+ dropout=dropout,
+ recurrent_dropout=recurrent_dropout,
+ rnn_type=rnn_type,
+ bidirectional=layer_type=='B'
+ )
+
+
+
+
+[docs]
+defparse_dropout_spec(spec:str)->DropoutConfig:
+"""
+ Parses a VGSL specification string for a Dropout layer and returns the parsed configuration.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the Dropout layer. Expected format:
+ `D<rate>` where <rate> is the dropout percentage (0-100).
+
+ Returns
+ -------
+ DropoutConfig
+ Parsed configuration for the Dropout layer.
+
+ Raises
+ ------
+ ValueError
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> config = parse_dropout_spec("D50")
+ >>> print(config)
+ DropoutConfig(rate=0.5)
+ """
+
+ match=re.match(r'D(-?\d+)$',spec)
+ ifnotmatch:
+ raiseValueError(
+ f"Dropout layer {spec} is of unexpected format. Expected format: D<rate>."
+ )
+
+ dropout_rate=int(match.group(1))
+
+ ifdropout_rate<0ordropout_rate>100:
+ raiseValueError("Dropout rate must be in the range [0, 100].")
+
+ returnDropoutConfig(rate=dropout_rate/100)
+
+
+
+
+[docs]
+defparse_activation_spec(spec:str)->str:
+"""
+ Parses a VGSL specification string for an Activation layer and returns the activation function.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the Activation layer. Expected format: `A(s|t|r|l|m)`
+ - `s`: softmax
+ - `t`: tanh
+ - `r`: relu
+ - `l`: linear
+ - `m`: sigmoid
+
+ Returns
+ -------
+ str
+ The activation function name.
+
+ Raises
+ ------
+ ValueError
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> activation = parse_activation_spec("Ar")
+ >>> print(activation)
+ 'relu'
+ """
+
+ match=re.match(r'A([strlm])$',spec)
+ ifnotmatch:
+ raiseValueError(
+ f"Activation layer spec '{spec}' is incorrect. Expected format: A(s|t|r|l|m).")
+
+ returnget_activation_function(match.group(1))
+
+
+
+
+[docs]
+defparse_reshape_spec(spec:str)->ReshapeConfig:
+"""
+ Parses a VGSL specification string for a Reshape layer and returns the target shape.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the Reshape layer. Expected format: `R<x>,<y>,<z>`
+
+ Returns
+ -------
+ ReshapeConfig
+ Parsed configuration for the Reshape layer.
+
+ Raises
+ ------
+ ValueError
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> config = parse_reshape_spec("R64,64,3")
+ >>> print(config)
+ ReshapeConfig(target_shape=(64, 64, 3))
+ """
+
+ match=re.match(r'R(-?\d+),(-?\d+)(?:,(-?\d+))?$',spec)
+ ifnotmatch:
+ raiseValueError(
+ f"Reshape layer spec '{spec}' is incorrect. Expected format: R<x>,<y>[,<z>].")
+
+ target_shape=tuple(int(x)forxinmatch.groups()ifx)
+ returnReshapeConfig(target_shape=target_shape)
+
+
+
+
+[docs]
+defparse_input_spec(spec:str)->InputConfig:
+"""
+ Parses a VGSL specification string for an Input layer and returns the parsed configuration.
+
+ Parameters
+ ----------
+ spec : str
+ VGSL specification for the Input layer. Supported format:
+ `<batch_size>,<depth>,<height>,<width>,<channels>` for 4D inputs,
+ `<batch_size>,<height>,<width>,<channels>` for 3D inputs,
+ `<batch_size>,<height>,<width>` for 2D inputs,
+ `<batch_size>,<width>` for 1D inputs.
+
+ Returns
+ -------
+ InputConfig
+ Parsed configuration for the Input layer.
+
+ Raises
+ ------
+ ValueError
+ If the provided VGSL spec string does not match the expected format.
+
+ Examples
+ --------
+ >>> config = parse_input_spec("None,224,224,3")
+ >>> print(config)
+ InputConfig(batch_size=None, width=224, depth=None, height=224, channels=3)
+ """
+ try:
+ dims=spec.split(",")
+ iflen(dims)==5:
+ batch,depth,height,width,channels=dims
+ eliflen(dims)==4:
+ batch,height,width,channels=dims
+ depth=None
+ eliflen(dims)==3:
+ batch,height,width=dims
+ depth,channels=None,None
+ eliflen(dims)==2:
+ batch,width=dims
+ height,depth,channels=None,None,None
+ else:
+ raiseValueError(f"Invalid input spec: {spec}")
+
+ returnInputConfig(
+ batch_size=Noneifbatch=="None"elseint(batch),
+ width=Noneifwidth=="None"elseint(width),
+ depth=Noneifdepth=="None"elseint(depth)ifdepthelseNone,
+ height=Noneifheight=="None"elseint(
+ height)ifheightelseNone,
+ channels=Noneifchannels=="None"elseint(
+ channels)ifchannelselseNone
+ )
+ exceptValueErrorase:
+ raiseValueError(
+ f"Invalid input string format '{spec}'. Expected valid VGSL format.")frome
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/core/utils.html b/_modules/vgslify/core/utils.html
new file mode 100644
index 0000000..c2d96e6
--- /dev/null
+++ b/_modules/vgslify/core/utils.html
@@ -0,0 +1,158 @@
+
+
+
+
+
+
+
+ vgslify.core.utils — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+defget_activation_function(activation_char:str)->str:
+"""
+ Maps a VGSL activation character to the corresponding Keras activation function.
+
+ Parameters
+ ----------
+ activation_char : str
+ The character representing the activation function in the VGSL spec.
+
+ Returns
+ -------
+ str
+ The name of the Keras activation function.
+
+ Raises
+ ------
+ ValueError
+ If the provided activation character is not recognized.
+
+ Examples
+ --------
+ >>> activation = get_activation_function('r')
+ >>> print(activation)
+ 'relu'
+ """
+ activation_map={
+ 's':'softmax',
+ 't':'tanh',
+ 'r':'relu',
+ 'l':'linear',
+ 'm':'sigmoid'
+ }
+
+ ifactivation_charnotinactivation_map:
+ raiseValueError(f"Invalid activation character '{activation_char}'.")
+
+ returnactivation_map[activation_char]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/generator.html b/_modules/vgslify/generator.html
new file mode 100644
index 0000000..547942d
--- /dev/null
+++ b/_modules/vgslify/generator.html
@@ -0,0 +1,380 @@
+
+
+
+
+
+
+
+ vgslify.generator — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+classVGSLModelGenerator:
+"""
+ VGSLModelGenerator constructs a neural network model based on a VGSL (Variable-size Graph
+ Specification Language) specification string. This class supports dynamic model generation
+ for different backends, with current support for TensorFlow and PyTorch.
+
+ The generator takes a VGSL specification string that defines the architecture of the neural
+ network, including the input layer, convolutional layers, pooling layers, RNN layers, dense
+ layers, and more. The class parses this string, constructs the layers in sequence, and builds
+ the final model.
+ """
+
+ def__init__(self,backend:str="auto")->None:
+"""
+ Initialize the VGSLModelGenerator with the backend.
+
+ Parameters
+ ----------
+ backend : str, optional
+ The backend to use for building the model. Can be "tensorflow", "torch", or "auto".
+ Default is "auto", which will attempt to automatically detect the available backend.
+ model_name : str, optional
+ The name of the model, by default "VGSL_Model"
+ """
+ self.backend=self._detect_backend(backend)
+ self.layer_factory_class,self.layer_constructors=self._initialize_backend_and_factory(
+ self.backend)
+ self.layer_factory=self.layer_factory_class()
+
+
+[docs]
+ defgenerate_model(self,model_spec:str,model_name:str="VGSL_Model")->Any:
+"""
+ Build the model based on the VGSL spec string.
+
+ This method parses the VGSL specification string, creates each layer
+ using the layer factory, and constructs the model sequentially.
+
+ Parameters
+ ----------
+ model_spec : str
+ The VGSL specification string defining the model architecture.
+
+ Returns
+ -------
+ Any
+ The built model using the specified backend.
+ """
+ returnself._process_layers(model_spec,return_history=False,model_name=model_name)
+
+
+
+[docs]
+ defgenerate_history(self,model_spec:str)->List[Any]:
+"""
+ Generate the history of layer specifications without building the full model.
+
+ This method parses the VGSL specification string, constructs each layer using
+ the layer factory, and stores them in a list, but does not chain them or connect
+ input/output layers.
+
+ Parameters
+ ----------
+ model_spec : str
+ The VGSL specification string defining the model architecture.
+
+ Returns
+ -------
+ list
+ A list of layers constructed from the specification string.
+ """
+ returnself._process_layers(model_spec,return_history=True)
+
+
+ def_process_layers(self,model_spec:str,return_history:bool=False,model_name:str="VGSL_Model")->Any:
+"""
+ Process the VGSL specification string to build the model or generate a history of layers.
+
+ Parameters
+ ----------
+ model_spec : str
+ The VGSL specification string defining the model architecture.
+ return_history : bool, optional
+ If True, returns a list of constructed layers (history) instead of the final model.
+ model_name : str, optional
+ The name of the model, by default "VGSL_Model"
+
+ Returns
+ -------
+ Any
+ The built model using the specified backend if `return_history` is False.
+ Otherwise, a list of constructed layers.
+ """
+ # Create a new instance of the layer factory for this model
+ self.layer_factory=self.layer_factory_class()
+
+ # Parse the specification string
+ specs=parse_spec(model_spec)
+
+ # Initialize the first layer (input layer)
+ input_layer=self.layer_factory.input(specs[0])
+
+ # Initialize history if required
+ history=[input_layer]ifreturn_historyelseNone
+
+ # Process each layer specification
+ forspecinspecs[1:]:
+ layer=self._construct_layer(spec,self.layer_factory)
+ ifreturn_history:
+ history.append(layer)
+
+ ifreturn_history:
+ returnhistory
+
+ # Build and return the final model
+ returnself.layer_factory.build(name=model_name)
+
+
+[docs]
+ defconstruct_layer(self,spec:str)->Any:
+"""
+ Constructs a single layer using the layer factory based on the spec string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for a layer.
+
+ Returns
+ -------
+ Any
+ The constructed layer.
+
+ Raises
+ ------
+ ValueError
+ If the layer specification is unknown.
+ """
+ # Create a new instance of the layer factory
+ layer_factory=self.layer_factory_class()
+ returnself._construct_layer(spec,layer_factory)
+
+
+ ### Private Helper Methods ###
+
+ def_detect_backend(self,backend:str)->str:
+"""
+ Detect the backend automatically by checking available libraries.
+ If both TensorFlow and PyTorch are available, TensorFlow is selected by default.
+
+ Parameters
+ ----------
+ backend : str
+ The backend to use for building the model. Can be "tensorflow", "torch", or "auto".
+
+ Returns
+ -------
+ str
+ The detected or provided backend ("tensorflow" or "torch").
+ """
+ ifbackend!="auto":
+ returnbackend
+
+ try:
+ importtensorflowastf
+ return"tensorflow"
+ exceptImportError:
+ pass
+
+ try:
+ importtorch
+ return"torch"
+ exceptImportError:
+ pass
+
+ raiseImportError(
+ "Neither TensorFlow nor PyTorch is installed. Please install one of them.")
+
+ def_initialize_backend_and_factory(self,backend:str)->tuple:
+"""
+ Initialize the backend and return the layer factory class and constructor map.
+
+ Parameters
+ ----------
+ backend : str
+ The backend to use for building the model.
+
+ Returns
+ -------
+ tuple
+ A tuple containing the layer factory class and layer constructors dictionary.
+ """
+ try:
+ ifbackend=="tensorflow":
+ fromvgslify.tensorflow.layersimportTensorFlowLayerFactoryasLayerFactory
+ elifbackend=="torch":
+ fromvgslify.torch.layersimportTorchLayerFactoryasLayerFactory
+ else:
+ raiseValueError(
+ f"Unsupported backend: {backend}. Choose 'tensorflow' or 'torch'.")
+ exceptImportError:
+ raiseImportError(
+ f"Backend '{backend}' is not available. Please install the required library.")
+
+ layer_constructors:Dict[str,Any]={
+ 'C':LayerFactory.conv2d,
+ 'Mp':LayerFactory.pooling2d,
+ 'Ap':LayerFactory.pooling2d,
+ 'L':LayerFactory.rnn,
+ 'G':LayerFactory.rnn,
+ 'B':LayerFactory.rnn,
+ 'Flt':LayerFactory.flatten,
+ 'F':LayerFactory.dense,
+ 'D':LayerFactory.dropout,
+ 'Bn':LayerFactory.batchnorm,
+ 'A':LayerFactory.activation,
+ 'R':LayerFactory.reshape,
+ 'Rc':LayerFactory.reshape,
+ }
+
+ returnLayerFactory,layer_constructors
+
+ def_construct_layer(self,spec:str,layer_factory)->Any:
+"""
+ Constructs a layer using the layer factory based on the specification string.
+
+ Parameters
+ ----------
+ spec : str
+ The VGSL specification string for a layer.
+ layer_factory : Any
+ The layer factory instance to use for constructing the layer.
+
+ Returns
+ -------
+ Any
+ The constructed layer.
+
+ Raises
+ ------
+ ValueError
+ If the layer specification is unknown.
+ """
+ forprefixinsorted(self.layer_constructors.keys(),key=len,reverse=True):
+ ifspec.startswith(prefix):
+ layer_constructor=getattr(
+ layer_factory,self.layer_constructors[prefix].__name__)
+ returnlayer_constructor(spec)
+
+ raiseValueError(f"Unknown layer specification: {spec}")
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/parsers/base_parser.html b/_modules/vgslify/parsers/base_parser.html
new file mode 100644
index 0000000..8ea2f02
--- /dev/null
+++ b/_modules/vgslify/parsers/base_parser.html
@@ -0,0 +1,499 @@
+
+
+
+
+
+
+
+ vgslify.parsers.base_parser — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+classBaseModelParser(ABC):
+"""
+ Abstract base class for model parsers.
+ Provides common utility methods for parsing different frameworks and generating VGSL spec strings.
+ """
+
+
+[docs]
+ defgenerate_vgsl(self,configs:List[Union[
+ Conv2DConfig,
+ Pooling2DConfig,
+ DenseConfig,
+ RNNConfig,
+ DropoutConfig,
+ ReshapeConfig,
+ InputConfig,
+ ActivationConfig
+ ]])->str:
+"""
+ Convert a list of layer configuration dataclasses into a VGSL specification string.
+
+ Parameters
+ ----------
+ configs : List[Union[Conv2DConfig, Pooling2DConfig, DenseConfig, RNNConfig,
+ DropoutConfig, ReshapeConfig, InputConfig, ActivationConfig]]
+ List of layer configurations.
+
+ Returns
+ -------
+ str
+ VGSL specification string.
+ """
+ vgsl_parts=[]
+ i=len(configs)-1# Start from the end of the list to merge activations
+
+ whilei>=0:
+ config=configs[i]
+
+ ifisinstance(config,ActivationConfig):
+ # Check if there is a preceding layer to merge with
+ ifi>0:
+ preceding_config=configs[i-1]
+ ifisinstance(preceding_config,(Conv2DConfig,DenseConfig,RNNConfig))and \
+ preceding_config.activation=='linear':
+ # Merge the activation into the preceding layer
+ preceding_config.activation=config.activation
+ # Skip adding this ActivationConfig
+ i-=1
+ continue
+ # If cannot merge, add the activation spec
+ vgsl_parts.append(self._vgsl_activation(config))
+ else:
+ # Handle non-activation layers and strings
+ ifisinstance(config,InputConfig):
+ vgsl_parts.append(self._vgsl_input(config))
+ elifisinstance(config,Conv2DConfig):
+ vgsl_parts.append(self._vgsl_conv2d(config))
+ elifisinstance(config,Pooling2DConfig):
+ vgsl_parts.append(self._vgsl_pooling2d(config))
+ elifisinstance(config,DenseConfig):
+ vgsl_parts.append(self._vgsl_dense(config))
+ elifisinstance(config,RNNConfig):
+ vgsl_parts.append(self._vgsl_rnn(config))
+ elifisinstance(config,DropoutConfig):
+ vgsl_parts.append(self._vgsl_dropout(config))
+ elifisinstance(config,ReshapeConfig):
+ vgsl_parts.append(self._vgsl_reshape(config))
+ elifisinstance(config,str):
+ vgsl_parts.append(config)
+ else:
+ raiseValueError(f"Unsupported configuration type: {type(config).__name__}")
+ i-=1# Move to the previous config
+
+ # Reverse to restore the original order
+ return" ".join(vgsl_parts[::-1])
+
+
+
+[docs]
+ @abstractmethod
+ defparse_model(self,model)->str:
+"""Parse the model into a VGSL spec string."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_input(self,layer)->InputConfig:
+"""Parse the input layer into a InputConfig dataclass."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_conv2d(self,layer)->Conv2DConfig:
+"""Parse the Conv2D layer into a Conv2DConfig dataclass."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_dense(self,layer)->DenseConfig:
+"""Parse the Dense layer into a DenseConfig dataclass."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_rnn(self,layer)->RNNConfig:
+"""Parse the RNN layer into a RNNConfig dataclass."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_pooling(self,layer)->Pooling2DConfig:
+"""Parse the Pooling layer into a Pooling2DConfig dataclass."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_batchnorm(self,layer)->str:
+"""Parse the BatchNorm layer into a VGSL spec string."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_dropout(self,layer)->DropoutConfig:
+"""Parse the Dropout layer into a DropoutConfig dataclass."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_flatten(self,layer)->str:
+"""Parse the Flatten layer into a VGSL spec string."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_reshape(self,layer)->ReshapeConfig:
+"""Parse the Reshape layer into a ReshapeConfig dataclass."""
+ pass
+
+
+
+[docs]
+ @abstractmethod
+ defparse_activation(self,layer)->ActivationConfig:
+"""Parse the Activation layer into a ActivationConfig dataclass."""
+ pass
+
+
+ # VGSL Generation Methods
+ def_vgsl_input(self,config:InputConfig)->str:
+"""
+ Generate VGSL string for input layer.
+
+ Parameters
+ ----------
+ config : InputConfig
+ Configuration for the input layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the input layer.
+ """
+ return",".join(map(str,filter(lambdax:x!=-1,[
+ config.batch_size,
+ config.depth,
+ config.height,
+ config.width,
+ config.channels
+ ])))
+
+ def_vgsl_conv2d(self,config:Conv2DConfig)->str:
+"""
+ Generate VGSL string for Conv2D layer.
+
+ Parameters
+ ----------
+ config : Conv2DConfig
+ Configuration for the Conv2D layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the Conv2D layer.
+ """
+ act=self._get_activation_code(config.activation)
+ stride_spec=",".join(map(str,config.strides))ifconfig.strides!=(1,1)else""
+ stride_str=f",{stride_spec}"ifstride_specelse""
+ returnf"C{act}{config.kernel_size[0]},{config.kernel_size[1]}{stride_str},{config.filters}"
+
+ def_vgsl_pooling2d(self,config:Pooling2DConfig)->str:
+"""
+ Generate VGSL string for Pooling2D layer.
+
+ Parameters
+ ----------
+ config : Pooling2DConfig
+ Configuration for the Pooling2D layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the Pooling2D layer.
+ """
+ pool_type_code='Mp'ifconfig.pool_type.lower()=='max'else'Ap'
+ pool_size_str=",".join(map(str,config.pool_size))
+ strides_str=",".join(map(str,config.strides))ifconfig.strides!=config.pool_sizeelse""
+ returnf"{pool_type_code}{pool_size_str}{','+strides_strifstrides_strelse''}"
+
+ def_vgsl_dense(self,config:DenseConfig)->str:
+"""
+ Generate VGSL string for Dense layer.
+
+ Parameters
+ ----------
+ config : DenseConfig
+ Configuration for the Dense layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the Dense layer.
+ """
+ act=self._get_activation_code(config.activation)
+ returnf"F{act}{config.units}"
+
+ def_vgsl_rnn(self,config:RNNConfig)->str:
+"""
+ Generate VGSL string for RNN layer.
+
+ Parameters
+ ----------
+ config : RNNConfig
+ Configuration for the RNN layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the RNN layer.
+
+ Raises
+ ------
+ ValueError
+ If an unsupported RNN type is provided.
+ """
+ ifconfig.bidirectional:
+ layer_type='B'
+ rnn_type='l'ifconfig.rnn_type.lower()=='lstm'else'g'
+ else:
+ ifconfig.rnn_type.lower()=='lstm':
+ layer_type='L'
+ elifconfig.rnn_type.lower()=='gru':
+ layer_type='G'
+ else:
+ raiseValueError(f"Unsupported RNN type: {config.rnn_type}")
+ rnn_type='r'ifconfig.go_backwardselse'f'
+
+ return_sequences='s'ifconfig.return_sequencesandnotconfig.bidirectionalelse''
+
+ spec=f"{layer_type}{rnn_type}{return_sequences}{config.units}"
+
+ ifconfig.dropout>0:
+ spec+=f",D{int(config.dropout*100)}"
+ ifconfig.recurrent_dropout>0:
+ spec+=f",Rd{int(config.recurrent_dropout*100)}"
+
+ returnspec
+
+ def_vgsl_dropout(self,config:DropoutConfig)->str:
+"""
+ Generate VGSL string for Dropout layer.
+
+ Parameters
+ ----------
+ config : DropoutConfig
+ Configuration for the Dropout layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the Dropout layer.
+ """
+ returnf"D{int(config.rate*100)}"
+
+ def_vgsl_reshape(self,config:ReshapeConfig)->str:
+"""
+ Generate VGSL string for Reshape layer.
+
+ Parameters
+ ----------
+ config : ReshapeConfig
+ Configuration for the Reshape layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the Reshape layer.
+ """
+ iflen(config.target_shape)==2and(Noneinconfig.target_shapeor-1inconfig.target_shape):
+ return"Rc3"
+ else:
+ reshape_dims=",".join(map(lambdax:str(x)ifxisnotNoneelse'-1',config.target_shape))
+ returnf"R{reshape_dims}"
+
+ def_vgsl_activation(self,config:ActivationConfig)->str:
+"""
+ Generate VGSL string for Activation layer.
+
+ Parameters
+ ----------
+ config : ActivationConfig
+ Configuration for the Activation layer.
+
+ Returns
+ -------
+ str
+ VGSL string representation of the Activation layer.
+ """
+ act=self._get_activation_code(config.activation)
+ returnf"A{act}"
+
+ def_get_activation_code(self,activation:str)->str:
+"""
+ Get the VGSL activation code for a given activation function.
+
+ Parameters
+ ----------
+ activation : str
+ Name of the activation function.
+
+ Returns
+ -------
+ str
+ VGSL activation code.
+
+ Raises
+ ------
+ ValueError
+ If an unsupported activation function is provided.
+ """
+ ACTIVATION_MAP={
+ 'softmax':'s','tanh':'t','relu':'r',
+ 'linear':'l','sigmoid':'m','identity':'l'
+ }
+ act_code=ACTIVATION_MAP.get(activation.lower(),None)
+ ifact_codeisNone:
+ raiseValueError(f"Unsupported activation '{activation}'.")
+ returnact_code
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/parsers/tf_parser.html b/_modules/vgslify/parsers/tf_parser.html
new file mode 100644
index 0000000..5319a27
--- /dev/null
+++ b/_modules/vgslify/parsers/tf_parser.html
@@ -0,0 +1,512 @@
+
+
+
+
+
+
+
+ vgslify.parsers.tf_parser — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+classTensorFlowModelParser(BaseModelParser):
+"""
+ Parser for converting TensorFlow Keras models into VGSL (Variable-size Graph Specification Language) spec strings.
+
+ This class extends the BaseModelParser to provide specific functionality for TensorFlow Keras models.
+ It uses configuration dataclasses to represent different layer types and converts them into
+ VGSL spec strings.
+
+ Attributes
+ ----------
+ layer_parsers : Dict[Type[tf.keras.layers.Layer], Callable]
+ A dictionary mapping TensorFlow Keras layer types to their corresponding parsing methods.
+
+ Notes
+ -----
+ This parser supports a wide range of TensorFlow Keras layers and can be extended to support
+ additional layer types by adding new parsing methods and updating the layer_parsers dictionary.
+ """
+
+ def__init__(self):
+ # Initialize the layer parsers mapping
+ self.layer_parsers:Dict[Type[tf.keras.layers.Layer],Callable]={
+ tf.keras.layers.InputLayer:self.parse_input,
+ tf.keras.layers.Conv2D:self.parse_conv2d,
+ tf.keras.layers.Dense:self.parse_dense,
+ tf.keras.layers.LSTM:self.parse_rnn,
+ tf.keras.layers.GRU:self.parse_rnn,
+ tf.keras.layers.Bidirectional:self.parse_rnn,
+ tf.keras.layers.MaxPooling2D:self.parse_pooling,
+ tf.keras.layers.AveragePooling2D:self.parse_pooling,
+ tf.keras.layers.BatchNormalization:self.parse_batchnorm,
+ tf.keras.layers.Dropout:self.parse_dropout,
+ tf.keras.layers.Reshape:self.parse_reshape,
+ tf.keras.layers.Flatten:self.parse_flatten,
+ tf.keras.layers.Activation:self.parse_activation
+ }
+
+
+[docs]
+ defparse_model(self,model:tf.keras.models.Model)->str:
+"""
+ Parse a TensorFlow Keras model into a VGSL spec string.
+
+ Parameters
+ ----------
+ model : tf.keras.models.Model
+ Keras model to be converted.
+
+ Returns
+ -------
+ str
+ VGSL spec string.
+
+ Raises
+ ------
+ ValueError
+ If the model contains unsupported layers or if the input shape is invalid.
+ """
+ configs=[]
+
+ # Handle InputLayer
+ ifnotisinstance(model.layers[0],tf.keras.layers.InputLayer):
+ input_layer=tf.keras.layers.InputLayer(
+ input_shape=model.input_shape[1:],
+ batch_size=model.input_shape[0]
+ )
+ input_config=self.parse_input(input_layer)
+ configs.append(input_config)
+
+ # Iterate through all layers in the model
+ foridx,layerinenumerate(model.layers):
+ layer_type=type(layer)
+ parser_func=self.layer_parsers.get(layer_type,None)
+
+ ifparser_func:
+ # Parse the layer
+ config=parser_func(layer)
+
+ # Append the config if not None
+ ifconfig:
+ configs.append(config)
+ else:
+ raiseValueError(
+ f"Unsupported layer type {layer_type.__name__} at position {idx}."
+ )
+
+ # Generate VGSL spec string from configs
+ returnself.generate_vgsl(configs)
+
+
+
+ # Parser methods for different layer types
+
+
+[docs]
+ defparse_pooling(self,layer:Union[tf.keras.layers.MaxPooling2D,tf.keras.layers.AveragePooling2D],pool_type:str)->Pooling2DConfig:
+"""
+ Parse a Pooling layer into a Pooling2DConfig dataclass.
+
+ Parameters
+ ----------
+ layer : tf.keras.layers.MaxPooling2D or tf.keras.layers.AveragePooling2D
+ The Pooling layer to parse.
+ pool_type : str
+ Type of pooling ('max' or 'average').
+
+ Returns
+ -------
+ Pooling2DConfig
+ The configuration for the Pooling layer.
+ """
+ returnPooling2DConfig(
+ pool_type=pool_type,
+ pool_size=layer.pool_size,
+ strides=layer.stridesiflayer.strideselselayer.pool_size
+ )
+
+
+
+[docs]
+ defparse_batchnorm(self,layer:tf.keras.layers.BatchNormalization)->None:
+"""
+ Parse a BatchNormalization layer.
+ Since BatchNormalization does not require a VGSL spec beyond 'Bn', return a placeholder.
+
+ Parameters
+ ----------
+ layer : tf.keras.layers.BatchNormalization
+ The BatchNormalization layer to parse.
+
+ Returns
+ -------
+ None
+ Indicates that the VGSL spec should include 'Bn'.
+ """
+ return"Bn"
+
+
+
+[docs]
+ defparse_dropout(self,layer:tf.keras.layers.Dropout)->DropoutConfig:
+"""
+ Parse a Dropout layer into a DropoutConfig dataclass.
+
+ Parameters
+ ----------
+ layer : tf.keras.layers.Dropout
+ The Dropout layer to parse.
+
+ Returns
+ -------
+ DropoutConfig
+ The configuration for the Dropout layer.
+ """
+ returnDropoutConfig(
+ rate=layer.rate
+ )
+
+
+
+[docs]
+ defparse_flatten(self,layer:tf.keras.layers.Flatten)->None:
+"""
+ Parse a Flatten layer.
+ Since Flatten does not require a VGSL spec beyond 'Flatten', return a placeholder.
+
+ Parameters
+ ----------
+ layer : tf.keras.layers.Flatten
+ The Flatten layer to parse.
+
+ Returns
+ -------
+ None
+ Indicates that the VGSL spec should include 'Flatten'.
+ """
+ return"Flt"
+
+
+
+[docs]
+ defparse_reshape(self,layer:tf.keras.layers.Reshape)->ReshapeConfig:
+"""
+ Parse a Reshape layer into a ReshapeConfig dataclass.
+
+ Parameters
+ ----------
+ layer : tf.keras.layers.Reshape
+ The Reshape layer to parse.
+
+ Returns
+ -------
+ ReshapeConfig
+ The configuration for the Reshape layer.
+ """
+ target_shape=layer.target_shape
+ returnReshapeConfig(
+ target_shape=target_shape
+ )
+
+
+
+[docs]
+ defparse_activation(self,layer:tf.keras.layers.Activation)->ActivationConfig:
+"""
+ Parse an Activation layer.
+
+ Parameters
+ ----------
+ layer : tf.keras.layers.Activation
+ The Activation layer to parse.
+
+ Returns
+ -------
+ ActivationConfig
+ The configuration for the Activation layer.
+ """
+ activation=self._extract_activation(layer)
+ returnActivationConfig(activation=activation)
+
+
+
+ # Helper methods
+ def_extract_activation(self,layer:tf.keras.layers.Layer)->str:
+"""
+ Extract the activation function from a TensorFlow Keras layer.
+
+ Parameters
+ ----------
+ layer : tf.keras.layers.Layer
+ The layer from which to extract the activation.
+
+ Returns
+ -------
+ str
+ The activation function name.
+ """
+ ifhasattr(layer,'activation')andcallable(layer.activation):
+ activation=layer.activation.__name__
+ elifisinstance(layer,tf.keras.layers.Activation):
+ activation=layer.activation.__name__
+ else:
+ activation='linear'
+ returnactivation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/parsers/torch_parser.html b/_modules/vgslify/parsers/torch_parser.html
new file mode 100644
index 0000000..2890152
--- /dev/null
+++ b/_modules/vgslify/parsers/torch_parser.html
@@ -0,0 +1,518 @@
+
+
+
+
+
+
+
+ vgslify.parsers.torch_parser — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+classTorchModelParser(BaseModelParser):
+"""
+ Parser for converting PyTorch models into VGSL (Variable-size Graph Specification Language) spec strings.
+
+ This class extends the BaseModelParser to provide specific functionality for PyTorch models.
+ It uses configuration dataclasses to represent different layer types and converts them into
+ VGSL spec strings.
+
+ Attributes
+ ----------
+ layer_parsers : Dict[Type[nn.Module], Callable]
+ A dictionary mapping PyTorch layer types to their corresponding parsing methods.
+
+ Notes
+ -----
+ This parser supports a wide range of PyTorch layers and can be extended to support
+ additional layer types by adding new parsing methods and updating the layer_parsers dictionary.
+ """
+
+ def__init__(self):
+ # Initialize the layer parsers mapping
+ self.layer_parsers:Dict[Type[nn.Module],Callable]={
+ nn.Conv2d:self.parse_conv2d,
+ nn.Linear:self.parse_dense,
+ nn.LSTM:self.parse_rnn,
+ nn.GRU:self.parse_rnn,
+ nn.MaxPool2d:self.parse_pooling,
+ nn.AvgPool2d:self.parse_pooling,
+ nn.BatchNorm2d:self.parse_batchnorm,
+ nn.Dropout:self.parse_dropout,
+ nn.Flatten:self.parse_flatten,
+ nn.ReLU:self.parse_activation,
+ nn.Sigmoid:self.parse_activation,
+ nn.Tanh:self.parse_activation,
+ nn.Identity:self.parse_activation,
+ nn.Softmax:self.parse_activation,
+ Reshape:self.parse_reshape,
+ }
+
+
+[docs]
+ defparse_model(self,model:nn.Module)->str:
+"""
+ Parse a PyTorch model into a VGSL spec string.
+
+ Parameters
+ ----------
+ model : nn.Module
+ PyTorch model to be converted.
+
+ Returns
+ -------
+ str
+ VGSL spec string.
+
+ Raises
+ ------
+ ValueError
+ If the model contains unsupported layers or if the input shape is invalid.
+ """
+ configs=[]
+
+ # Extract input shape from the first layer
+ first_layer=next(model.children())
+ input_config=self.parse_input(first_layer)
+ ifinput_config:
+ configs.append(input_config)
+
+ # Iterate through all layers in the model
+ forname,layerinmodel.named_modules():
+ ifisinstance(layer,nn.Sequential):
+ continue
+
+ layer_type=type(layer)
+ parser_func=self.layer_parsers.get(layer_type,None)
+
+ ifparser_func:
+ # Parse the layer
+ config=parser_func(layer)
+ ifisinstance(config,ReshapeConfig)orconfig=="Flt":
+ warnings.warn("Warning: The model contains a Flatten or Reshape layer. This may cause VGSLify to "
+ "misinterpret the model's input shape. It is recommended to manually verify and "
+ "adjust the input shape if necessary to ensure accuracy.")
+
+ # Append the config if not None
+ ifconfig:
+ configs.append(config)
+ else:
+ raiseValueError(
+ f"Unsupported layer type {layer_type.__name__} at {name}."
+ )
+
+ # Generate VGSL spec string from configs
+ returnself.generate_vgsl(configs)
+
+
+
+[docs]
+ defparse_input(self,layer:nn.Module)->InputConfig:
+"""
+ Parse the input shape from the first layer of the model.
+
+ Parameters
+ ----------
+ layer : nn.Module
+ The first layer of the PyTorch model.
+
+ Returns
+ -------
+ InputConfig
+ The configuration for the input layer.
+
+ Raises
+ ------
+ ValueError
+ If the input shape cannot be determined.
+ """
+ batch_size=None# Placeholder for dynamic batch size
+ depth,height,width,channels=-1,-1,-1,-1
+
+ ifhasattr(layer,'in_channels'):
+ # Conv2d, Conv3d, BatchNorm2d, etc.
+ channels=layer.in_channels
+ elifhasattr(layer,'in_features'):
+ # Linear, LSTM, GRU, etc.
+ channels=layer.in_features
+ elifhasattr(layer,'input_size'):
+ # Some RNN layers
+ channels=layer.input_size
+ elifhasattr(layer,'num_features'):
+ # Some normalization layers
+ channels=layer.num_features
+
+ # Try to infer spatial dimensions if available
+ ifisinstance(layer,(nn.Conv2d,nn.BatchNorm2d,nn.MaxPool2d,nn.AvgPool2d)):
+ height,width=None,None
+ elifisinstance(layer,(nn.Conv3d,nn.BatchNorm3d,nn.MaxPool3d,nn.AvgPool3d)):
+ depth,height,width=None,None,None
+ elifisinstance(layer,(nn.Linear,nn.LSTM,nn.GRU)):
+ depth,height,width=None,None,None
+
+ ifchannels==-1:
+ raiseValueError("Unable to determine input shape from the first layer.")
+
+ returnInputConfig(
+ batch_size=batch_size,
+ depth=depth,
+ height=height,
+ width=width,
+ channels=channels
+ )
+
+
+ # Parser methods for different layer types
+
+[docs]
+ defparse_conv2d(self,layer:nn.Conv2d)->Conv2DConfig:
+"""
+ Parse a Conv2d layer into a Conv2DConfig dataclass.
+
+ Parameters
+ ----------
+ layer : nn.Conv2d
+ The Conv2d layer to parse.
+
+ Returns
+ -------
+ Conv2DConfig
+ The configuration for the Conv2D layer.
+ """
+ returnConv2DConfig(
+ activation="linear",# PyTorch typically separates activation
+ kernel_size=layer.kernel_size,
+ strides=layer.stride,
+ filters=layer.out_channels
+ )
+
+
+
+[docs]
+ defparse_dense(self,layer:nn.Linear)->DenseConfig:
+"""
+ Parse a Linear layer into a DenseConfig dataclass.
+
+ Parameters
+ ----------
+ layer : nn.Linear
+ The Linear layer to parse.
+
+ Returns
+ -------
+ DenseConfig
+ The configuration for the Dense layer.
+ """
+ returnDenseConfig(
+ activation="linear",# PyTorch typically separates activation
+ units=layer.out_features
+ )
+
+
+
+[docs]
+ defparse_rnn(self,layer:Union[nn.LSTM,nn.GRU])->RNNConfig:
+"""
+ Parse an RNN layer (LSTM or GRU) into an RNNConfig dataclass.
+
+ Parameters
+ ----------
+ layer : Union[nn.LSTM, nn.GRU]
+ The RNN layer to parse.
+
+ Returns
+ -------
+ RNNConfig
+ The configuration for the RNN layer.
+ """
+ ifisinstance(layer,nn.LSTM):
+ rnn_type='lstm'
+ elifisinstance(layer,nn.GRU):
+ rnn_type='gru'
+ else:
+ raiseValueError(f"Unsupported RNN layer type {type(layer).__name__}.")
+
+ returnRNNConfig(
+ units=layer.hidden_size,
+ return_sequences=True,# PyTorch RNNs always return sequences by default
+ go_backwards=False,# PyTorch doesn't have a direct equivalent
+ dropout=layer.dropout,
+ recurrent_dropout=0,# PyTorch doesn't have recurrent dropout
+ rnn_type=rnn_type,
+ bidirectional=layer.bidirectional
+ )
+
+
+
+[docs]
+ defparse_pooling(self,layer:Union[nn.MaxPool2d,nn.AvgPool2d])->Pooling2DConfig:
+"""
+ Parse a Pooling layer into a Pooling2DConfig dataclass.
+
+ Parameters
+ ----------
+ layer : nn.MaxPool2d or nn.AvgPool2d
+ The Pooling layer to parse.
+
+ Returns
+ -------
+ Pooling2DConfig
+ The configuration for the Pooling layer.
+ """
+ ifisinstance(layer,nn.MaxPool2d):
+ pool_type="max"
+ elifisinstance(layer,nn.AvgPool2d):
+ pool_type="average"
+
+ returnPooling2DConfig(
+ pool_type=pool_type,
+ pool_size=layer.kernel_size,
+ strides=layer.stride
+ )
+
+
+
+[docs]
+ defparse_batchnorm(self,layer:nn.BatchNorm2d)->str:
+"""
+ Parse a BatchNorm2d layer.
+
+ Parameters
+ ----------
+ layer : nn.BatchNorm2d
+ The BatchNorm2d layer to parse.
+
+ Returns
+ -------
+ str
+ Indicates that the VGSL spec should include 'Bn'.
+ """
+ return"Bn"
+
+
+
+[docs]
+ defparse_dropout(self,layer:nn.Dropout)->DropoutConfig:
+"""
+ Parse a Dropout layer into a DropoutConfig dataclass.
+
+ Parameters
+ ----------
+ layer : nn.Dropout
+ The Dropout layer to parse.
+
+ Returns
+ -------
+ DropoutConfig
+ The configuration for the Dropout layer.
+ """
+ returnDropoutConfig(
+ rate=layer.p
+ )
+
+
+
+[docs]
+ defparse_flatten(self,layer:nn.Flatten)->str:
+"""
+ Parse a Flatten layer.
+
+ Parameters
+ ----------
+ layer : nn.Flatten
+ The Flatten layer to parse.
+
+ Returns
+ -------
+ str
+ Indicates that the VGSL spec should include 'Flatten'.
+ """
+ return"Flt"
+
+
+
+[docs]
+ defparse_reshape(self,layer:Reshape)->ReshapeConfig:
+"""
+ Parse a Reshape layer into a ReshapeConfig dataclass.
+
+ Parameters
+ ----------
+ layer : Reshape
+ The custom Reshape layer to parse.
+
+ Returns
+ -------
+ ReshapeConfig
+ The configuration for the Reshape layer.
+ """
+ target_shape=layer.target_shape
+ returnReshapeConfig(
+ target_shape=target_shape
+ )
+[docs]
+classTensorFlowLayerFactory(LayerFactory):
+"""
+ TensorFlowLayerFactory is responsible for creating TensorFlow-specific layers based on parsed
+ VGSL (Variable-size Graph Specification Language) specifications.
+
+ This factory handles the creation of various types of layers, including convolutional layers,
+ pooling layers, RNN layers, dense layers, activation layers, and more.
+
+ Attributes
+ ----------
+ layers : list
+ A list of TensorFlow layers that have been added to the factory.
+ shape : tuple of int
+ The current shape of the tensor, excluding the batch size.
+ _input_shape : tuple of int or None
+ The original input shape provided during initialization.
+ """
+
+ def__init__(self,input_shape:Tuple[int,...]=None):
+"""
+ Initialize the TensorFlowLayerFactory.
+
+ Parameters
+ ----------
+ input_shape : tuple of int, optional
+ The input shape for the model, excluding batch size.
+ """
+ super().__init__(input_shape,data_format='channels_last')
+
+
+[docs]
+ defbuild(self,name:str="VGSL_Model")->tf.keras.models.Model:
+"""
+ Build the final model using the accumulated layers.
+
+ Parameters
+ ----------
+ name : str, optional
+ The name of the model, by default "VGSL_Model"
+
+ Returns
+ -------
+ tf.keras.models.Model
+ The constructed TensorFlow model.
+
+ Raises
+ ------
+ ValueError
+ If no layers have been added to the model.
+ ValueError
+ If no input shape has been specified for the model.
+ """
+ ifnotself.layers:
+ raiseValueError("No layers added to the model.")
+ ifnotself._input_shape:
+ raiseValueError("No input shape specified for the model.")
+
+ # If we do not have an input layer, add one
+ ifnotisinstance(self.layers[0],tf.keras.KerasTensor):
+ input_layer=tf.keras.Input(shape=self._input_shape)
+ self.layers.insert(0,input_layer)
+
+ inputs=self.layers[0]
+ outputs=inputs
+ forlayerinself.layers[1:]:
+ outputs=layer(outputs)
+ model=tf.keras.models.Model(
+ inputs=inputs,outputs=outputs,name=name)
+ returnmodel
+
+
+ # Layer creation methods
+ def_input(self,config:InputConfig,input_shape:Tuple[int,...]):
+"""
+ Create a TensorFlow Input layer.
+
+ Parameters
+ ----------
+ config : InputConfig
+ Configuration object for the Input layer.
+ input_shape : tuple of int
+ The input shape for the layer.
+
+ Returns
+ -------
+ tf.keras.layers.Input
+ The created Input layer.
+ """
+ returntf.keras.Input(shape=input_shape,batch_size=config.batch_size)
+
+ def_conv2d(self,config:Conv2DConfig):
+"""
+ Create a TensorFlow Conv2D layer.
+
+ Parameters
+ ----------
+ config : Conv2DConfig
+ Configuration object for the Conv2D layer.
+
+ Returns
+ -------
+ tf.keras.layers.Conv2D
+ The created Conv2D layer.
+ """
+ returntf.keras.layers.Conv2D(
+ filters=config.filters,
+ kernel_size=config.kernel_size,
+ strides=config.strides,
+ padding='same',
+ activation=None
+ )
+
+ def_pooling2d(self,config:Pooling2DConfig):
+"""
+ Create a TensorFlow Pooling2D layer.
+
+ Parameters
+ ----------
+ config : Pooling2DConfig
+ Configuration object for the Pooling2D layer.
+
+ Returns
+ -------
+ tf.keras.layers.Layer
+ The created Pooling2D layer (either MaxPooling2D or AveragePooling2D).
+ """
+ ifconfig.pool_type=='max':
+ returntf.keras.layers.MaxPooling2D(
+ pool_size=config.pool_size,
+ strides=config.strides,
+ padding='same'
+ )
+ ifconfig.pool_type=='avg':
+ returntf.keras.layers.AveragePooling2D(
+ pool_size=config.pool_size,
+ strides=config.strides,
+ padding='same'
+ )
+
+ def_dense(self,config:DenseConfig):
+"""
+ Create a TensorFlow Dense layer.
+
+ Parameters
+ ----------
+ config : DenseConfig
+ Configuration object for the Dense layer.
+
+ Returns
+ -------
+ tf.keras.layers.Dense
+ The created Dense layer.
+ """
+ returntf.keras.layers.Dense(
+ units=config.units,
+ activation=None
+ )
+
+ def_rnn(self,config:RNNConfig):
+"""
+ Create a TensorFlow RNN layer (LSTM or GRU), either unidirectional or bidirectional.
+
+ Parameters
+ ----------
+ config : RNNConfig
+ Configuration object for the RNN layer.
+
+ Returns
+ -------
+ tf.keras.layers.Layer
+ The created RNN layer (either LSTM or GRU, unidirectional or bidirectional).
+
+ Raises
+ ------
+ ValueError
+ If an unsupported RNN type is specified.
+ """
+ ifconfig.rnn_type.upper()=='L':
+ rnn_class=tf.keras.layers.LSTM
+ elifconfig.rnn_type.upper()=='G':
+ rnn_class=tf.keras.layers.GRU
+ else:
+ raiseValueError(f"Unsupported RNN type: {config.rnn_type}")
+
+ rnn_layer=rnn_class(
+ units=config.units,
+ return_sequences=config.return_sequences,
+ dropout=config.dropout,
+ recurrent_dropout=config.recurrent_dropout
+ )
+
+ ifconfig.bidirectional:
+ returntf.keras.layers.Bidirectional(
+ rnn_layer,
+ merge_mode='concat'
+ )
+ else:
+ returnrnn_layer
+
+ def_batchnorm(self):
+"""
+ Create a TensorFlow BatchNormalization layer.
+
+ Returns
+ -------
+ tf.keras.layers.BatchNormalization
+ The created BatchNormalization layer.
+ """
+ returntf.keras.layers.BatchNormalization()
+
+ def_dropout(self,config:DropoutConfig):
+"""
+ Create a TensorFlow Dropout layer.
+
+ Parameters
+ ----------
+ config : DropoutConfig
+ Configuration object for the Dropout layer.
+
+ Returns
+ -------
+ tf.keras.layers.Dropout
+ The created Dropout layer.
+ """
+ returntf.keras.layers.Dropout(rate=config.rate)
+
+ def_activation(self,activation_function:str):
+"""
+ Create a TensorFlow activation layer.
+
+ Parameters
+ ----------
+ activation_function : str
+ Name of the activation function.
+
+ Returns
+ -------
+ tf.keras.layers.Activation
+ The created activation layer.
+ """
+ returntf.keras.layers.Activation(activation=activation_function)
+
+ def_reshape(self,config:ReshapeConfig):
+"""
+ Create a TensorFlow Reshape layer.
+
+ Parameters
+ ----------
+ config : ReshapeConfig
+ Configuration object for the Reshape layer.
+
+ Returns
+ -------
+ tf.keras.layers.Reshape
+ The created Reshape layer.
+ """
+ returntf.keras.layers.Reshape(target_shape=config.target_shape)
+
+ def_flatten(self):
+"""
+ Create a TensorFlow Flatten layer.
+
+ Returns
+ -------
+ tf.keras.layers.Flatten
+ The created Flatten layer.
+ """
+ returntf.keras.layers.Flatten()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/torch/layers.html b/_modules/vgslify/torch/layers.html
new file mode 100644
index 0000000..71b237c
--- /dev/null
+++ b/_modules/vgslify/torch/layers.html
@@ -0,0 +1,470 @@
+
+
+
+
+
+
+
+ vgslify.torch.layers — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+classTorchLayerFactory(LayerFactory):
+"""
+ TorchLayerFactory is responsible for creating PyTorch-specific layers based on parsed
+ VGSL (Variable-size Graph Specification Language) specifications.
+
+ This factory handles the creation of various types of layers, including convolutional layers,
+ pooling layers, RNN layers, dense layers, activation layers, and more.
+
+ Attributes
+ ----------
+ layers : list
+ A list of PyTorch layers that have been added to the factory.
+ shape : tuple of int
+ The current shape of the tensor, excluding the batch size.
+ _input_shape : tuple of int or None
+ The original input shape provided during initialization.
+ """
+
+ def__init__(self,input_shape:Tuple[int,...]=None):
+"""
+ Initialize the TorchLayerFactory.
+
+ Parameters
+ ----------
+ input_shape : tuple of int, optional
+ The input shape for the model, excluding batch size.
+ """
+ super().__init__(input_shape,data_format='channels_first')
+
+
+[docs]
+ defbuild(self,name:str="VGSL_Model")->nn.Module:
+"""
+ Build the final model using the accumulated layers.
+
+ Parameters
+ ----------
+ name : str, optional
+ The name of the model, by default "VGSL_Model"
+
+ Returns
+ -------
+ torch.nn.Module
+ The constructed PyTorch model.
+
+ Raises
+ ------
+ ValueError
+ If no layers have been added to the model.
+ ValueError
+ If no input shape has been specified for the model.
+ """
+ ifnotself.layers:
+ raiseValueError("No layers added to the model.")
+ ifnotself._input_shape:
+ raiseValueError("No input shape specified for the model.")
+
+ # model = VGSLModel(self.layers)
+ # TODO: Implement VGSLModel class
+ model=nn.Sequential(*self.layers)
+ model.__class__.__name__=name
+ returnmodel
+
+
+ # Layer creation methods
+ def_input(self,config:InputConfig,input_shape:Tuple[int,...]):
+"""
+ Create a PyTorch input layer (placeholder method).
+
+ Parameters
+ ----------
+ config : InputConfig
+ Configuration object (unused in PyTorch).
+ input_shape : tuple of int
+ The input shape for the layer.
+
+ Returns
+ -------
+ None
+ PyTorch doesn't require a separate input layer.
+ """
+ returnNone
+
+ def_conv2d(self,config:Conv2DConfig):
+"""
+ Create a PyTorch Conv2d layer.
+
+ Parameters
+ ----------
+ config : Conv2DConfig
+ Configuration object for the Conv2D layer.
+
+ Returns
+ -------
+ torch.nn.Conv2d
+ The created Conv2d layer.
+ """
+ padding='same'iftorch.__version__>='1.7'elseself._compute_same_padding(
+ config.kernel_size,config.strides)
+ returnnn.Conv2d(
+ in_channels=self.shape[0],
+ out_channels=config.filters,
+ kernel_size=config.kernel_size,
+ stride=config.strides,
+ padding=padding
+ )
+
+ def_pooling2d(self,config:Pooling2DConfig):
+"""
+ Create a PyTorch Pooling2d layer.
+
+ Parameters
+ ----------
+ config : Pooling2DConfig
+ Configuration object for the Pooling2D layer.
+
+ Returns
+ -------
+ torch.nn.Module
+ The created Pooling2d layer (either MaxPool2d or AvgPool2d).
+ """
+ padding=self._compute_same_padding(config.pool_size,config.strides)
+ pool_layer=nn.MaxPool2difconfig.pool_type=='max'elsenn.AvgPool2d
+ returnpool_layer(
+ kernel_size=config.pool_size,
+ stride=config.strides,
+ padding=padding
+ )
+
+ def_dense(self,config:DenseConfig):
+"""
+ Create a PyTorch Linear (Dense) layer.
+
+ Parameters
+ ----------
+ config : DenseConfig
+ Configuration object for the Dense layer.
+
+ Returns
+ -------
+ torch.nn.Linear
+ The created Linear layer.
+ """
+ returnnn.Linear(self.shape[-1],config.units)
+
+ def_rnn(self,config:RNNConfig):
+"""
+ Create a PyTorch RNN layer (LSTM or GRU), either unidirectional or bidirectional.
+
+ Parameters
+ ----------
+ config : RNNConfig
+ Configuration object for the RNN layer.
+
+ Returns
+ -------
+ torch.nn.Module
+ The created RNN layer (either LSTM or GRU, unidirectional or bidirectional).
+
+ Raises
+ ------
+ ValueError
+ If an unsupported RNN type is specified.
+ """
+ ifconfig.rnn_type.upper()=='L':
+ rnn_class=nn.LSTM
+ elifconfig.rnn_type.upper()=='G':
+ rnn_class=nn.GRU
+ else:
+ raiseValueError(f"Unsupported RNN type: {config.rnn_type}")
+
+ returnrnn_class(
+ input_size=self.shape[-1],
+ hidden_size=config.units,
+ num_layers=1,
+ batch_first=True,
+ dropout=config.dropout,
+ bidirectional=config.bidirectional
+ )
+
+ def_batchnorm(self):
+"""
+ Create a PyTorch BatchNorm layer.
+
+ Returns
+ -------
+ torch.nn.Module
+ The created BatchNorm layer (either BatchNorm1d or BatchNorm2d).
+
+ Raises
+ ------
+ ValueError
+ If the input shape is not supported for BatchNorm.
+ """
+ iflen(self.shape)==3:
+ returnnn.BatchNorm2d(self.shape[0])
+ eliflen(self.shape)==2:
+ returnnn.BatchNorm1d(self.shape[0])
+ else:
+ raiseValueError("Unsupported input shape for BatchNorm layer.")
+
+ def_dropout(self,config:DropoutConfig):
+"""
+ Create a PyTorch Dropout layer.
+
+ Parameters
+ ----------
+ config : DropoutConfig
+ Configuration object for the Dropout layer.
+
+ Returns
+ -------
+ nn.Dropout
+ The created Dropout layer.
+ """
+ returnnn.Dropout(p=config.rate)
+
+ def_activation(self,activation_function:str):
+"""
+ Create a PyTorch activation layer.
+
+ Parameters
+ ----------
+ activation_function : str
+ Name of the activation function. Supported values are 'softmax', 'tanh', 'relu',
+ 'linear', 'sigmoid'.
+
+ Returns
+ -------
+ nn.Module
+ The created activation layer.
+
+ Raises
+ ------
+ ValueError
+ If the activation function is not supported.
+ """
+ activations={
+ 'softmax':nn.Softmax(dim=1),
+ 'tanh':nn.Tanh(),
+ 'relu':nn.ReLU(),
+ 'linear':nn.Identity(),
+ 'sigmoid':nn.Sigmoid(),
+ }
+ ifactivation_functioninactivations:
+ returnactivations[activation_function]
+ else:
+ raiseValueError(f"Unsupported activation: {activation_function}")
+
+ def_reshape(self,config:ReshapeConfig):
+"""
+ Create a PyTorch Reshape layer.
+
+ Parameters
+ ----------
+ config : ReshapeConfig
+ Configuration object for the Reshape layer.
+
+ Returns
+ -------
+ nn.Module
+ The created Reshape layer.
+ """
+ returnReshape(*config.target_shape)
+
+ def_flatten(self):
+"""
+ Create a PyTorch Flatten layer.
+
+ Returns
+ -------
+ nn.Flatten
+ The created Flatten layer.
+ """
+ returnnn.Flatten()
+
+ # Helper methods
+ def_compute_same_padding(self,kernel_size,stride):
+"""
+ Compute the padding size to achieve 'same' padding.
+
+ Parameters
+ ----------
+ kernel_size : int or tuple
+ Size of the kernel.
+ stride : int or tuple
+ Stride of the convolution.
+
+ Returns
+ -------
+ tuple
+ Padding size for height and width dimensions.
+ """
+ ifisinstance(kernel_size,int):
+ kernel_size=(kernel_size,kernel_size)
+ ifisinstance(stride,int):
+ stride=(stride,stride)
+ padding=[]
+ fork,sinzip(kernel_size,stride):
+ p=((k-1)//2)
+ padding.append(p)
+ returntuple(padding)
+
+ def_get_activation_layer(self,activation_name:str):
+"""
+ Return a PyTorch activation layer based on the activation name.
+
+ Parameters
+ ----------
+ activation_name : str
+ Name of the activation function.
+
+ Returns
+ -------
+ torch.nn.Module
+ The activation layer.
+
+ Raises
+ ------
+ ValueError
+ If the activation_name is not recognized.
+ """
+ activations={
+ 'softmax':nn.Softmax(dim=1),
+ 'tanh':nn.Tanh(),
+ 'relu':nn.ReLU(),
+ 'linear':nn.Identity(),
+ 'sigmoid':nn.Sigmoid(),
+ }
+ ifactivation_nameinactivations:
+ returnactivations[activation_name]
+ else:
+ raiseValueError(f"Unsupported activation: {activation_name}")
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_modules/vgslify/utils/model_to_spec.html b/_modules/vgslify/utils/model_to_spec.html
new file mode 100644
index 0000000..d10d80d
--- /dev/null
+++ b/_modules/vgslify/utils/model_to_spec.html
@@ -0,0 +1,177 @@
+
+
+
+
+
+
+
+ vgslify.utils.model_to_spec — VGSLify 0.13.0 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[docs]
+defmodel_to_spec(model)->str:
+"""
+ Convert a deep learning model (TensorFlow or PyTorch) to a VGSL spec string.
+
+ Parameters
+ ----------
+ model : Model
+ The deep learning model to be converted. Can be a TensorFlow model (tf.keras.models.Model)
+ or a PyTorch model (torch.nn.Module).
+
+ Returns
+ -------
+ str
+ VGSL spec string.
+
+ Raises
+ ------
+ ValueError
+ If the model is not supported or cannot be parsed.
+
+ Examples
+ --------
+ >>> from vgslify.utils import model_to_spec
+ >>> import tensorflow as tf
+ >>> model = tf.keras.models.load_model("path_to_model.h5")
+ >>> spec_string = model_to_spec(model)
+ >>> print(spec_string)
+ """
+
+ # Check if it's a TensorFlow model
+ iftfandisinstance(model,tf.keras.Model):
+ fromvgslify.parsers.tf_parserimportTensorFlowModelParser
+ parser=TensorFlowModelParser()
+
+ # Check if it's a PyTorch model
+ ifnnandisinstance(model,nn.Module):
+ fromvgslify.parsers.torch_parserimportTorchModelParser
+ parser=TorchModelParser()
+
+ # Raise an error if the model is not recognized
+ ifnotparser:
+ raiseValueError(
+ f"Unsupported model type: {type(model).__name__}. Expected TensorFlow "
+ "or PyTorch model.")
+
+ returnparser.parse_model(model)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/_sources/convert_to_vgsl_spec.rst.txt b/_sources/convert_to_vgsl_spec.rst.txt
new file mode 100644
index 0000000..c8cf4ea
--- /dev/null
+++ b/_sources/convert_to_vgsl_spec.rst.txt
@@ -0,0 +1,67 @@
+Converting Models Back to VGSL Spec
+===================================
+
+VGSLify now includes the ability to convert a trained or existing model back into a VGSL specification string. This functionality is useful for:
+
+- Sharing model architectures in a concise format.
+- Reproducing models from the VGSL spec string.
+- Analyzing and understanding complex models via their VGSL representation.
+
+How It Works
+------------
+
+After you build or load a model using TensorFlow (with PyTorch support planned), you can convert it back into its VGSL specification string using the `model_to_spec()` function provided by VGSLify.
+
+Example: Convert a Model to VGSL Spec
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Here’s how you can convert an existing model to its VGSL spec:
+
+.. code-block:: python
+
+ from vgslify.utils import model_to_spec
+ from tensorflow.keras.models import load_model
+
+ # Load an existing TensorFlow model (previously saved)
+ model = load_model("path_to_your_model.keras")
+
+ # Convert the model to VGSL spec
+ vgsl_spec = model_to_spec(model)
+ print(vgsl_spec)
+
+The above example will output the VGSL spec string corresponding to the architecture of the loaded model.
+
+Saving and Reusing VGSL Spec
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Once you've converted the model to a VGSL spec, you can easily save or share the spec string. This can be reused to rebuild the same model using VGSLify.
+
+1. **Save the VGSL Spec**:
+
+ - Save the generated VGSL spec string to a file or store it in your project for later use.
+
+.. code-block:: python
+
+ with open("model_spec.txt", "w") as f:
+ f.write(vgsl_spec)
+
+2. **Rebuild the Model from the Spec**:
+
+ - You can use the saved VGSL spec to rebuild the exact same model at any time.
+
+.. code-block:: python
+
+ from vgslify.generator import VGSLModelGenerator
+
+ # Load the VGSL spec from file
+ with open("model_spec.txt", "r") as f:
+ vgsl_spec = f.read()
+
+ # Rebuild the model from the spec
+ vgsl_gn = VGSLModelGenerator(backend="tensorflow")
+ model = vgsl_gn.generate_model(vgsl_spec)
+ model.summary()
+
+By using this functionality, you can quickly share, reproduce, and analyze deep learning models in a concise format.
+
+
diff --git a/_sources/getting_started.rst.txt b/_sources/getting_started.rst.txt
new file mode 100644
index 0000000..91793b6
--- /dev/null
+++ b/_sources/getting_started.rst.txt
@@ -0,0 +1,98 @@
+Getting Started
+===============
+
+Overview
+--------
+
+VGSLify makes it incredibly simple to define, build, and train deep learning models using the Variable-size Graph Specification Language (VGSL). VGSL strings serve as compact representations of neural network architectures, allowing you to build models in a single line.
+
+VGSLify abstracts the complexity of backend-specific syntax, enabling seamless switching between TensorFlow and, in future releases, PyTorch. This flexibility allows you to focus on model architecture and training without worrying about framework-specific implementations.
+
+What is a VGSL Specification?
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A VGSL specification string concisely defines a neural network's architecture. The string encodes all layers, including input, convolutional layers, pooling, fully connected layers, and more. Each part of the string corresponds to a different component of the model.
+
+For example, the following VGSL string defines a simple convolutional neural network:
+
+``None,28,28,1 Cr3,3,32 Mp2,2,2,2 Rc Fr64 D20 Fs10``
+
+This string represents a model with an input layer, a convolutional layer, a max pooling layer, a reshape layer, a dense (fully connected) layer, dropout, and an output layer. The model's structure is encoded entirely within this single line.
+
+Key functionality of VGSLify includes:
+
+- **Building models with a single line**: You can define complex architectures with a VGSL string, reducing the need for verbose code.
+- **Switching between TensorFlow and PyTorch**: VGSLify supports both TensorFlow and (planned) PyTorch, allowing you to easily switch between backends.
+
+Simple Example: Building a Model
+--------------------------------
+
+Let’s walk through building a simple deep learning model using VGSLify.
+
+1. **Import the VGSLModelGenerator**:
+
+ The `VGSLModelGenerator` class is the core component for building models from VGSL strings. Begin by importing it:
+
+ .. code-block:: python
+
+ from vgslify.generator import VGSLModelGenerator
+
+2. **Define the VGSL Specification String**:
+
+ The VGSL spec string encodes the structure of the model. In this example, we will define a simple convolutional neural network suitable for handling MNIST digit images (28x28 grayscale):
+
+ .. code-block:: python
+
+ vgsl_spec = "None,28,28,1 Cr3,3,32 Mp2,2,2,2 Rc2 Fr64 D20 Fs10"
+
+3. **Build and View the Model**:
+
+ Initialize the `VGSLModelGenerator` and use it to build the model based on the VGSL spec string:
+
+ .. code-block:: python
+
+ vgsl_gn = VGSLModelGenerator(backend="tensorflow") # Set backend to TensorFlow
+ model = vgsl_gn.generate_model(vgsl_spec)
+ model.summary() # View the model architecture
+
+ This will generate the model and display a summary of its architecture, including all layers defined by the VGSL spec string.
+
+Explanation of Layers
+---------------------
+
+Let’s break down the layers defined by the VGSL specification string in our example:
+
+- **Input Layer**: ``None,28,28,1``
+ - This defines the input shape of the model, which corresponds to grayscale images of size 28x28 pixels. The first dimension (`None`) allows for a variable batch size.
+
+- **Convolutional Layer**: ``Cr3,3,32``
+ - This adds a 2D convolutional layer with a 3x3 kernel and 32 output filters, using ReLU activation (`r` for ReLU).
+
+- **MaxPooling Layer**: ``Mp2,2,2,2``
+ - This reduces the spatial dimensions by applying 2x2 max pooling with a stride of 2x2, which downsamples the input by taking the maximum value over each 2x2 window.
+
+- **Reshape Layer**: ``Rc2``
+ - Reshapes the output from the previous layer, collapsing the spatial dimensions into a single vector suitable for fully connected layers.
+
+- **Fully Connected Layer**: ``Fc64``
+ - Adds a fully connected layer (dense layer) with 64 units.
+
+- **Dropout Layer**: ``D20``
+ - Applies dropout with a 20% rate to prevent overfitting by randomly setting a portion of the inputs to zero during training.
+
+- **Output Layer**: ``Fs10``
+ - Represents the output layer with 10 units (for 10 classes, such as the digits in MNIST) using softmax activation.
+
+This VGSL string provides a concise, human-readable format for specifying complex model architectures. VGSLify automatically translates this specification into a deep learning model that can be trained using TensorFlow.
+
+Next Steps
+----------
+
+Once you’ve built and explored a basic model, you can dive deeper into VGSLify's capabilities. Follow the [tutorials](tutorials.html) to explore more advanced use cases such as:
+
+- Using different VGSL spec strings to define custom architectures.
+- Switching between TensorFlow and PyTorch backends (PyTorch support coming soon).
+- Integrating VGSLify models into larger deep learning workflows.
+
+Check out the `API reference