Chapter 5 — Sub-chapter 5.7

Fine-Tuning & Prompt Engineering

A pre-trained language model is a general-purpose engine. To make it useful for civil engineering, you have two levers: fine-tuning — adjusting the model's internal weights on domain-specific data — and prompt engineering — carefully structuring your input so the unchanged model produces expert-quality output. Knowing when to pull each lever is the difference between a prototype and a production tool.

40 min read 2 interactive demos 4 quiz questions

The Transfer Learning Paradigm

Training a large language model from scratch requires millions of GPU-hours, terabytes of text, and budgets measured in millions of dollars. Fortunately, the knowledge a model acquires during pre-training — grammar, facts, reasoning patterns — is transferable. Instead of starting from zero, you take a pre-trained model and adapt it to your specific task. This is transfer learning, and it is the foundation of every practical LLM deployment in engineering today.

Transfer learning works because the lower layers of a neural network learn general features (syntax, common word associations), while the higher layers learn increasingly abstract and task-specific representations. By keeping the general knowledge intact and only adjusting the top layers — or by guiding the model through prompts — you can achieve expert-level performance on domain tasks with a fraction of the original training cost.

The modern LLM workflow follows a two-stage (sometimes three-stage) pipeline. Stage 1: Pre-train on a massive, general corpus (books, web pages, code). Stage 2: Fine-tune on a curated, task-specific dataset (building code Q&A, inspection reports, structural analysis queries). An optional Stage 3 uses reinforcement learning from human feedback (RLHF) to align the model with human preferences for safety, helpfulness, and factual accuracy.

Prerequisites

This sub-chapter assumes familiarity with the Transformer architecture (Sub-chapter 5.3), encoder models like BERT (Sub-chapter 5.4), decoder models like GPT (Sub-chapter 5.5), and tokenization/embeddings (Sub-chapter 5.6). We will reference attention mechanisms, model parameters, and training loss concepts throughout.

The Civil Engineering Analogy

Civil Engineering Analogy

Fine-tuning is like retrofitting an existing structure. Imagine a general-purpose office building (the pre-trained model). It has a solid foundation, structural frame, and building services. To convert it into a structural testing laboratory, you do not demolish and rebuild from scratch. Instead, you reinforce specific floors for heavy equipment loads, install crane rails, add vibration isolation pads, and upgrade the electrical capacity. The core structure remains, but targeted modifications make it fit for the new purpose. That is fine-tuning: targeted weight adjustments that specialise a general model.

Prompt engineering is like writing a detailed work order for an experienced contractor. The contractor (model) already has the skills and knowledge. The quality of the output depends entirely on how clearly you specify the scope, standards, tolerances, and deliverables. A vague instruction like "fix the crack" gets a different (worse) result than "Repair the 2mm-wide flexural crack at mid-span of beam B3-2 using epoxy injection per ACI 224.1R, document before/after with photographs, and reference clause 4.3.2 of the repair specification."

Pre-Training vs Fine-Tuning

Pre-training and fine-tuning differ in scale, data, objective, and cost. Understanding these differences is essential for making practical decisions about how to deploy LLMs in engineering workflows.

Pre-Training vs Fine-Tuning Comparison

Dimension Pre-Training Fine-Tuning
Data Terabytes of general text Megabytes of task-specific data
Objective Next-token prediction / masked language modelling Task-specific (classification, Q&A, generation)
Parameters All weights trained from random init All or a subset of weights updated
Cost $1M–$100M+ (GPU clusters, months) $10–$10,000 (single GPU, hours to days)
Who does it Large AI labs (OpenAI, Google, Meta) Any team with a GPU and domain data

The key insight is that pre-training captures general knowledge, while fine-tuning injects domain expertise. A model that has been pre-trained on the internet knows what concrete is; a model fine-tuned on ACI 318 knows the exact provisions for minimum reinforcement ratios in flexural members. The pre-trained knowledge provides the reasoning scaffolding; fine-tuning fills in the specialised details.

Full Fine-Tuning

