ModelPersistanceManager.swift

ModelPersistenceManager Documentation

Overview

ModelPersistenceManager.swift handles the storage, versioning, and retrieval of trained machine learning models. It manages model files and their associated metadata in the app's document directory.

Core Components

Class Structure

class ModelPersistenceManager {
    private let fileManager: FileManager
    private let modelDirectory: URL
}

Error Types

enum PersistenceError: Error {
    case saveFailed
    case loadFailed
    case modelNotFound
    case invalidModelVersion
}

Metadata Structure

private struct ModelMetadata: Codable {
    let version: String
    let timestamp: Date
}

Primary Features

Directory Management

init() throws
private func createModelDirectoryIfNeeded() throws
  • Initializes the model storage directory

  • Creates necessary directories if they don't exist

  • Handles directory access permissions

Model Management Operations

Saving Models

func saveModel(_ model: MLModel, version: String) throws

Features:

  • Saves model file with version number

  • Creates and stores metadata

  • Handles write errors

  • Updates version tracking

Loading Models

func loadLatestModel() throws -> MLModel
func loadModel(version: String) throws -> MLModel

Features:

  • Loads specific version or latest model

  • Verifies model integrity

  • Handles missing models

  • Validates version compatibility

Metadata Management

private func saveMetadata(_ metadata: ModelMetadata, for version: String) throws
private func loadLatestMetadata() throws -> ModelMetadata

Features:

  • Tracks model versions

  • Stores creation timestamps

  • Manages version history

  • Enables model rollback

File Structure

Directory Layout

MLModels/
├── model_v1.0.mlmodel
├── metadata_v1.0.json
├── model_v1.1.mlmodel
├── metadata_v1.1.json
└── ...

File Naming Convention

  • Models: model_v{version}.mlmodel

  • Metadata: metadata_v{version}.json

Usage Examples

Basic Usage

// Initialize manager
let persistenceManager = try ModelPersistenceManager()

// Save model
try persistenceManager.saveModel(trainedModel, version: "1.0")

// Load latest model
let model = try persistenceManager.loadLatestModel()

// Load specific version
let oldModel = try persistenceManager.loadModel(version: "1.0")

Error Handling Example

do {
    let model = try persistenceManager.loadLatestModel()
} catch PersistenceError.modelNotFound {
    // Handle missing model
} catch PersistenceError.invalidModelVersion {
    // Handle version mismatch
} catch {
    // Handle other errors
}

Best Practices

1. Version Management

  • Use semantic versioning (e.g., "1.0.0")

  • Maintain version history

  • Document version changes

  • Implement rollback capability

2. Storage Management

  • Monitor storage space

  • Clean up old versions

  • Validate file integrity

  • Backup critical models

3. Error Handling

  • Validate before saving

  • Handle corruption cases

  • Provide clear error messages

  • Implement recovery strategies

4. Performance Considerations

  • Efficient file operations

  • Proper memory management

  • Asynchronous loading when appropriate

  • Cache frequently used models

Security Considerations

  1. File Protection

    • Encrypted storage

    • Access control

    • Data integrity checks

    • Secure deletion

  2. Metadata Protection

    • Secure version tracking

    • Protected timestamps

    • Validated updates

    • Audit logging

Integration Points

TrainingDataManager

  • Model versioning alignment

  • Data version tracking

  • Compatibility checking

ModelTrainerService

  • Version management

  • Training history

  • Model evolution

  • Performance tracking

Troubleshooting

Common Issues and Solutions:

  1. Missing Models

    • Check file permissions

    • Verify directory path

    • Validate version numbers

    • Check storage space

  2. Version Conflicts

    • Compare metadata

    • Check version sequence

    • Validate compatibility

    • Review change history

  3. Storage Issues

    • Monitor space usage

    • Implement cleanup

    • Handle corruption

    • Backup strategy

Last updated