momentarek1/Text-to-Face_Generation
๐งโ๐จ Text-to-Face Generation with BERT, GAN & CelebA
A deep learning project for text-to-face image generation, where natural-language descriptions are converted into realistic facial images using Sentence-BERT embeddings and a conditional Generative Adversarial Network (GAN).
The project contains two text-conditioned face generation models:
- Baseline Text-to-Face Generator โ a lightweight conditional generator.
- Attention-based Text-to-Face GAN โ an improved architecture using Self-Attention, Spectral Normalization, and a conditional Discriminator.
๐ Project Overview
The goal of this project is to generate a face image from a textual description.
For example, given:
"The female has high cheekbones. Her hair is black. She has arched eyebrows, a big nose and bushy eyebrows. She is young, smiling and wearing lipstick."
the model attempts to generate a corresponding face.
The overall pipeline is:
Text Description
โ
โผ
Sentence-BERT
โ
โผ
768-D Text Embedding
โ
โผ
Text Conditioning
โ
+
Random Noise
โ
โผ
Generator
โ
โผ
Generated FaceThe project uses the CelebA dataset with natural-language descriptions associated with facial images.
๐ฏ Objectives
The project aims to explore:
- Text-to-image generation
- Conditional GANs
- Text embeddings
- Sentence-BERT
- Face generation
- GAN architecture design
- Self-Attention
- Spectral Normalization
- Conditional Discriminators
- Image-text matching
- Generative model training
๐๏ธ Dataset
The project uses the CelebA (CelebFaces Attributes Dataset).
CelebA contains large-scale celebrity face images together with facial attribute annotations.
The project additionally uses textual descriptions generated from the facial attributes.
Dataset sources
- Kaggle CelebA Dataset
- CUHK Multimedia Lab โ CelebA
The project expects a dataset containing:
Face Images
+
Text Descriptions
+
CelebA Attribute Information๐ Text Descriptions
Each image is associated with one or more natural-language descriptions.
Example:
The female has pretty high cheekbones and an oval face.
She has brown hair.
She has arched eyebrows and a pointy nose.
She is smiling, seems attractive and young.
She has rosy cheeks and heavy makeup.
She is wearing earrings and lipstick.Another example:
He wears a 5 o'clock shadow.
His hair is brown and straight.
He has a slightly open mouth and a pointy nose.
He looks attractive and young and is smiling.
He is wearing a necktie.These descriptions provide the semantic information used to condition the image generator.
๐ง Text Encoder
The project uses:
SentenceTransformerwith:
all-mpnet-base-v2The model converts each textual description into a 768-dimensional semantic embedding.
SentenceTransformer("all-mpnet-base-v2")The descriptions are split into sentences and each sentence is encoded individually.
The resulting sentence embeddings are then averaged:
Text
โ
โโโ Sentence 1 โโโบ Embedding
โโโ Sentence 2 โโโบ Embedding
โโโ Sentence 3 โโโบ Embedding
โโโ Sentence N โโโบ Embedding
โ
โผ
Mean Embedding
โ
โผ
768-DThis produces a fixed-size representation regardless of the number of sentences.
๐ข Text Embedding
The initial embedding size is:
768The embedding is then reduced to:
256using a projection layer.
Sentence-BERT
โ
โผ
768 dimensions
โ
โผ
Linear Layer
โ
โผ
256 dimensions๐๏ธ Model 1 โ Baseline Text-to-Face Generator
The first model is a conditional image generator that combines:
- Random noise
- Text embeddings
- Transposed convolution layers
- Batch Normalization
- ReLU / LeakyReLU
- Tanh output
The model generates RGB face images.
Architecture
The input consists of:
Random Noise
100 dimensionsand:
Text Embedding
768 dimensionsThe text embedding is projected to:
256 dimensionsThe generator then concatenates the noise and text representation.
Text Description
โ
โผ
Sentence-BERT
โ
โผ
768-D
โ
โผ
Projection
โ
โผ
256-D
โ
โโโโโโโโโโโโโโ
โ โ
โผ โผ
Random Noise Text
100-D 256-D
โ โ
โโโโโโโฌโโโโโโโ
โผ
Conditional Input
โ
โผ
ConvTranspose2D
โ
โผ
4 ร 4
โ
โผ
8 ร 8
โ
โผ
16 ร 16
โ
โผ
32 ร 32
โ
โผ
64 ร 64
โ
โผ
RGB ImageGenerator Configuration
model = Generator(
100, # noise size
128, # feature size
3, # RGB channels
768, # embedding size
256 # reduced embedding size
)Main parameters
๐ผ๏ธ Generated Image Resolution
The baseline generator progressively upsamples the feature representation:
4 ร 4
โ
8 ร 8
โ
16 ร 16
โ
32 ร 32
โ
64 ร 64
โ
128 ร 128The final output is an RGB face image.
๐พ Pretrained Generator
A trained generator checkpoint can be loaded using:
model.load_state_dict(
torch.load(
"generator_50k.pth",
map_location="cpu"
)
)
model.eval()This allows the model to generate faces directly from new text descriptions without retraining.
๐งช Baseline Inference
Example:
test_noise = torch.randn(
size=(1, 100)
)
test_embeddings = sentence_encoder.convert_text_to_embeddings([
"The female has pretty high cheekbones and an oval face. "
"She has brown hair. She has arched eyebrows and a pointy nose. "
"She is smiling, seems attractive, young, has rosy cheeks and heavy makeup. "
"She is wearing earrings and lipstick."
])
test_image = model(
test_noise,
test_embeddings
)The generated image is then visualized using torchvision.
๐ง Model 2 โ Attention-Based Text-to-Face GAN
The second model is a more advanced conditional GAN architecture.
It contains:
- Conditional Generator
- Conditional Discriminator
- Sentence-BERT
- Self-Attention
- Spectral Normalization
- Batch Normalization
- Transposed Convolution
- Conditional image-text discrimination
The architecture is designed to improve image quality and capture long-range spatial relationships in facial features.
๐๏ธ Generator Architecture
The second generator receives:
Text Embedding
+
Random NoiseThe text embedding is processed through:
768
โ
256
โ
100The resulting representation is combined with the random noise through element-wise multiplication.
concat_input = torch.mul(
noise,
encoded_text
)Generator Pipeline
Text
โ
โผ
Sentence-BERT
โ
โผ
768-D
โ
โผ
Linear
โ
โผ
256-D
โ
โผ
Linear
โ
โผ
100-D
โ
โ
Random Noise โโโโโโโโโค
โผ
Element-wise
Multiplication
โ
โผ
1 ร 1
โ
โผ
4 ร 4 Feature
โ
โผ
8 ร 8 Feature
โ
โผ
16 ร 16 Feature
โ
โผ
Self-Attention
โ
โผ
32 ร 32 Feature
โ
โผ
Self-Attention
โ
โผ
64 ร 64 Feature
โ
โผ
Self-Attention
โ
โผ
128 ร 128 Image๐๏ธ Self-Attention
The generator includes custom Self-Attention modules.
The attention mechanism allows the model to establish relationships between distant spatial locations.
This is useful for face generation because facial features are not completely independent.
For example:
Eyes
โ
โโโโโโโโบ Nose
โ
โโโโโโโโบ Mouth
โ
โโโโโโโโบ Face ShapeInstead of only processing local convolutional features, Self-Attention allows the network to model broader spatial relationships.
๐ฌ Self-Attention Architecture
The module uses three projections:
Query
Key
Valueimplemented using convolution layers:
self.query_conv
self.key_conv
self.value_convAttention scores are calculated using matrix multiplication:
Query ร Key
โ
โผ
Softmax
โ
โผ
Attention Map
โ
โผ
ValueThe attention output is then combined with the original feature map through a learnable parameter:
Output = ฮณ ร Attention + Input๐ก๏ธ Spectral Normalization
The advanced architecture also implements Spectral Normalization for convolutional layers.
Spectral normalization constrains the magnitude of the network weights and helps stabilize GAN training.
It is applied to:
Generator
โ
โโโ ConvTranspose2D
โโโ ConvTranspose2D
Discriminator
โ
โโโ Conv2DConceptually:
Convolution
โ
โผ
Spectral Normalization
โ
โผ
Controlled Weight Magnitude
โ
โผ
More Stable GAN Training๐ต๏ธ Discriminator
The discriminator determines whether an image is:
Real
or
Fakebut this model also receives the corresponding text description.
Therefore, it performs conditional discrimination.
Instead of asking only:
Is this image real?
the discriminator effectively evaluates:
Is this image realistic and consistent with the given text?
๐ Conditional Discriminator
The architecture is:
Image
โ
โผ
CNN Encoder
โ
โผ
Image Features
โ
โ
Text โโโบ Sentence-BERT
โ
โผ
Text Encoder
โ
โผ
Text Features
โ
โโโโโโโดโโโโโโ
โ โ
โโโโโโโฌโโโโโโ
โผ
Image + Text
Features
โ
โผ
CNN Layers
โ
โผ
Real / Fake Score๐งฉ Wrong Image Training
An important part of the discriminator training is the use of wrong image-text pairs.
For each text description:
Correct Pair
Text โโโโโโโโโโบ Correct Faceand:
Incorrect Pair
Text โโโโโโโโโโบ Different FaceThe discriminator learns to distinguish between:
Real Image + Correct Textand:
Wrong Image + Text
Fake Image + TextThis encourages the generated image to be semantically related to the description.
๐ Dataset Pipeline
The custom dataset returns:
true_image
true_text
wrong_imageThe pipeline is:
CelebA
โ
โโโโโโโโโโบ Real Image
โ
โโโโโโโโโโบ Text Description
โ
โโโโโโโโโโบ Random Wrong ImageImages are resized to:
128 ร 128and normalized using:
transforms.Normalize(
mean=(0.5),
std=(0.5)
)โ๏ธ Training Configuration
The advanced model uses:
โ๏ธ GAN Training
The training process alternates between the Generator and Discriminator.
Text
โ
โผ
Text Encoder
โ
โผ
Embeddings
โ
โผ
Generator
โฒ
โ
Random Noise
โ
โผ
Fake Image
โ
โโโโโโโโโดโโโโโโโโโ
โ โ
โผ โผ
Generator Discriminator
Loss โ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
Real Image Wrong Image Fake Image๐ฏ Generator Objective
The generator attempts to fool the discriminator.
Text + Noise
โ
โผ
Generator
โ
โผ
Fake Face
โ
โผ
Discriminator
โ
โผ
Real?The generator loss is calculated using:
nn.BCELoss()and attempts to make the discriminator classify generated images as real.
๐ก๏ธ Discriminator Objective
The discriminator receives three types of examples:
1. Real Image + Correct Text
Expected:
12. Wrong Image + Text
Expected:
03. Generated Image + Text
Expected:
0Therefore:
Discriminator Loss
โ
โโโ Real Loss
โโโ Wrong Pair Loss
โโโ Fake Loss๐ Experiment Tracking
The project uses:
Weights & Biases (W&B) for experiment tracking.
wandb.init(
project="text-to-face",
name="n-sagan"
)The following metrics are tracked:
Generator Loss
Discriminator Loss
Generated ImagesGenerated images are logged after each configured epoch.
๐ผ๏ธ Visualization
The project visualizes generated images using:
Matplotlib
+
TorchvisionGenerated images can be arranged into grids:
torchvision.utils.make_grid(
output,
normalize=True
)This makes it possible to monitor image quality during training.
๐ฌ Model Comparison
The project contains two approaches:
๐ Overall Architecture
Text Description
โ
โผ
Sentence-BERT
all-mpnet-base-v2
โ
โผ
768-D Embedding
โ
โโโโโโโโโโโโโดโโโโโโโโโโโโ
โ โ
โผ โผ
Baseline Model Attention GAN
โ โ
โ Text Projection
โ โ
โ โผ
โ Random Noise
โ โ
โ โผ
โ Generator
โ โ
โ โโโโโโโโโโดโโโโโโโโโ
โ โ โ
โ โผ โผ
โ Self-Attention Spectral Norm
โ โ
โ โผ
โ Generated Face
โ โ
โ โผ
โ Discriminator
โ โฒ
โ โ
โ Real / Wrong
โ Images
โ
โผ
Generated Face๐ ๏ธ Technologies
Deep Learning
- PyTorch
- Torchvision
- PyTorch Neural Networks
Natural Language Processing
- Sentence Transformers
all-mpnet-base-v2- Text Embeddings
Computer Vision
- OpenCV
- PIL
- Torchvision
- Matplotlib
Machine Learning
- NumPy
- Pandas
GAN / Generative AI
- Conditional GAN
- Self-Attention
- Spectral Normalization
- Transposed Convolution
Experiment Tracking
- Weights & Biases
Dataset
- CelebA
๐ฆ Installation
Clone the repository:
git clone https://github.com/kad99kev/FGTD.gitMove into the project directory:
cd FGTDInstall dependencies:
pip install -r requirements.txtInstall the main deep-learning dependencies if required:
pip install torch torchvisionInstall Sentence Transformers:
pip install sentence-transformersInstall experiment tracking:
pip install wandb๐ Running the Project
1. Load the Text Encoder
from sentence_transformers import SentenceTransformer
sentence_encoder = SentenceTransformer(
"all-mpnet-base-v2"
)2. Generate an Image from Text
Prepare a text description:
text = [
"The female has high cheekbones and black hair. "
"She is young and smiling."
]Convert it into an embedding:
Text
โ
Sentence-BERT
โ
768-D EmbeddingGenerate a random latent vector:
noise = torch.randn(
1,
100
)Then pass both into the generator:
image = generator(
noise,
text_embeddings
)๐งช Example Prompts
Female Face
The female has pretty high cheekbones and an oval face.
Her hair is black.
She has arched eyebrows and a pointy nose.
She is smiling and looks young.
She is wearing earrings and lipstick.Male Face
The man is young and attractive.
He has brown straight hair and a pointy nose.
He is smiling and wearing a necktie.Different Facial Attributes
The man has a double chin and high cheekbones.
He has black hair and big lips.
He looks young.๐ Suggested Repository Structure
Text-to-Face-GAN/
โ
โโโ README.md
โโโ requirements.txt
โ
โโโ notebooks/
โ โโโ baseline_text_to_face.ipynb
โ โโโ attention_text_to_face_gan.ipynb
โ
โโโ models/
โ โโโ generator.py
โ โโโ discriminator.py
โ โโโ attention.py
โ โโโ spectral_norm.py
โ
โโโ text_encoder/
โ โโโ sentence_encoder.py
โ
โโโ dataset/
โ โโโ text_5_descr_celeba.csv
โ โโโ list_attr_celeba.csv
โ
โโโ checkpoints/
โ โโโ generator_50k.pth
โ
โโโ outputs/
โ โโโ generated_faces/
โ
โโโ results/
โโโ wandb/๐ง Key Concepts Demonstrated
Natural Language Processing
- Sentence Embeddings
- Sentence-BERT
- Semantic Representation
- Text Conditioning
Computer Vision
- Face Generation
- Image Preprocessing
- Image Normalization
- Image Visualization
Deep Learning
- PyTorch
- CNNs
- Transposed Convolution
- Batch Normalization
- ReLU
- Tanh
Generative AI
- GANs
- Conditional GANs
- Text-to-Image Generation
- Latent Noise
- Generator / Discriminator Training
Advanced GAN Techniques
- Self-Attention
- Spectral Normalization
- Conditional Discrimination
- Wrong Image-Text Pairing
๐ Important Design Decisions
Why Sentence-BERT?
Instead of treating text as individual words, Sentence-BERT provides a semantic representation of the entire description.
Natural Language
โ
Semantic Embedding
โ
768-D Vector
โ
Generator ConditioningThis allows descriptions containing multiple facial attributes to be represented in a compact vector.
Why Conditional GAN?
A normal GAN learns:
Random Noise โ ImageThis project instead learns:
Random Noise + Text โ ImageTherefore, the generated image can be influenced by the supplied description.
Why Self-Attention?
Convolutional layers are excellent at learning local patterns, while Self-Attention helps the network model relationships between distant regions of an image.
This can be useful when generating coherent facial structures.
Why Spectral Normalization?
GAN training can be unstable.
Spectral Normalization helps constrain the network's weight matrices and can improve training stability, particularly in the discriminator.
๐ Expected Workflow
CelebA Dataset
โ
โผ
Image + Caption
โ
โโโโโโโโโโโดโโโโโโโโโโ
โ โ
โผ โผ
Image Text
โ โ
โ โผ
โ Sentence-BERT
โ โ
โ โผ
โ 768-D
โ โ
โ โผ
โ Projection
โ โ
โ โผ
โ Text Code
โ โ
โโโโโโโโโโโโฌโโโโโโโโโ
โผ
GAN
โ
โโโโโโโโโโโโดโโโโโโโโโโโ
โผ โผ
Generator Discriminator
โ โ
โผ โ
Fake Face โโโโโโโโโโโโโโโโโค
โ
Real Face โโโโโโโโโโโโโโโโโค
โ
Wrong Face โโโโโโโโโโโโโโโโค
โผ
Real / Fakeโ ๏ธ Implementation Notes
The project is primarily an experimental research implementation.
Several aspects can be improved for a cleaner production/research implementation:
- Separate training and inference scripts.
- Add explicit validation/testing datasets.
- Save both Generator and Discriminator checkpoints.
- Add automatic checkpoint recovery.
- Track additional GAN metrics.
- Evaluate generated image quality quantitatively.
- Use a dedicated configuration file.
- Avoid hard-coded CUDA calls and use the configured device consistently.
- Add reproducible random seeds.
- Add automated experiment logging.
For example, instead of:
generator.cuda()a more portable approach is:
generator.to(cfg.device)This allows the project to run on either GPU or CPU.
๐ Future Improvements
Possible extensions include:
- Increase image resolution to 256ร256.
- Experiment with larger text encoders.
- Use CLIP-based text-image alignment.
- Add perceptual loss.
- Add text-image similarity metrics.
- Add FID evaluation.
- Add Inception Score.
- Improve caption diversity.
- Experiment with different GAN architectures.
- Compare Self-Attention vs standard convolution.
- Implement progressive image generation.
- Add mixed-precision training.
- Add distributed training.
- Improve dataset balancing.
- Add automated checkpointing.
- Build a web interface for text-to-face generation.
๐ Learning Outcomes
This project provides practical experience with:
- Text-to-image generation
- Conditional GANs
- PyTorch
- Sentence Transformers
- BERT-based embeddings
- CNN architectures
- Transposed convolution
- GAN optimization
- Generator/Discriminator training
- Self-Attention
- Spectral Normalization
- CelebA preprocessing
- Image-text conditioning
- Experiment tracking with W&B
๐ Keywords
Text-to-Image
Text-to-Face
Face Generation
Generative AI
GAN
Conditional GAN
cGAN
PyTorch
Sentence-BERT
Sentence Transformers
all-mpnet-base-v2
CelebA
Computer Vision
Deep Learning
Self-Attention
Spectral Normalization
Image Generation
Natural Language Processing
Multimodal AI
Generative Models๐ Disclaimer
This project is intended for educational, research, and experimental purposes.
Generated faces are synthetic outputs produced by a machine-learning model and should not be interpreted as photographs or evidence of real individuals.
๐จโ๐ป Project Summary
Text-to-Face Generation with BERT & Conditional GANs is a multimodal generative AI project that connects natural-language descriptions with facial image generation.
The project progresses from a baseline text-conditioned generator to an advanced GAN architecture incorporating Sentence-BERT embeddings, Self-Attention, Spectral Normalization, and a conditional Discriminator.
Text
โ
Sentence-BERT
โ
768-D Embedding
โ
Text Conditioning
+
Random Noise
โ
Generator
โ
Generated Face
โ
Conditional Discriminator
โ
GAN TrainingThe project demonstrates how NLP and Computer Vision can be combined into a single generative AI pipeline for text-guided face synthesis.