In full fine-tuning, every parameter of the pre-trained model is updated during training on the downstream dataset. For a 7-billion parameter model, this means computing gradients for all 7 billion weights at every training step. The model is initialised with the pre-trained weights rather than random values, so it starts from a strong baseline and converges rapidly.

Full Fine-Tuning Requirements

  • Memory: ~4x model size in FP32 (weights + gradients + optimizer states). A 7B model needs ~112 GB of GPU memory
  • Hardware: Multiple high-end GPUs (A100/H100) or cloud instances
  • Data: Typically 10,000–100,000+ curated examples for robust specialisation
  • Risk: Catastrophic forgetting — the model may lose general capabilities as it over-specialises on the fine-tuning data
  • Output: A complete new copy of the model (same size as original)

Full fine-tuning delivers the highest potential performance because every weight can shift to accommodate the new domain. However, the resource requirements are prohibitive for most civil engineering teams. Storing, serving, and versioning multiple fully fine-tuned copies of a large model is expensive. This is what motivated the development of parameter-efficient methods.

Parameter-Efficient Fine-Tuning (PEFT)

Parameter-efficient fine-tuning (PEFT) methods freeze most of the pre-trained weights and train only a small set of additional or selected parameters. This reduces memory requirements by 10x or more, enables fine-tuning on a single consumer GPU, and avoids catastrophic forgetting because the original weights remain intact.

LoRA (Low-Rank Adaptation)

How LoRA Works

LoRA (Hu et al., 2021) is the most popular PEFT method. The core idea: instead of updating a full weight matrix W (d × d), LoRA freezes W and adds a parallel low-rank decomposition: ΔW = B × A, where A is (d × r) and B is (r × d), with rank r << d (typically r = 4, 8, or 16).

  • Trainable parameters: Only A and B matrices (~0.1–1% of total parameters)
  • Memory: ~1.2x model size (frozen weights + small adapters)
  • Inference: Merge ΔW into W after training — zero latency overhead
  • Swappable: Multiple LoRA adapters can share one base model (one for building codes, one for geotechnical reports, one for cost estimation)

QLoRA (Quantized LoRA)

QLoRA (Dettmers et al., 2023) pushes efficiency further by quantizing the frozen base model to 4-bit precision while keeping the LoRA adapters in higher precision (BF16/FP16). This reduces the memory footprint to roughly 6 GB for a 7B model — feasible on a single consumer GPU with 8 GB of VRAM. The quality loss from quantization is surprisingly small, typically within 1–2% of full fine-tuning performance on benchmarks.

Adapter Layers

Before LoRA, adapter-based methods (Houlsby et al., 2019) were the standard PEFT approach. Adapters insert small trainable bottleneck layers between existing Transformer blocks. Each adapter consists of a down-projection, a nonlinearity, and an up-projection. Only the adapter parameters are trained; the original Transformer weights are frozen.

Adapters vs LoRA

  • Adapters add sequential bottleneck layers — they introduce latency at inference because the extra layers must be computed
  • LoRA adds parallel low-rank matrices — they can be merged into the original weights, adding zero inference cost
  • Both achieve similar quality, but LoRA's merge-ability gives it a practical advantage for deployment
Civil Engineering Analogy

PEFT is like installing modular attachments on heavy equipment. A general-purpose excavator (the pre-trained model) can accept different attachments: a bucket for earthmoving, a breaker for demolition, a grapple for sorting debris. The base machine stays unchanged. Swapping an attachment (LoRA adapter) takes minutes, not weeks, and you do not need to buy a separate excavator for each task. Full fine-tuning, by contrast, is like permanently welding a breaker onto the boom — great for demolition, useless for anything else.

Instruction Tuning

A base pre-trained model predicts the next token but does not follow instructions. If you write "Summarise the following inspection report:", the base model might continue with more report text rather than producing a summary. Instruction tuning fine-tunes the model on thousands of (instruction, response) pairs so it learns to follow directives.

Instruction Tuning Dataset Example (CE Domain)

Instruction: "Calculate the factored moment capacity of a rectangular beam with b=300mm, d=500mm, As=1500mm2, fy=415MPa, f'c=28MPa per ACI 318-19."

Response: "Step 1: Compute the depth of the stress block...
a = As * fy / (0.85 * f'c * b)
a = 1500 * 415 / (0.85 * 28 * 300) = 87.2 mm
Step 2: Compute phi*Mn...
Mn = As * fy * (d - a/2) = 1500 * 415 * (500 - 43.6) = 284.1 kN-m
phi*Mn = 0.9 * 284.1 = 255.7 kN-m"

The most impactful instruction-tuned models — ChatGPT, Claude, Gemini — were trained on hundreds of thousands of such pairs covering diverse tasks. For civil engineering specialisation, you can create a smaller instruction dataset (1,000–10,000 pairs) focused on code compliance checks, structural calculations, material specifications, and report generation.

RLHF: Reinforcement Learning from Human Feedback

Instruction tuning teaches a model what to say; RLHF teaches it how to say it in a way humans prefer. The three-step RLHF pipeline is used by ChatGPT, Claude, and most modern assistant models:

The RLHF Pipeline

  1. Supervised Fine-Tuning (SFT): Fine-tune the base model on high-quality (prompt, response) pairs written by human experts
  2. Reward Model Training: Generate multiple responses to each prompt, have human labellers rank them by quality, and train a reward model to predict human preference scores
  3. RL Optimisation (PPO): Use the reward model as a scoring function and optimise the SFT model via Proximal Policy Optimisation to maximise the predicted reward while staying close to the SFT baseline (KL penalty)

RLHF is why ChatGPT feels helpful, polite, and structured compared to a raw GPT-3 completion. For civil engineering, RLHF could theoretically train a model to prefer responses that cite specific code clauses, show calculation steps, and flag safety-critical assumptions — but the cost and complexity of RLHF mean it is currently practical only for large AI labs. Most engineering teams will use SFT (instruction tuning) combined with prompt engineering as their primary adaptation strategies.

Prompt Engineering Fundamentals

Prompt engineering is the art and science of designing input text that guides a language model to produce the desired output without modifying the model's weights. It is the lowest-cost, fastest-to-iterate adaptation strategy, and it is often sufficient for many civil engineering tasks when using a capable base model like GPT-4 or Claude.

Zero-Shot Prompting

Zero-Shot: No Examples Needed

In zero-shot prompting, you describe the task directly without providing any examples. The model relies entirely on its pre-trained knowledge.

Prompt: "Classify the following defect as structural or cosmetic: 'Horizontal crack along mortar joints at third-floor level, width 3mm, visible on exterior facade.'"

Zero-shot works well for tasks the model encountered frequently during pre-training. It struggles with domain-specific formats, niche terminology, or tasks requiring a specific output structure.

Few-Shot Prompting

Few-Shot: Learning from Examples

Few-shot prompting includes 2–5 worked examples before the actual query. The model uses in-context learning to mimic the pattern established by the examples.

Example 1:
Defect: "Hairline crack in plaster, <0.1mm" → Cosmetic
Example 2:
Defect: "Diagonal crack at beam-column joint, 5mm" → Structural
Example 3:
Defect: "Paint peeling on ceiling" → Cosmetic

Query:
Defect: "Horizontal crack along mortar joints, 3mm" → ?

Few-shot prompting dramatically improves output consistency and format compliance. It is especially powerful for classification, data extraction, and structured output generation.

Chain-of-Thought (CoT) Prompting

Chain-of-Thought: Step-by-Step Reasoning

CoT prompting (Wei et al., 2022) instructs the model to show its reasoning before providing the final answer. This dramatically improves performance on multi-step calculations, logical reasoning, and engineering analysis tasks.

Prompt: "A simply supported beam spans 6m with a UDL of 20 kN/m. Calculate the maximum bending moment. Think step by step."

Response:
Step 1: For a simply supported beam with UDL, M_max = wL^2/8
Step 2: w = 20 kN/m, L = 6 m
Step 3: M_max = 20 * 6^2 / 8 = 20 * 36 / 8 = 90 kN-m
The maximum bending moment is 90 kN-m at mid-span.

System Prompts

A system prompt sets the model's persona, constraints, and output conventions before the user's query. It persists across the entire conversation and is invisible to the end user in most deployments.

System Prompt Example for CE Applications

"You are a senior structural engineer with 20 years of experience. When answering questions:
1. Always cite the relevant design code clause (ACI, Eurocode, IS)
2. Show all calculation steps with units
3. State assumptions explicitly
4. Flag any safety-critical limitations
5. Use SI units unless the user specifies otherwise
6. Format output in markdown with section headers"

Output Formatting

Specifying the desired output format in the prompt is one of the most effective prompt engineering techniques. Instead of hoping the model guesses your format, explicitly request it:

Output Formatting Strategies

  • JSON output: "Return a JSON object with keys: member_id, load_kN, moment_kNm, status"
  • Tabular: "Present results in a markdown table with columns: Element, Demand, Capacity, DCR, Pass/Fail"
  • Report format: "Structure your response as: Executive Summary, Findings, Recommendations, Code References"
  • Constrained vocabulary: "Classify as exactly one of: PASS, FAIL, REQUIRES_REVIEW"

Prompt Templates for CE Tasks

Effective prompts for civil engineering tasks follow a consistent structure: role (who the model should be), context (relevant background data), task (what to do), format (how to present the output), and constraints (limitations and standards to respect). Below are templates for three common CE applications.

Template 1: Structural Analysis Query

# Role
You are a structural analysis assistant.

# Context
Member: {member_type}, Span: {span}m, Section: {section}
Loading: {dead_load} kN/m (DL), {live_load} kN/m (LL)
Code: {design_code}

# Task
Check flexural adequacy. Show factored load combinations,
demand calculation, capacity calculation, and DCR.

# Format
Return a JSON object with fields: factored_load_kNm,
demand_kNm, capacity_kNm, dcr, status ("PASS"/"FAIL")

Template 2: Inspection Report Generator

# Role
You are a certified building inspector.

# Observations
{list_of_field_observations}

# Task
Generate a standardised inspection report with:
1. Executive Summary (2–3 sentences)
2. Defect Table (ID, Location, Type, Severity, Photo Ref)
3. Recommended Actions (prioritised by severity)
4. Code References for each defect

# Constraints
Severity levels: Critical / Major / Minor / Cosmetic.
Reference only {applicable_code} provisions.

Template 3: Material Specification Lookup

# Role
You are a materials engineer.

# Query
Material: {material_name}
Application: {intended_use}
Environment: {exposure_class}

# Task
Provide the specification including: grade, min strength,
chemical composition limits, applicable ASTM/EN standard,
and any special requirements for the given exposure class.

Fine-Tuning on Building Codes

Building codes are the most natural fine-tuning target for civil engineering LLMs. Codes like ACI 318, Eurocode 2, IS 456, and AS 3600 contain thousands of prescriptive rules, equations, tables, and commentary that a general-purpose model may not reliably recall. Fine-tuning on structured code-clause data teaches the model to cite specific provisions accurately.

Building a Code Compliance Dataset

  1. Extract clauses: Parse code documents into individual clause-level records with metadata (clause number, section, topic)
  2. Generate Q&A pairs: For each clause, create 3–5 natural-language questions whose answers require that clause. Example: "What is the minimum concrete cover for a beam in moderate exposure?" → clause 4.4.1.2
  3. Add calculation examples: For clauses containing equations, generate worked examples with numerical inputs and step-by-step solutions
  4. Include edge cases: Add examples where clauses interact (e.g., minimum reinforcement vs maximum spacing requirements)
  5. Quality review: Have a licensed engineer verify all Q&A pairs for correctness and completeness

Fine-Tuning Datasets for Construction / Engineering

Beyond building codes, several data sources are valuable for creating civil engineering fine-tuning datasets:

Potential CE Fine-Tuning Data Sources

  • Design codes & standards: ACI, AISC, Eurocode, IS, BS, AS series — structured clause-level extraction
  • Technical manuals: FHWA bridge inspection guides, PCI design handbooks, steel construction manuals
  • Inspection reports: Historical building and bridge inspection records (anonymised)
  • Project specifications: Standard specification sections (CSI MasterFormat divisions)
  • Academic papers: ASCE, ICE, and fib journals covering structural analysis, geotechnics, and construction management
  • Calculation templates: Worked examples from textbooks and design guides
  • Failure case studies: NIST, ASCE forensic investigation reports with lessons learned

When to Fine-Tune vs Prompt Engineer

This is the most important practical question for any engineering team adopting LLMs. The answer depends on your data, budget, latency requirements, and the complexity of your task.

Decision Framework

Factor Choose Prompting Choose Fine-Tuning
Data available < 100 examples 1,000+ labelled examples
Budget API costs only ($0.01–$0.10/query) GPU costs + engineering time ($100–$10K+)
Iteration speed Minutes to change a prompt Hours to retrain
Task complexity Standard formats, classification, Q&A Niche domain knowledge, custom output styles
Latency Long prompts increase inference time Shorter prompts, faster inference after training
Consistency Moderate (sensitive to wording) High (behaviour baked into weights)
Best Practice

Start with prompt engineering. Most civil engineering tasks can be solved with a well-crafted prompt on a capable model like GPT-4 or Claude. Fine-tune only when you have proven the task is feasible via prompting but need better consistency, lower latency, or reduced per-query cost at scale. The progression is: zero-shot → few-shot → system prompt + CoT → RAG (Sub-chapter 5.8) → fine-tuning.

Demo 1: Prompt Strategy Playground

Select a civil engineering task and a prompting strategy below to see how different prompt approaches change the quality and structure of the model's output. Compare zero-shot, few-shot, and chain-of-thought responses side by side.

Prompt Playground — Compare prompting strategies for CE tasks

Select a task and strategy, then press "Generate" to see the prompt and simulated output side by side.

Demo 2: Fine-Tuning Simulator

Drag the training-step slider to watch a model improve over epochs. The loss curve shows how the training loss decreases as the model sees more examples. Below the curve, sample outputs demonstrate how the model's responses evolve from generic and inaccurate (early training) to precise and domain-aware (late training).

Fine-Tuning Simulator — Watch a model learn building codes
Step 0

Drag the slider or press "Auto-Play" to watch the loss curve decrease and sample outputs improve over training steps.

CE Application: Generating Standardised Inspection Reports

One of the highest-value applications of LLMs in civil engineering is automating the generation of standardised inspection reports. Field engineers collect observations (crack locations, spalling areas, corrosion extent, settlement measurements) and the model transforms these raw notes into a structured, code-referenced report.

Workflow: Field Notes to Report

  1. Input: Engineer enters field observations via a mobile form or voice-to-text
  2. Prompt template: Observations are injected into a pre-built prompt template with role, format, and code reference requirements
  3. Model processing: The LLM classifies defect severity, maps observations to code clauses, and generates narrative text
  4. Review: The engineer reviews, edits, and approves the draft report
  5. Output: Finalised report in standard format (PDF/Word) with defect table, photo references, and recommendations

This workflow reduces report writing time from 2–4 hours to 15–30 minutes while improving consistency across inspectors. The model handles the tedious formatting and code-lookup work; the engineer provides the critical judgment and field knowledge that no model can replace.

CE Applications: Prompt Engineering for Geotechnical & Hydrology

The quality of an LLM's engineering output depends entirely on how you prompt it. Well-structured prompts with code references and constraints produce reliable, verifiable results.

Hydrology Analysis Prompts

Effective prompts specify the return period (100-yr), method (SCS, Rational), watershed data, and output format (peak Q, hydrograph). Adding "cite IDF curves from [source]" grounds the response.

Geotechnical Prompting Patterns

For foundation design, include: soil type, SPT data, water table depth, loading conditions, and applicable code (IS 6403, Terzaghi). Use "step-by-step" to get transparent calculations.

Constraint-Based Safety Prompts

Always include safety constraints: "Ensure FOS ≥ 1.5", "Check against ACI 318", "Flag any assumption not supported by field data." This turns the LLM from a text generator into a verification assistant.

Knowledge Check

Test your understanding of fine-tuning and prompt engineering with these four questions.

Question 1 of 4

What is the primary advantage of LoRA over full fine-tuning?

Question 2 of 4

Which prompt engineering strategy is most effective for multi-step engineering calculations?

Question 3 of 4

When should a civil engineering team choose fine-tuning over prompt engineering?

Question 4 of 4

What role does the reward model play in the RLHF pipeline?

Summary

Key Takeaways

  • Transfer learning: Pre-trained models encode general knowledge that can be adapted to civil engineering tasks through fine-tuning or prompt engineering
  • Full fine-tuning: Updates all model parameters. Maximum flexibility but requires significant GPU memory and risks catastrophic forgetting
  • LoRA / QLoRA: Train only small low-rank adapter matrices (~0.1–1% of parameters). Feasible on a single GPU, swappable across tasks, zero inference overhead after merging
  • Adapters: Insert trainable bottleneck layers. Similar quality to LoRA but add inference latency
  • Instruction tuning: Fine-tuning on (instruction, response) pairs teaches the model to follow directives rather than just predicting the next token
  • RLHF: Reinforcement learning from human feedback aligns model behaviour with human preferences for helpfulness, safety, and accuracy
  • Zero-shot: Describe the task directly. Works for common tasks the model learned during pre-training
  • Few-shot: Provide 2–5 examples. Dramatically improves format consistency and domain accuracy
  • Chain-of-thought: Ask the model to reason step by step. Essential for multi-step calculations and engineering analysis
  • System prompts: Set role, constraints, and output conventions for the entire conversation
  • Start with prompting: Escalate to fine-tuning only when prompting proves insufficient for consistency, latency, or cost requirements at scale

In the next sub-chapter, we will explore RAG & Knowledge Retrieval — how to ground LLM outputs in external knowledge sources (design codes, project documents, specifications) using retrieval-augmented generation, combining the flexibility of prompt engineering with the factual grounding of a curated knowledge base.

Mini case study

Fine-tuning beats prompting: AISC + SkillsetAI steel-connection assistant

In 2024 the American Institute of Steel Construction released an AI assistant trained on the AISC 360 Specification, the Steel Construction Manual, AISC Design Guides and decades of engineering-journal Q&A. The team benchmarked zero-shot GPT-4, few-shot GPT-4, and a fine-tuned GPT-4 variant; the fine-tuned model is the one shipped to members.

0Curated Q/A pairs
0Zero-shot accuracy
0Few-shot accuracy
0Fine-tuned accuracy

Members of AISC ask the same hundred-odd questions every week about prequalified connections, slip-critical bolts, and torsion in HSS members. A generic LLM gets the units wrong, cites obsolete editions, and fabricates equation numbers. Fine-tuning is the lever that turns the LLM into something an engineer can actually quote.

“A wrong code citation is worse than no answer at all.”

  • Curate the dataset, then tune. AISC’s technical staff produced 2,200+ Q/A pairs grounded in AISC 360-22 and Manual 15th ed., each citing equation/section.
  • Three-tier benchmark — zero-shot GPT-4, few-shot with 6 in-context examples, and full supervised fine-tune on the 2,200 pairs.
  • Citation-required output format. The system prompt forces “answer + AISC 360 section + equation no.” — engineers reject anything without provenance.
Accuracy on held-out steel-design Q/A — zero-shot → few-shot → fine-tuned

Connection design — the hardest category, with the most prequalification rules — is where fine-tuning helps most (48% → 84%).

  • 89% mean accuracy on the held-out test set after fine-tuning — up from 58% zero-shot.
  • Citation correctness 94% when the answer is correct — engineers can verify in one click.
  • Production rollout to AISC members via the AISC website in 2024.
  • Fine-tuning is still the SOTA for narrow code-driven domains; prompt engineering caps out below it.
  • Curated Q/A beats raw text. Throwing the PDF at the model is worse than 2,000 hand-crafted Q/A pairs.
  • Provenance is the product. “Section/equation cited” is what makes the assistant deployable in a design-of-record workflow.